code
stringlengths
1
46.1k
label
class label
1.18k classes
domain_label
class label
21 classes
index
stringlengths
4
5
null
219Special characters
8haskell
yis66
void StoogeSort(int a[], int i, int j) { int t; if (a[j] < a[i]) SWAP(a[i], a[j]); if (j - i > 1) { t = (j - i + 1) / 3; StoogeSort(a, i, j - t); StoogeSort(a, i + t, j); StoogeSort(a, i, j - t); } } int main(int argc, char *argv[]) { int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7}; int i, n; n = sizeof(nums)/sizeof(int); StoogeSort(nums, 0, n-1); for(i = 0; i <= n-1; i++) printf(, nums[i]); return 0; }
221Sorting algorithms/Stooge sort
5c
6ow32
(ns sleepsort.core (require [clojure.core.async:as async:refer [chan go <! <!! >! timeout]])) (defn sleep-sort [l] (let [c (chan (count l))] (doseq [i l] (go (<! (timeout (* 1000 i))) (>! c i))) (<!! (async/into [] (async/take (count l) c)))))
220Sorting algorithms/Sleep sort
6clojure
9d0ma
import Data.List.Split (splitOneOf) import Data.Char (chr) toSparkLine :: [Double] -> String toSparkLine xs = map cl xs where top = maximum xs bot = minimum xs range = top - bot cl x = chr $ 0x2581 + floor (min 7 ((x - bot) / range * 8)) makeSparkLine :: String -> (String, Stats) makeSparkLine xs = (toSparkLine parsed, stats parsed) where parsed = map read $ filter (not . null) $ splitOneOf " ," xs data Stats = Stats { minValue, maxValue, rangeOfValues :: Double , numberOfValues :: Int } instance Show Stats where show (Stats mn mx r n) = "min: " ++ show mn ++ "; max: " ++ show mx ++ "; range: " ++ show r ++ "; no. of values: " ++ show n stats :: [Double] -> Stats stats xs = Stats { minValue = mn , maxValue = mx , rangeOfValues = mx - mn , numberOfValues = length xs } where mn = minimum xs mx = maximum xs drawSparkLineWithStats :: String -> IO () drawSparkLineWithStats xs = putStrLn sp >> print st where (sp, st) = makeSparkLine xs main :: IO () main = mapM_ drawSparkLineWithStats [ "0, 1, 19, 20" , "0, 999, 4000, 4999, 7000, 7999" , "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1" , "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5" , "3 2 1 0 -1 -2 -3 -4 -3 -2 -1 0 1 2 3" , "-1000 100 1000 500 200 -400 -700 621 -189 3" ]
217Sparkline in unicode
8haskell
p4ubt
data class Person(val name: String) { val preferences = mutableListOf<Person>() var matchedTo: Person? = null fun trySwap(p: Person) { if (prefers(p)) { matchedTo?.matchedTo = null matchedTo = p p.matchedTo = this } } fun prefers(p: Person) = when (matchedTo) { null -> true else -> preferences.indexOf(p) < preferences.indexOf(matchedTo!!) } fun showMatch() = "$name <=> ${matchedTo?.name}" } fun match(males: Collection<Person>) { while (males.find { it.matchedTo == null }?.also { match(it) } != null) { } } fun match(male: Person) { while (male.matchedTo == null) { male.preferences.removeAt(0).trySwap(male) } } fun isStableMatch(males: Collection<Person>, females: Collection<Person>): Boolean { return males.all { isStableMatch(it, females) } } fun isStableMatch(male: Person, females: Collection<Person>): Boolean { val likesBetter = females.filter { !male.preferences.contains(it) } val stable = !likesBetter.any { it.prefers(male) } if (!stable) { println("#### Unstable pair: ${male.showMatch()}") } return stable } fun main(args: Array<String>) { val inMales = mapOf( "abe" to mutableListOf("abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"), "bob" to mutableListOf("cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"), "col" to mutableListOf("hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"), "dan" to mutableListOf("ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"), "ed" to mutableListOf("jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"), "fred" to mutableListOf("bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"), "gav" to mutableListOf("gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"), "hal" to mutableListOf("abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"), "ian" to mutableListOf("hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"), "jon" to mutableListOf("abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope")) val inFemales = mapOf( "abi" to listOf("bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"), "bea" to listOf("bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"), "cath" to listOf("fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"), "dee" to listOf("fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"), "eve" to listOf("jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"), "fay" to listOf("bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"), "gay" to listOf("jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"), "hope" to listOf("gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"), "ivy" to listOf("ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"), "jan" to listOf("ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan")) fun buildPrefs(person: Person, stringPrefs: List<String>, population: List<Person>) { person.preferences.addAll( stringPrefs.map { name -> population.single { it.name == name } } ) } val males = inMales.keys.map { Person(it) } val females = inFemales.keys.map { Person(it) } males.forEach { buildPrefs(it, inMales[it.name]!!, females) } females.forEach { buildPrefs(it, inFemales[it.name]!!, males) } match(males) males.forEach { println(it.showMatch()) } println("#### match is stable: ${isStableMatch(males, females)}") fun swapMatch(male1: Person, male2: Person) { val female1 = male1.matchedTo!! val female2 = male2.matchedTo!! male1.matchedTo = female2 male2.matchedTo = female1 female1.matchedTo = male2 female2.matchedTo = male1 } swapMatch(males.single { it.name == "fred" }, males.single { it.name == "jon" }) males.forEach { println(it.showMatch()) } println("#### match is stable: ${isStableMatch(males, females)}") }
214Stable marriage problem
11kotlin
p4gb6
public extension String { func splitOnChanges() -> [String] { guard!isEmpty else { return [] } var res = [String]() var workingChar = first! var workingStr = "\(workingChar)" for char in dropFirst() { if char!= workingChar { res.append(workingStr) workingStr = "\(char)" workingChar = char } else { workingStr += String(char) } } res.append(workingStr) return res } } print("gHHH5YY++
210Split a character string based on change of character
17swift
tsnfl
public class Sparkline { String bars=""; public static void main(String[] args) { Sparkline now=new Sparkline(); float[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1}; now.display1D(arr); System.out.println(now.getSparkline(arr)); float[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f}; now.display1D(arr1); System.out.println(now.getSparkline(arr1)); } public void display1D(float[] arr) { for(int i=0;i<arr.length;i++) System.out.print(arr[i]+" "); System.out.println(); } public String getSparkline(float[] arr) { float min=Integer.MAX_VALUE; float max=Integer.MIN_VALUE; for(int i=0;i<arr.length;i++) { if(arr[i]<min) min=arr[i]; if(arr[i]>max) max=arr[i]; } float range=max-min; int num=bars.length()-1; String line=""; for(int i=0;i<arr.length;i++) { line+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num))); } return line; } }
217Sparkline in unicode
9java
rcmg0
local Person = {} Person.__index = Person function Person.new(inName) local o = { name = inName, prefs = nil, fiance = nil, _candidateIndex = 1, } return setmetatable(o, Person) end function Person:indexOf(other) for i, p in pairs(self.prefs) do if p == other then return i end end return 999 end function Person:prefers(other) return self:indexOf(other) < self:indexOf(self.fiance) end function Person:nextCandidateNotYetProposedTo() if self._candidateIndex >= #self.prefs then return nil end local c = self.prefs[self._candidateIndex]; self._candidateIndex = self._candidateIndex + 1 return c; end function Person:engageTo(other) if other.fiance then other.fiance.fiance = nil end other.fiance = self if self.fiance then self.fiance.fiance = nil end self.fiance = other; end local function isStable(men) local women = men[1].prefs local stable = true for _, guy in pairs(men) do for _, gal in pairs(women) do if guy:prefers(gal) and gal:prefers(guy) then stable = false print(guy.name .. ' and ' .. gal.name .. ' prefer each other over their partners ' .. guy.fiance.name .. ' and ' .. gal.fiance.name) end end end return stable end local abe = Person.new("Abe") local bob = Person.new("Bob") local col = Person.new("Col") local dan = Person.new("Dan") local ed = Person.new("Ed") local fred = Person.new("Fred") local gav = Person.new("Gav") local hal = Person.new("Hal") local ian = Person.new("Ian") local jon = Person.new("Jon") local abi = Person.new("Abi") local bea = Person.new("Bea") local cath = Person.new("Cath") local dee = Person.new("Dee") local eve = Person.new("Eve") local fay = Person.new("Fay") local gay = Person.new("Gay") local hope = Person.new("Hope") local ivy = Person.new("Ivy") local jan = Person.new("Jan") abe.prefs = { abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay } bob.prefs = { cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay } col.prefs = { hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan } dan.prefs = { ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi } ed.prefs = { jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay } fred.prefs = { bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay } gav.prefs = { gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay } hal.prefs = { abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee } ian.prefs = { hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve } jon.prefs = { abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope } abi.prefs = { bob, fred, jon, gav, ian, abe, dan, ed, col, hal } bea.prefs = { bob, abe, col, fred, gav, dan, ian, ed, jon, hal } cath.prefs = { fred, bob, ed, gav, hal, col, ian, abe, dan, jon } dee.prefs = { fred, jon, col, abe, ian, hal, gav, dan, bob, ed } eve.prefs = { jon, hal, fred, dan, abe, gav, col, ed, ian, bob } fay.prefs = { bob, abe, ed, ian, jon, dan, fred, gav, col, hal } gay.prefs = { jon, gav, hal, fred, bob, abe, col, ed, dan, ian } hope.prefs = { gav, jon, bob, abe, ian, dan, hal, ed, col, fred } ivy.prefs = { ian, col, hal, gav, fred, bob, abe, ed, jon, dan } jan.prefs = { ed, hal, gav, abe, bob, jon, col, ian, fred, dan } local men = abi.prefs local freeMenCount = #men while freeMenCount > 0 do for _, guy in pairs(men) do if not guy.fiance then local gal = guy:nextCandidateNotYetProposedTo() if not gal.fiance then guy:engageTo(gal) freeMenCount = freeMenCount - 1 elseif gal:prefers(guy) then guy:engageTo(gal) end end end end print(' ') for _, guy in pairs(men) do print(guy.name .. ' is engaged to ' .. guy.fiance.name) end print('Stable: ', isStable(men)) print(' ') print('Switching ' .. fred.name .. "'s & " .. jon.name .. "'s partners") jon.fiance, fred.fiance = fred.fiance, jon.fiance print('Stable: ', isStable(men))
214Stable marriage problem
1lua
1grpo
(() => { 'use strict'; const main = () => {
217Sparkline in unicode
10javascript
b5vki
use English; $. $INPUT_LINE_NUMBER $, $OUTPUT_FIELD_SEPARATOR $; $SUBSCRIPT_SEPARATOR $_ $ARG $" $LIST_SEPARATOR $+ $LAST_PAREN_MATCH $0 $PROGRAM_NAME $! $ERRNO $@ $EVAL_ERROR $/ $INPUT_RECORD_SEPARATOR $\ $OUTPUT_RECORD_SEPARATOR $| $OUTPUT_AUTOFLUSH $& $MATCH $' $POSTMATCH $` $PREMATCH @ARGV @F @INC %ENV %SIG
215Special variables
2perl
4mm5d
& | ^ ~
219Special characters
9java
dx1n9
^[a-zA-Z_][a-zA-Z_0-9]*$
219Special characters
10javascript
6oq38
(defn swap [v x y] (assoc! v y (v x) x (v y))) (defn stooge-sort ([v] (persistent! (stooge-sort (transient v) 0 (dec (count v))))) ([v i j] (if (> (v i) (v j)) (swap v i j) v) (if (> (- j i) 1) (let [t (int (Math/floor (/ (inc (- j i)) 3)))] (stooge-sort v i (- j t)) (stooge-sort v (+ i t) j) (stooge-sort v i (- j t)))) v))
221Sorting algorithms/Stooge sort
6clojure
lt8cb
void main() async { Future<void> sleepsort(Iterable<int> input) => Future.wait(input .map((i) => Future.delayed(Duration(milliseconds: i), () => print(i)))); await sleepsort([3, 10, 2, 120, 122, 121, 54]); }
220Sorting algorithms/Sleep sort
18dart
oah8s
internal const val bars = "" internal const val n = bars.length - 1 fun <T: Number> Iterable<T>.toSparkline(): String { var min = Double.MAX_VALUE var max = Double.MIN_VALUE val doubles = map { it.toDouble() } doubles.forEach { i -> when { i < min -> min = i; i > max -> max = i } } val range = max - min return doubles.fold("") { line, d -> line + bars[Math.ceil((d - min) / range * n).toInt()] } } fun String.toSparkline() = replace(",", "").split(" ").map { it.toFloat() }.toSparkline() fun main(args: Array<String>) { val s1 = "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1" println(s1) println(s1.toSparkline()) val s2 = "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5" println(s2) println(s2.toSparkline()) }
217Sparkline in unicode
11kotlin
v3t21
use strict; use warnings; use feature 'say'; sub merge { my ($x, $y) = @_; my @out; while (@$x and @$y) { my $t = $x->[-1] <=> $y->[-1]; if ($t == 1) { unshift @out, pop @$x } elsif ($t == -1) { unshift @out, pop @$y } else { splice @out, 0, 0, pop(@$x), pop(@$y) } } @$x, @$y, @out } sub strand { my $x = shift; my @out = shift @$x // return; for (-@$x .. -1) { push @out, splice @$x, $_, 1 if $x->[$_] >= $out[-1]; } @out } sub strand_sort { my @x = @_; my(@out, @strand); @out = merge \@out, \@strand while @strand = strand(\@x); @out } my @a = map (int rand(100), 1 .. 10); say "Before @a"; @a = strand_sort(@a); say "After @a";
216Sorting algorithms/Strand sort
2perl
wj7e6
typedef int(*cmp_func)(const void*, const void*); void perm_sort(void *a, int n, size_t msize, cmp_func _cmp) { char *p, *q, *tmp = malloc(msize); memcpy(tmp, a, msize);\ memcpy(a, b, msize);\ memcpy(b, tmp, msize); } while (1) { for (p = A(n - 1); (void*)p > a; p = q) if (_cmp(q = p - msize, p) > 0) break; if ((void*)p <= a) break; for (p = A(n - 1); p > q; p-= msize) if (_cmp(q, p) > 0) break; swap(p, q); for (q += msize, p = A(n - 1); q < p; q += msize, p -= msize) swap(p, q); } free(tmp); } int scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); } int main() { int i; const char *strs[] = { , , , , }; perm_sort(strs, 5, sizeof(*strs), scmp); for (i = 0; i < 5; i++) printf(, strs[i]); return 0; }
222Sorting algorithms/Permutation sort
5c
lt0cy
# defined local ie. #mylocal will fail if not defined $ defined variable ie. $myvar will fail if not defined = assignment := assign as return assigned value ? ternary conditional true? this | ternary else false? this | that || or && and ! negative operator { open capture } close capture => specify givenblock / capture -> invoke method: mytype->mymethod & retarget: mytype->mymethod&
219Special characters
11kotlin
0pjsf
void shell_sort (int *a, int n) { int h, i, j, t; for (h = n; h /= 2;) { for (i = h; i < n; i++) { t = a[i]; for (j = i; j >= h && t < a[j - h]; j -= h) { a[j] = a[j - h]; } a[j] = t; } } } int main (int ac, char **av) { int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; int n = sizeof a / sizeof a[0]; int i; for (i = 0; i < n; i++) printf(, a[i], i == n - 1 ? : ); shell_sort(a, n); for (i = 0; i < n; i++) printf(, a[i], i == n - 1 ? : ); return 0; }
223Sorting algorithms/Shell sort
5c
7ltrg
var intStack []int
212Stack
0go
4ml52
names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split())) print( '\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) )
215Special variables
3python
g994h
$lst = new SplDoublyLinkedList(); foreach (array(1,20,64,72,48,75,96,55,42,74) as $v) $lst->push($v); foreach (strandSort($lst) as $v) echo ; function strandSort(SplDoublyLinkedList $lst) { $result = new SplDoublyLinkedList(); while (!$lst->isEmpty()) { $sorted = new SplDoublyLinkedList(); $remain = new SplDoublyLinkedList(); $sorted->push($lst->shift()); foreach ($lst as $item) { if ($sorted->top() <= $item) { $sorted->push($item); } else { $remain->push($item); } } $result = _merge($sorted, $result); $lst = $remain; } return $result; } function _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) { $res = new SplDoublyLinkedList(); while (!$left->isEmpty() && !$right->isEmpty()) { if ($left->bottom() <= $right->bottom()) { $res->push($left->shift()); } else { $res->push($right->shift()); } } foreach ($left as $v) $res->push($v); foreach ($right as $v) $res->push($v); return $res; }
216Sorting algorithms/Strand sort
12php
ltfcj
use strict; use warnings; use feature qw/say/; use List::Util qw(first); my %Likes = ( M => { abe => [qw/ abi eve cath ivy jan dee fay bea hope gay /], bob => [qw/ cath hope abi dee eve fay bea jan ivy gay /], col => [qw/ hope eve abi dee bea fay ivy gay cath jan /], dan => [qw/ ivy fay dee gay hope eve jan bea cath abi /], ed => [qw/ jan dee bea cath fay eve abi ivy hope gay /], fred => [qw/ bea abi dee gay eve ivy cath jan hope fay /], gav => [qw/ gay eve ivy bea cath abi dee hope jan fay /], hal => [qw/ abi eve hope fay ivy cath jan bea gay dee /], ian => [qw/ hope cath dee gay bea abi fay ivy jan eve /], jon => [qw/ abi fay jan gay eve bea dee cath ivy hope /], }, W => { abi => [qw/ bob fred jon gav ian abe dan ed col hal /], bea => [qw/ bob abe col fred gav dan ian ed jon hal /], cath => [qw/ fred bob ed gav hal col ian abe dan jon /], dee => [qw/ fred jon col abe ian hal gav dan bob ed /], eve => [qw/ jon hal fred dan abe gav col ed ian bob /], fay => [qw/ bob abe ed ian jon dan fred gav col hal /], gay => [qw/ jon gav hal fred bob abe col ed dan ian /], hope => [qw/ gav jon bob abe ian dan hal ed col fred /], ivy => [qw/ ian col hal gav fred bob abe ed jon dan /], jan => [qw/ ed hal gav abe bob jon col ian fred dan /], }, ); my %Engaged; my %Proposed; match_them(); check_stability(); perturb(); check_stability(); sub match_them { say 'Matchmaking:'; while(my $man = unmatched_man()) { my $woman = preferred_choice($man); $Proposed{$man}{$woman} = 1; if(! $Engaged{W}{$woman}) { engage($man, $woman); say "\t$woman and $man"; } else { if(woman_prefers($woman, $man)) { my $engaged_man = $Engaged{W}{$woman}; engage($man, $woman); undef $Engaged{M}{$engaged_man}; say "\t$woman dumped $engaged_man for $man"; } } } } sub check_stability { say 'Stablility:'; my $stable = 1; foreach my $m (men()) { foreach my $w (women()) { if(man_prefers($m, $w) && woman_prefers($w, $m)) { say "\t$w prefers $m to $Engaged{W}{$w} and $m prefers $w to $Engaged{M}{$m}"; $stable = 0; } } } if($stable) { say "\t(all marriages stable)"; } } sub unmatched_man { return first { ! $Engaged{M}{$_} } men(); } sub preferred_choice { my $man = shift; return first { ! $Proposed{$man}{$_} } @{ $Likes{M}{$man} }; } sub engage { my ($man, $woman) = @_; $Engaged{W}{$woman} = $man; $Engaged{M}{$man} = $woman; } sub prefers { my $sex = shift; return sub { my ($person, $prospect) = @_; my $choices = join ' ', @{ $Likes{$sex}{$person} }; return index($choices, $prospect) < index($choices, $Engaged{$sex}{$person}); } } BEGIN { *woman_prefers = prefers('W'); *man_prefers = prefers('M'); } sub perturb { say 'Perturb:'; say "\tengage abi with fred and bea with jon"; engage('fred' => 'abi'); engage('jon' => 'bea'); } sub men { keys %{ $Likes{M} } } sub women { keys %{ $Likes{W} } }
214Stable marriage problem
2perl
yin6u
def stack = [] assert stack.empty stack.push(55) stack.push(21) stack.push('kittens') assert stack.last() == 'kittens' assert stack.size() == 3 assert ! stack.empty println stack assert stack.pop() == "kittens" assert stack.size() == 2 println stack stack.push(-20) println stack stack.push( stack.pop() * stack.pop() ) assert stack.last() == -420 assert stack.size() == 2 println stack stack.push(stack.pop() / stack.pop()) assert stack.size() == 1 println stack println stack.pop() assert stack.size() == 0 assert stack.empty try { stack.pop() } catch (NoSuchElementException e) { println e.message }
212Stack
7groovy
lt6c1
Markup: () Sequence {} List " String \ Escape for following character (* *) Comment block base^^number`s ` Context [[]] Indexed reference Within expression: \ At end of line: Continue on next line, skipping white space
219Special characters
1lua
81h0e
type Stack a = [a] create :: Stack a create = [] push :: a -> Stack a -> Stack a push = (:) pop :: Stack a -> (a, Stack a) pop [] = error "Stack empty" pop (x:xs) = (x,xs) empty :: Stack a -> Bool empty = null peek :: Stack a -> a peek [] = error "Stack empty" peek (x:_) = x
212Stack
8haskell
qk1x9
package main import ( "fmt" "strconv" ) var n = 5 func main() { if n < 1 { return } top, left, bottom, right := 0, 0, n-1, n-1 sz := n * n a := make([]int, sz) i := 0 for left < right {
218Spiral matrix
0go
wjgeg
(use '[clojure.contrib.combinatorics :only (permutations)]) (defn permutation-sort [s] (first (filter (partial apply <=) (permutations s)))) (permutation-sort [2 3 5 3 5])
222Sorting algorithms/Permutation sort
6clojure
4md5o
static char code[128] = { 0 }; void add_code(const char *s, int c) { while (*s) { code[(int)*s] = code[0x20 ^ (int)*s] = c; s++; } } void init() { static const char *cls[] = { , , , , , , , , 0}; int i; for (i = 0; cls[i]; i++) add_code(cls[i], i - 1); } const char* soundex(const char *s) { static char out[5]; int c, prev, i; out[0] = out[4] = 0; if (!s || !*s) return out; out[0] = *s++; prev = code[(int)out[0]]; for (i = 1; *s && i < 4; s++) { if ((c = code[(int)*s]) == prev) continue; if (c == -1) prev = 0; else if (c > 0) { out[i++] = c + '0'; prev = c; } } while (i < 4) out[i++] = '0'; return out; } int main() { int i; const char *sdx, *names[][2] = { {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {, }, {0, 0} }; init(); puts(); for (i = 0; names[i][0]; i++) { sdx = soundex(names[i][0]); printf(, names[i][0], names[i][1], sdx); printf(, strcmp(sdx, names[i][1]) ? : ); } return 0; }
224Soundex
5c
fqhd3
enum Direction { East([0,1]), South([1,0]), West([0,-1]), North([-1,0]); private static _n private final stepDelta private bound private Direction(delta) { stepDelta = delta } public static setN(int n) { Direction._n = n North.bound = 0 South.bound = n-1 West.bound = 0 East.bound = n-1 } public List move(i, j) { def dir = this def newIJDir = [[i,j],stepDelta].transpose().collect { it.sum() } + dir if (((North.bound)..(South.bound)).contains(newIJDir[0]) && ((West.bound)..(East.bound)).contains(newIJDir[1])) { newIJDir } else { (++dir).move(i, j) } } public Object next() { switch (this) { case North: West.bound++; return East; case East: North.bound++; return South; case South: East.bound--; return West; case West: South.bound--; return North; } } } def spiralMatrix = { n -> if (n < 1) return [] def M = (0..<n).collect { [0]*n } def i = 0 def j = 0 Direction.n = n def dir = Direction.East (0..<(n**2)).each { k -> M[i][j] = k (i,j,dir) = (k < (n**2 - 1)) \ ? dir.move(i,j) \ : [i,j,dir] } M }
218Spiral matrix
7groovy
b52ky
import scala._ import scala.{ Predef => _, _ } def f[M[_]] def f(m: M[_]) _ + _ m _ m(_) _ => 5 case _ => val (a, _) = (1, 2) for (_ <- 1 to 10) f(xs: _*) case Seq(xs @ _*) var i: Int = _ def abc_<>! t._2 var i: Int = _ for (_ <- 1 to 10) doIt() def f: T; def f_=(t: T)
215Special variables
14ruby
7llri
import scala._
215Special variables
16scala
b55k6
package main import ( "fmt" "log" "os" "strconv" "time" ) func main() { out := make(chan uint64) for _, a := range os.Args[1:] { i, err := strconv.ParseUint(a, 10, 64) if err != nil { log.Fatal(err) } go func(n uint64) { time.Sleep(time.Duration(n) * time.Millisecond) out <- n }(i) } for _ = range os.Args[1:] { fmt.Println(<-out) } }
220Sorting algorithms/Sleep sort
0go
ku9hz
@Grab(group = 'org.codehaus.gpars', module = 'gpars', version = '1.2.1') import groovyx.gpars.GParsPool GParsPool.withPool args.size(), { args.eachParallel { sleep(it.toInteger() * 10) println it } }
220Sorting algorithms/Sleep sort
7groovy
g9z46
binmode(STDOUT, ":utf8"); our @sparks=map {chr} 0x2581 .. 0x2588; sub sparkline(@) { my @n=map {0+$_} grep {length} @_ or return ""; my($min,$max)=($n[0])x2; if (@n>1) { for (@n[1..$ if ($_<$min) { $min=$_ } elsif ($_>$max) { $max=$_ } } } my $sparkline=""; for(@n) { my $height=int( $max==$min ? @sparks/2 : ($_-$min)/($max-$min)*@sparks ); $height=$ $sparkline.=$sparks[$height]; } my $summary=sprintf "%d values; range%s..%s", scalar(@n), $min, $max; return wantarray ? ($summary, "\n", $sparkline, "\n") : $sparkline; } print sparkline( split /[\s,]+/ ) while <>;
217Sparkline in unicode
2perl
0pks4
def merge_list(a, b): out = [] while len(a) and len(b): if a[0] < b[0]: out.append(a.pop(0)) else: out.append(b.pop(0)) out += a out += b return out def strand(a): i, s = 0, [a.pop(0)] while i < len(a): if a[i] > s[-1]: s.append(a.pop(i)) else: i += 1 return s def strand_sort(a): out = strand(a) while len(a): out = merge_list(out, strand(a)) return out print strand_sort([1, 6, 3, 2, 1, 7, 5, 3])
216Sorting algorithms/Strand sort
3python
xhjwr
import Data.List import Control.Monad grade xs = map snd. sort $ zip xs [0..] values n = cycle [1,n,-1,-n] counts n = (n:).concatMap (ap (:) return) $ [n-1,n-2..1] reshape n = unfoldr (\xs -> if null xs then Nothing else Just (splitAt n xs)) spiral n = reshape n . grade. scanl1 (+). concat $ zipWith replicate (counts n) (values n) displayRow = putStrLn . intercalate " " . map show main = mapM displayRow $ spiral 5
218Spiral matrix
8haskell
6os3k
import System.Environment import Control.Concurrent import Control.Monad sleepSort :: [Int] -> IO () sleepSort values = do chan <- newChan forM_ values (\time -> forkIO (threadDelay (50000 * time) >> writeChan chan time)) forM_ values (\_ -> readChan chan >>= print) main :: IO () main = getArgs >>= sleepSort . map read
220Sorting algorithms/Sleep sort
8haskell
nwbie
static void swap(unsigned *a, unsigned *b) { unsigned tmp = *a; *a = *b; *b = tmp; } static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit) { if (!bit || to < from + 1) return; unsigned *ll = from, *rr = to - 1; for (;;) { while (ll < rr && !(*ll & bit)) ll++; while (ll < rr && (*rr & bit)) rr--; if (ll >= rr) break; swap(ll, rr); } if (!(bit & *ll) && ll < to) ll++; bit >>= 1; rad_sort_u(from, ll, bit); rad_sort_u(ll, to, bit); } static void radix_sort(int *a, const size_t len) { size_t i; unsigned *x = (unsigned*) a; for (i = 0; i < len; i++) x[i] ^= INT_MIN; rad_sort_u(x, x + len, INT_MIN); for (i = 0; i < len; i++) x[i] ^= INT_MIN; } int main(void) { srand(time(NULL)); int x[16]; for (size_t i = 0; i < ARR_LEN(x); i++) x[i] = RAND_RNG(-128,127) radix_sort(x, ARR_LEN(x)); for (size_t i = 0; i < ARR_LEN(x); i++) printf(, x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n'); }
225Sorting algorithms/Radix sort
5c
0pust
import java.util.concurrent.CountDownLatch; public class SleepSort { public static void sleepSortAndPrint(int[] nums) { final CountDownLatch doneSignal = new CountDownLatch(nums.length); for (final int num: nums) { new Thread(new Runnable() { public void run() { doneSignal.countDown(); try { doneSignal.await();
220Sorting algorithms/Sleep sort
9java
qkgxa
void main() { List<int> a = shellSort([1100, 2, 56, 200, -52, 3, 99, 33, 177, -199]); print('$a'); } shellSort(List<int> array) { int n = array.length;
223Sorting algorithms/Shell sort
18dart
v382j
bar = '' barcount = len(bar) def sparkline(numbers): mn, mx = min(numbers), max(numbers) extent = mx - mn sparkline = ''.join(bar[min([barcount - 1, int((n - mn) / extent * barcount)])] for n in numbers) return mn, mx, sparkline if __name__ == '__main__': import re for line in ( ).split(';'): print(, line) numbers = [float(n) for n in re.split(r'[\s,]+', line.strip())] mn, mx, sp = sparkline(numbers) print(' min:%5f; max:%5f'% (mn, mx)) print( + sp)
217Sparkline in unicode
3python
81b0o
import copy guyprefers = { 'abe': ['abi', 'eve', 'cath', 'ivy', 'jan', 'dee', 'fay', 'bea', 'hope', 'gay'], 'bob': ['cath', 'hope', 'abi', 'dee', 'eve', 'fay', 'bea', 'jan', 'ivy', 'gay'], 'col': ['hope', 'eve', 'abi', 'dee', 'bea', 'fay', 'ivy', 'gay', 'cath', 'jan'], 'dan': ['ivy', 'fay', 'dee', 'gay', 'hope', 'eve', 'jan', 'bea', 'cath', 'abi'], 'ed': ['jan', 'dee', 'bea', 'cath', 'fay', 'eve', 'abi', 'ivy', 'hope', 'gay'], 'fred': ['bea', 'abi', 'dee', 'gay', 'eve', 'ivy', 'cath', 'jan', 'hope', 'fay'], 'gav': ['gay', 'eve', 'ivy', 'bea', 'cath', 'abi', 'dee', 'hope', 'jan', 'fay'], 'hal': ['abi', 'eve', 'hope', 'fay', 'ivy', 'cath', 'jan', 'bea', 'gay', 'dee'], 'ian': ['hope', 'cath', 'dee', 'gay', 'bea', 'abi', 'fay', 'ivy', 'jan', 'eve'], 'jon': ['abi', 'fay', 'jan', 'gay', 'eve', 'bea', 'dee', 'cath', 'ivy', 'hope']} galprefers = { 'abi': ['bob', 'fred', 'jon', 'gav', 'ian', 'abe', 'dan', 'ed', 'col', 'hal'], 'bea': ['bob', 'abe', 'col', 'fred', 'gav', 'dan', 'ian', 'ed', 'jon', 'hal'], 'cath': ['fred', 'bob', 'ed', 'gav', 'hal', 'col', 'ian', 'abe', 'dan', 'jon'], 'dee': ['fred', 'jon', 'col', 'abe', 'ian', 'hal', 'gav', 'dan', 'bob', 'ed'], 'eve': ['jon', 'hal', 'fred', 'dan', 'abe', 'gav', 'col', 'ed', 'ian', 'bob'], 'fay': ['bob', 'abe', 'ed', 'ian', 'jon', 'dan', 'fred', 'gav', 'col', 'hal'], 'gay': ['jon', 'gav', 'hal', 'fred', 'bob', 'abe', 'col', 'ed', 'dan', 'ian'], 'hope': ['gav', 'jon', 'bob', 'abe', 'ian', 'dan', 'hal', 'ed', 'col', 'fred'], 'ivy': ['ian', 'col', 'hal', 'gav', 'fred', 'bob', 'abe', 'ed', 'jon', 'dan'], 'jan': ['ed', 'hal', 'gav', 'abe', 'bob', 'jon', 'col', 'ian', 'fred', 'dan']} guys = sorted(guyprefers.keys()) gals = sorted(galprefers.keys()) def check(engaged): inverseengaged = dict((v,k) for k,v in engaged.items()) for she, he in engaged.items(): shelikes = galprefers[she] shelikesbetter = shelikes[:shelikes.index(he)] helikes = guyprefers[he] helikesbetter = helikes[:helikes.index(she)] for guy in shelikesbetter: guysgirl = inverseengaged[guy] guylikes = guyprefers[guy] if guylikes.index(guysgirl) > guylikes.index(she): print( % (she, guy, he, guysgirl)) return False for gal in helikesbetter: girlsguy = engaged[gal] gallikes = galprefers[gal] if gallikes.index(girlsguy) > gallikes.index(he): print( % (he, gal, she, girlsguy)) return False return True def matchmaker(): guysfree = guys[:] engaged = {} guyprefers2 = copy.deepcopy(guyprefers) galprefers2 = copy.deepcopy(galprefers) while guysfree: guy = guysfree.pop(0) guyslist = guyprefers2[guy] gal = guyslist.pop(0) fiance = engaged.get(gal) if not fiance: engaged[gal] = guy print(% (guy, gal)) else: galslist = galprefers2[gal] if galslist.index(fiance) > galslist.index(guy): engaged[gal] = guy print(% (gal, fiance, guy)) if guyprefers2[fiance]: guysfree.append(fiance) else: if guyslist: guysfree.append(guy) return engaged print('\nEngagements:') engaged = matchmaker() print('\nCouples:') print(' ' + ',\n '.join('%s is engaged to%s'% couple for couple in sorted(engaged.items()))) print() print('Engagement stability check PASSED' if check(engaged) else 'Engagement stability check FAILED') print('\n\nSwapping two fiances to introduce an error') engaged[gals[0]], engaged[gals[1]] = engaged[gals[1]], engaged[gals[0]] for gal in gals[:2]: print(' %s is now engaged to%s'% (gal, engaged[gal])) print() print('Engagement stability check PASSED' if check(engaged) else 'Engagement stability check FAILED')
214Stable marriage problem
3python
mndyh
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) stoogesort(a) fmt.Println("after: ", a) fmt.Println("nyuk nyuk nyuk") } func stoogesort(a []int) { last := len(a) - 1 if a[last] < a[0] { a[0], a[last] = a[last], a[0] } if last > 1 { t := len(a) / 3 stoogesort(a[:len(a)-t]) stoogesort(a[t:]) stoogesort(a[:len(a)-t]) } }
221Sorting algorithms/Stooge sort
0go
p4cbg
Array.prototype.timeoutSort = function (f) { this.forEach(function (n) { setTimeout(function () { f(n) }, 5 * n) }); }
220Sorting algorithms/Sleep sort
10javascript
iekol
bars <- intToUtf8(seq(0x2581, 0x2588), multiple = T) n_chars <- length(bars) sparkline <- function(numbers) { mn <- min(numbers) mx <- max(numbers) interval <- mx - mn bins <- sapply( numbers, function(i) bars[[1 + min(n_chars - 1, floor((i - mn) / interval * n_chars))]] ) sparkline <- paste0(bins, collapse = "") return(sparkline) } sparkline(c(1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1)) sparkline(c(1.5, 0.5, 3.5, 2.5, 5.5, 4.5, 7.5, 6.5)) sparkline(c(0, 999, 4000, 4999, 7000, 7999)) sparkline(c(0, 0, 1, 1)) sparkline(c(0, 1, 19, 20))
217Sparkline in unicode
13r
xh7w2
class Array def strandsort a = dup result = [] until a.empty? v = a.first sublist, a = a.partition{|val| v=val if v<=val} result.each_index do |idx| break if sublist.empty? result.insert(idx, sublist.shift) if sublist.first < result[idx] end result += sublist end result end def strandsort! replace(strandsort) end end p [1, 6, 3, 2, 1, 7, 5, 3].strandsort
216Sorting algorithms/Strand sort
14ruby
sbkqw
Delimiters Operators , =:= ==!= < <= > >= @= @== @!= @< @<= @> @>= + - * / += -= *= /= @+= @-= @*= @/= .. & &=?;: | Braces ()[]{} BlockComment /* */ --/* --*/ LineComment -- TokenStart abcedfghijklmnopqrstuvwxyz TokenStart ABCDEFGHIJKLMNOPQRSTUVWXYZ_ TokenChar 0123456789 Escapes \rnt\'"eE
219Special characters
2perl
5ytu2
import Data.List import Control.Arrow import Control.Monad insertAt e k = uncurry(++).second ((e:).drop 1). splitAt k swapElems :: [a] -> Int -> Int -> [a] swapElems xs i j = insertAt (xs!!j) i $ insertAt (xs!!i) j xs stoogeSort [] = [] stoogeSort [x] = [x] stoogeSort xs = doss 0 (length xs - 1) xs doss :: (Ord a) => Int -> Int -> [a] -> [a] doss i j xs | j-i>1 = doss i (j-t) $ doss (i+t) j $ doss i (j-t) xs' | otherwise = xs' where t = (j-i+1)`div`3 xs' | xs!!j < xs!!i = swapElems xs i j | otherwise = xs
221Sorting algorithms/Stooge sort
8haskell
fqpd1
null
220Sorting algorithms/Sleep sort
11kotlin
1g2pd
void selection_sort (int *a, int n) { int i, j, m, t; for (i = 0; i < n; i++) { for (j = i, m = i; j < n; j++) { if (a[j] < a[m]) { m = j; } } t = a[i]; a[i] = a[m]; a[m] = t; } } int main () { int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1}; int n = sizeof a / sizeof a[0]; int i; for (i = 0; i < n; i++) printf(, a[i], i == n - 1 ? : ); selection_sort(a, n); for (i = 0; i < n; i++) printf(, a[i], i == n - 1 ? : ); return 0; }
226Sorting algorithms/Selection sort
5c
dxrnv
(defn get-code [c] (case c (\B \F \P \V) 1 (\C \G \J \K \Q \S \X \Z) 2 (\D \T) 3 \L 4 (\M \N) 5 \R 6 nil)) (defn soundex [s] (let [[f & s] (.toUpperCase s)] (-> (map get-code s) distinct (concat , "0000") (->> (cons f ,) (remove nil? ,) (take 4 ,) (apply str ,)))))
224Soundex
6clojure
yia6b
import java.util.Stack; public class StackTest { public static void main( final String[] args ) { final Stack<String> stack = new Stack<String>(); System.out.println( "New stack empty? " + stack.empty() ); stack.push( "There can be only one" ); System.out.println( "Pushed stack empty? " + stack.empty() ); System.out.println( "Popped single entry: " + stack.pop() ); stack.push( "First" ); stack.push( "Second" ); System.out.println( "Popped entry should be second: " + stack.pop() );
212Stack
9java
p47b3
public class Blah { public static void main(String[] args) { print2dArray(getSpiralArray(5)); } public static int[][] getSpiralArray(int dimension) { int[][] spiralArray = new int[dimension][dimension]; int numConcentricSquares = (int) Math.ceil((dimension) / 2.0); int j; int sideLen = dimension; int currNum = 0; for (int i = 0; i < numConcentricSquares; i++) {
218Spiral matrix
9java
nw1ih
function sleeprint(n) local t0 = os.time() while os.time() - t0 <= n do coroutine.yield(false) end print(n) return true end coroutines = {} for i=1, #arg do wrapped = coroutine.wrap(sleeprint) table.insert(coroutines, wrapped) wrapped(tonumber(arg[i])) end done = false while not done do done = true for i=#coroutines,1,-1 do if coroutines[i]() then table.remove(coroutines, i) else done = false end end end
220Sorting algorithms/Sleep sort
1lua
arv1v
var stack = []; stack.push(1) stack.push(2,3); print(stack.pop());
212Stack
10javascript
xhpw9
spiralArray = function (edge) { var arr = Array(edge), x = 0, y = edge, total = edge * edge--, dx = 1, dy = 0, i = 0, j = 0; while (y) arr[--y] = []; while (i < total) { arr[y][x] = i++; x += dx; y += dy; if (++j == edge) { if (dy < 0) {x++; y++; edge -= 2} j = dx; dx = -dy; dy = j; j = 0; } } return arr; }
218Spiral matrix
10javascript
38qz0
int* patienceSort(int* arr,int size){ int decks[size][size],i,j,min,pickedRow; int *count = (int*)calloc(sizeof(int),size),*sortedArr = (int*)malloc(size*sizeof(int)); for(i=0;i<size;i++){ for(j=0;j<size;j++){ if(count[j]==0 || (count[j]>0 && decks[j][count[j]-1]>=arr[i])){ decks[j][count[j]] = arr[i]; count[j]++; break; } } } min = decks[0][count[0]-1]; pickedRow = 0; for(i=0;i<size;i++){ for(j=0;j<size;j++){ if(count[j]>0 && decks[j][count[j]-1]<min){ min = decks[j][count[j]-1]; pickedRow = j; } } sortedArr[i] = min; count[pickedRow]--; for(j=0;j<size;j++) if(count[j]>0){ min = decks[j][count[j]-1]; pickedRow = j; break; } } free(count); free(decks); return sortedArr; } int main(int argC,char* argV[]) { int *arr, *sortedArr, i; if(argC==0) printf(); else{ arr = (int*)malloc((argC-1)*sizeof(int)); for(i=1;i<=argC;i++) arr[i-1] = atoi(argV[i]); sortedArr = patienceSort(arr,argC-1); for(i=0;i<argC-1;i++) printf(,sortedArr[i]); } return 0; }
227Sorting algorithms/Patience sort
5c
e7yav
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66}
222Sorting algorithms/Permutation sort
0go
xhuwf
bar = (''..'').to_a loop {print 'Numbers please separated by space/commas: ' numbers = gets.split(/[\s,]+/).map(&:to_f) min, max = numbers.minmax puts % [min, max] div = (max - min) / (bar.size - 1) puts min == max? bar.last*numbers.size: numbers.map{|num| bar[((num - min) / div).to_i]}.join }
217Sparkline in unicode
14ruby
ie1oh
const BARS: &'static str = ""; fn print_sparkline(s: &str){ let v = BARS.chars().collect::<Vec<char>>(); let line: String = s.replace(",", " ").split(" ") .filter(|x|!x.is_empty()) .map(|x| v[x.parse::<f64>().unwrap().ceil() as usize - 1]) .collect(); println!("{:?}", line); } fn main(){ let s1 = "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1"; print_sparkline(s1); let s2 = "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5"; print_sparkline(s2); }
217Sparkline in unicode
15rust
nwai4
class Person def initialize(name) @name = name @fiance = nil @preferences = [] @proposals = [] end attr_reader :name, :proposals attr_accessor :fiance, :preferences def to_s @name end def free @fiance = nil end def single? @fiance == nil end def engage(person) self.fiance = person person.fiance = self end def better_choice?(person) @preferences.index(person) < @preferences.index(@fiance) end def propose_to(person) puts if $DEBUG @proposals << person person.respond_to_proposal_from(self) end def respond_to_proposal_from(person) if single? puts if $DEBUG engage(person) elsif better_choice?(person) puts if $DEBUG @fiance.free engage(person) else puts if $DEBUG end end end prefs = { 'abe' => %w[abi eve cath ivy jan dee fay bea hope gay], 'bob' => %w[cath hope abi dee eve fay bea jan ivy gay], 'col' => %w[hope eve abi dee bea fay ivy gay cath jan], 'dan' => %w[ivy fay dee gay hope eve jan bea cath abi], 'ed' => %w[jan dee bea cath fay eve abi ivy hope gay], 'fred' => %w[bea abi dee gay eve ivy cath jan hope fay], 'gav' => %w[gay eve ivy bea cath abi dee hope jan fay], 'hal' => %w[abi eve hope fay ivy cath jan bea gay dee], 'ian' => %w[hope cath dee gay bea abi fay ivy jan eve], 'jon' => %w[abi fay jan gay eve bea dee cath ivy hope], 'abi' => %w[bob fred jon gav ian abe dan ed col hal], 'bea' => %w[bob abe col fred gav dan ian ed jon hal], 'cath' => %w[fred bob ed gav hal col ian abe dan jon], 'dee' => %w[fred jon col abe ian hal gav dan bob ed], 'eve' => %w[jon hal fred dan abe gav col ed ian bob], 'fay' => %w[bob abe ed ian jon dan fred gav col hal], 'gay' => %w[jon gav hal fred bob abe col ed dan ian], 'hope' => %w[gav jon bob abe ian dan hal ed col fred], 'ivy' => %w[ian col hal gav fred bob abe ed jon dan], 'jan' => %w[ed hal gav abe bob jon col ian fred dan], } @men = Hash[ %w[abe bob col dan ed fred gav hal ian jon].collect do |name| [name, Person.new(name)] end ] @women = Hash[ %w[abi bea cath dee eve fay gay hope ivy jan].collect do |name| [name, Person.new(name)] end ] @men.each {|name, man| man.preferences = @women.values_at(*prefs[name])} @women.each {|name, woman| woman.preferences = @men.values_at(*prefs[name])} def match_couples(men, women) men.each_value {|man| man.free} women.each_value {|woman| woman.free} while m = men.values.find {|man| man.single?} do puts if $DEBUG w = m.preferences.find {|woman| not m.proposals.include?(woman)} m.propose_to(w) end end match_couples @men, @women @men.each_value.collect {|man| puts } class Person def more_preferable_people ( @preferences.partition {|p| better_choice?(p)} ).first end end require 'set' def stability(men) unstable = Set.new men.each_value do |man| woman = man.fiance puts if $DEBUG man.more_preferable_people.each do |other_woman| if other_woman.more_preferable_people.include?(man) puts if $DEBUG unstable << [man, other_woman] end end woman.more_preferable_people.each do |other_man| if other_man.more_preferable_people.include?(woman) puts if $DEBUG unstable << [other_man, woman] end end end if unstable.empty? puts else puts unstable.each do |a,b| puts end end end stability @men puts def swap(m1, m2) w1 = m1.fiance w2 = m2.fiance m1.fiance = w2 w1.fiance = m2 m2.fiance = w1 w2.fiance = m1 end swap *@men.values_at('abe','bob') @men.each_value.collect {|man| puts } stability @men
214Stable marriage problem
14ruby
cft9k
def factorial = { (it > 1) ? (2..it).inject(1) { i, j -> i*j }: 1 } def makePermutation; makePermutation = { list, i -> def n = list.size() if (n < 2) return list def fact = factorial(n-1) assert i < fact*n def index = i.intdiv(fact) [list[index]] + makePermutation(list[0..<index] + list[(index+1)..<n], i % fact) } def sorted = { a -> (1..<(a.size())).every { a[it-1] <= a[it] } } def permutationSort = { a -> def n = a.size() def fact = factorial(n) def permuteA = makePermutation.curry(a) def pIndex = (0..<fact).find { print "."; sorted(permuteA(it)) } permuteA(pIndex) }
222Sorting algorithms/Permutation sort
7groovy
p49bo
int pancake_sort(int *list, unsigned int length) { if(length<2) return 0; int i,a,max_num_pos,moves; moves=0; for(i=length;i>1;i--) { max_num_pos=0; for(a=0;a<i;a++) { if(list[a]>list[max_num_pos]) max_num_pos=a; } if(max_num_pos==i-1) continue; if(max_num_pos) { moves++; do_flip(list, length, max_num_pos+1); } moves++; do_flip(list, length, i); } return moves; }
228Sorting algorithms/Pancake sort
5c
xhmwu
$ Item @ Positional % Associative & Callable
219Special characters
3python
4mz5k
import java.util.Arrays; public class Stooge { public static void main(String[] args) { int[] nums = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5}; stoogeSort(nums); System.out.println(Arrays.toString(nums)); } public static void stoogeSort(int[] L) { stoogeSort(L, 0, L.length - 1); } public static void stoogeSort(int[] L, int i, int j) { if (L[j] < L[i]) { int tmp = L[i]; L[i] = L[j]; L[j] = tmp; } if (j - i > 1) { int t = (j - i + 1) / 3; stoogeSort(L, i, j - t); stoogeSort(L, i + t, j); stoogeSort(L, i, j - t); } } }
221Sorting algorithms/Stooge sort
9java
0prse
(import 'java.util.ArrayList) (defn arr-swap! [#^ArrayList arr i j] (let [t (.get arr i)] (doto arr (.set i (.get arr j)) (.set j t)))) (defn sel-sort! ([arr] (sel-sort! compare arr)) ([cmp #^ArrayList arr] (let [n (.size arr)] (letfn [(move-min! [start-i] (loop [i start-i] (when (< i n) (when (< (cmp (.get arr i) (.get arr start-i)) 0) (arr-swap! arr start-i i)) (recur (inc i)))))] (doseq [start-i (range (dec n))] (move-min! start-i)) arr))))
226Sorting algorithms/Selection sort
6clojure
6ob3q
def mkSparks( numStr:String ) : String = numStr.split( "[\\s,]+" ).map(_.toFloat) match { case v if v.isEmpty => "" case v if v.length == 1 => "\u2581" case v => (for( i <- v; s = "\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588".toCharArray; d = (v.max - v.min) / (s.length - 1) ) yield s( ((i - v.min) / d).toInt)).mkString } println( mkSparks( "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1" ) ) println( mkSparks( "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5" ) )
217Sparkline in unicode
16scala
tsxfb
object SMP extends App { private def checkMarriages(): Unit = if (check) println("Marriages are stable") else println("Marriages are unstable") private def swap() { val girl1 = girls.head val girl2 = girls(1) val tmp = girl2 -> matches(girl1) matches += girl1 -> matches(girl2) matches += tmp println(girl1 + " and " + girl2 + " have switched partners") } private type TM = scala.collection.mutable.TreeMap[String, String] private def check: Boolean = { if (!girls.toSet.subsetOf(matches.keySet) || !guys.toSet.subsetOf(matches.values.toSet)) return false val invertedMatches = new TM matches foreach { invertedMatches += _.swap } for ((k, v) <- matches) { val shePrefers = girlPrefers(k) val sheLikesBetter = shePrefers.slice(0, shePrefers.indexOf(v)) val hePrefers = guyPrefers(v) val heLikesBetter = hePrefers.slice(0, hePrefers.indexOf(k)) for (guy <- sheLikesBetter) { val fiance = invertedMatches(guy) val guy_p = guyPrefers(guy) if (guy_p.indexOf(fiance) > guy_p.indexOf(k)) { println(s"$k likes $guy better than $v and $guy likes $k better than their current partner") return false } } for (girl <- heLikesBetter) { val fiance = matches(girl) val girl_p = girlPrefers(girl) if (girl_p.indexOf(fiance) > girl_p.indexOf(v)) { println(s"$v likes $girl better than $k and $girl likes $v better than their current partner") return false } } } true } private val guys = "abe" :: "bob" :: "col" :: "dan" :: "ed" :: "fred" :: "gav" :: "hal" :: "ian" :: "jon" :: Nil private val girls = "abi" :: "bea" :: "cath" :: "dee" :: "eve" :: "fay" :: "gay" :: "hope" :: "ivy" :: "jan" :: Nil private val guyPrefers = Map("abe" -> List("abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"), "bob" -> List("cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"), "col" -> List("hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"), "dan" -> List("ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"), "ed" -> List("jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"), "fred" -> List("bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"), "gav" -> List("gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"), "hal" -> List("abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"), "ian" -> List("hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"), "jon" -> List("abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope")) private val girlPrefers = Map("abi" -> List("bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"), "bea" -> List("bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"), "cath" -> List("fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"), "dee" -> List("fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"), "eve" -> List("jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"), "fay" -> List("bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"), "gay" -> List("jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"), "hope" -> List("gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"), "ivy" -> List("ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"), "jan" -> List("ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan")) private lazy val matches = { val engagements = new TM val freeGuys = scala.collection.mutable.Queue.empty ++ guys while (freeGuys.nonEmpty) { val guy = freeGuys.dequeue() val guy_p = guyPrefers(guy) var break = false for (girl <- guy_p) if (!break) if (!engagements.contains(girl)) { engagements(girl) = guy break = true } else { val other_guy = engagements(girl) val girl_p = girlPrefers(girl) if (girl_p.indexOf(guy) < girl_p.indexOf(other_guy)) { engagements(girl) = guy freeGuys += other_guy break = true } } } engagements foreach { e => println(s"${e._1} is engaged to ${e._2}") } engagements } checkMarriages() swap() checkMarriages() }
214Stable marriage problem
16scala
u6yv8
(defn patience-insert "Inserts a value into the sequence where each element is a stack. Comparison replaces the definition of less than. Uses the greedy strategy." [comparison sequence value] (lazy-seq (if (empty? sequence) `((~value)) (let [stack (first sequence) top (peek stack)] (if (comparison value top) (cons (conj stack value) (rest sequence)) (cons stack (patience-insert comparison (rest sequence) value))))))) (defn patience-remove "Removes the value from the top of the first stack it shows up in. Leaves the stacks otherwise intact." [sequence value] (lazy-seq (if (empty? sequence) nil (let [stack (first sequence) top (peek stack)] (if (= top value) (let [left-overs (pop stack)] (if (empty? left-overs) (rest sequence) (cons left-overs (rest sequence)))) (cons stack (patience-remove (rest sequence) value))))))) (defn patience-recover "Builds a sorted sequence from a list of patience stacks. The given comparison takes the place of 'less than'" [comparison sequence] (loop [sequence sequence sorted []] (if (empty? sequence) sorted (let [smallest (reduce #(if (comparison %1 %2) %1 %2) (map peek sequence)) remaining (patience-remove sequence smallest)] (recur remaining (conj sorted smallest)))))) (defn patience-sort "Sorts the sequence by comparison. First builds the list of valid patience stacks. Then recovers the sorted list from those. If you don't supply a comparison, assumes less than." ([comparison sequence] (->> (reduce (comp doall (partial patience-insert comparison)) nil sequence) (patience-recover comparison))) ([sequence] (patience-sort < sequence))) (println (patience-sort [4 65 2 -31 0 99 83 782 1]))
227Sorting algorithms/Patience sort
6clojure
0p2sj
import Control.Monad permutationSort l = head [p | p <- permute l, sorted p] sorted (e1: e2: r) = e1 <= e2 && sorted (e2: r) sorted _ = True permute = foldM (flip insert) [] insert e [] = return [e] insert e l@(h: t) = return (e: l) `mplus` do { t' <- insert e t; return (h: t') }
222Sorting algorithms/Permutation sort
8haskell
yiw66
val n = 1 + 2
219Special characters
14ruby
rc6gs
function stoogeSort (array, i, j) { if (j === undefined) { j = array.length - 1; } if (i === undefined) { i = 0; } if (array[j] < array[i]) { var aux = array[i]; array[i] = array[j]; array[j] = aux; } if (j - i > 1) { var t = Math.floor((j - i + 1) / 3); stoogeSort(array, i, j-t); stoogeSort(array, i+t, j); stoogeSort(array, i, j-t); } };
221Sorting algorithms/Stooge sort
10javascript
dxbnu
package main import "fmt" var a = []int{170, 45, 75, -90, -802, 24, 2, 66} func main() { fmt.Println("before:", a) for inc := len(a) / 2; inc > 0; inc = (inc + 1) * 5 / 11 { for i := inc; i < len(a); i++ { j, temp := i, a[i] for ; j >= inc && a[j-inc] > temp; j -= inc { a[j] = a[j-inc] } a[j] = temp } } fmt.Println("after: ", a) }
223Sorting algorithms/Shell sort
0go
dxhne
null
218Spiral matrix
11kotlin
sbjq7
package main import ( "bytes" "encoding/binary" "fmt" )
225Sorting algorithms/Radix sort
0go
u60vt
import java.util.List; import java.util.ArrayList; import java.util.Arrays; public class PermutationSort { public static void main(String[] args) { int[] a={3,2,1,8,9,4,6}; System.out.println("Unsorted: " + Arrays.toString(a)); a=pSort(a); System.out.println("Sorted: " + Arrays.toString(a)); } public static int[] pSort(int[] a) { List<int[]> list=new ArrayList<int[]>(); permute(a,a.length,list); for(int[] x: list) if(isSorted(x)) return x; return a; } private static void permute(int[] a, int n, List<int[]> list) { if (n == 1) { int[] b=new int[a.length]; System.arraycopy(a, 0, b, 0, a.length); list.add(b); return; } for (int i = 0; i < n; i++) { swap(a, i, n-1); permute(a, n-1, list); swap(a, i, n-1); } } private static boolean isSorted(int[] a) { for(int i=1;i<a.length;i++) if(a[i-1]>a[i]) return false; return true; } private static void swap(int[] arr,int i, int j) { int temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } }
222Sorting algorithms/Permutation sort
9java
dxkn9
val n = 1 + 2
219Special characters
16scala
kuchk
' ' String literal Identifier [ ] Identifier ` ` Identifier ? Numbered host parameter : Named host parameter $ Named host parameter @ Named host parameter ( ) Parentheses + Add - Subtract/negative * Multiply / Divide % Modulo & Bitwise AND | Bitwise OR ~ Bitwise NOT << Left shift >> Right shift = Equal == Equal <> Not equal != Not equal < Less > Greater <= Less or equal >= Greater or equal || String concatenation
219Special characters
19sql
1gvpg
import Data.List shellSort xs = foldr (invColumnize (map (foldr insert []))) xs gaps where gaps = takeWhile (< length xs) $ iterate (succ.(3*)) 1 invColumnize f k = concat. transpose. f. transpose . takeWhile (not.null). unfoldr (Just. splitAt k)
223Sorting algorithms/Shell sort
8haskell
5yiug
null
212Stack
11kotlin
7lur4
def radixSort = { final radixExponent, list -> def fromBuckets = new TreeMap([0:list]) def toBuckets = new TreeMap() final radix = 2**radixExponent final mask = radix - 1 final radixDigitSize = (int)Math.ceil(64/radixExponent) final digitWidth = radixExponent (0..<radixDigitSize).each { radixDigit -> fromBuckets.values().findAll { it != null }.flatten().each { print '.' long bucketNumber = (long)((((long)it) >>> digitWidth*radixDigit) & mask) toBuckets[bucketNumber] = toBuckets[bucketNumber] ?: [] toBuckets[bucketNumber] << it } (fromBuckets, toBuckets) = [toBuckets, fromBuckets] toBuckets.clear() } final overflow = 2**(63 % radixExponent) final pos = {it < overflow} final neg = {it >= overflow} final keys = fromBuckets.keySet() final twosComplIndx = [] + (keys.findAll(neg)) + (keys.findAll(pos)) twosComplIndx.collect { fromBuckets[it] }.findAll { it != null }.flatten() }
225Sorting algorithms/Radix sort
7groovy
9dem4
null
222Sorting algorithms/Permutation sort
11kotlin
0pgsf
(defn pancake-sort [arr] (if (= 1 (count arr)) arr (when-let [mx (apply max arr)] (let [tk (split-with #(not= mx %) arr) tail (second tk) torev (concat (first tk) (take 1 tail)) head (reverse torev)] (cons mx (pancake-sort (concat (drop 1 head) (drop 1 tail))))))))
228Sorting algorithms/Pancake sort
6clojure
oav8j
null
221Sorting algorithms/Stooge sort
11kotlin
e7va4
1 while ($_ = shift and @ARGV and !fork); sleep $_; print "$_\n"; wait;
220Sorting algorithms/Sleep sort
2perl
mnsyz
av, sn = math.abs, function(s) return s~=0 and s/av(s) or 0 end function sindex(y, x)
218Spiral matrix
1lua
0phsd
import Data.Bits (Bits(testBit, bitSize)) import Data.List (partition) lsdSort :: (Ord a, Bits a) => [a] -> [a] lsdSort = fixSort positiveLsdSort msdSort :: (Ord a, Bits a) => [a] -> [a] msdSort = fixSort positiveMsdSort fixSort sorter list = uncurry (flip (++)) (break (< 0) (sorter list)) positiveLsdSort :: (Bits a) => [a] -> [a] positiveLsdSort list = foldl step list [0..bitSize (head list)] where step list bit = uncurry (++) (partition (not . flip testBit bit) list) positiveMsdSort :: (Bits a) => [a] -> [a] positiveMsdSort list = aux (bitSize (head list) - 1) list where aux _ [] = [] aux (-1) list = list aux bit list = aux (bit - 1) lower ++ aux (bit - 1) upper where (lower, upper) = partition (not . flip testBit bit) list
225Sorting algorithms/Radix sort
8haskell
wjced
null
222Sorting algorithms/Permutation sort
1lua
81r0e
local Y = function (f) return (function(x) return x(x) end)(function(x) return f(function(...) return x(x)(...) end) end) end function stoogesort(L, pred) pred = pred or function(a,b) return a < b end Y(function(recurse) return function(i,j) if pred(L[j], L[i]) then L[j],L[i] = L[i],L[j] end if j - i > 1 then local t = math.floor((j - i + 1)/3) recurse(i,j-t) recurse(i+t,j) recurse(i,j-t) end end end)(1,#L) return L end print(unpack(stoogesort{9,7,8,5,6,3,4,2,1,0}))
221Sorting algorithms/Stooge sort
1lua
wjuea
void main() { List<int> a = selectionSort([1100, 2, 56, 200, -52, 3, 99, 33, 177, -199]); print('$a'); } selectionSort(List<int> array){ for(int currentPlace = 0;currentPlace<array.length-1;currentPlace++){ int smallest = 4294967296;
226Sorting algorithms/Selection sort
18dart
sb2q6
class Person { let name:String var candidateIndex = 0 var fiance:Person? var candidates = [Person]() init(name:String) { self.name = name } func rank(p:Person) -> Int { for (i, candidate) in enumerate(self.candidates) { if candidate === p { return i } } return self.candidates.count + 1 } func prefers(p:Person) -> Bool { if let fiance = self.fiance { return self.rank(p) < self.rank(fiance) } return false } func nextCandidate() -> Person? { if self.candidateIndex >= self.candidates.count { return nil } return self.candidates[candidateIndex++] } func engageTo(p:Person) { p.fiance?.fiance = nil p.fiance = self self.fiance?.fiance = nil self.fiance = p } func swapWith(p:Person) { let thisFiance = self.fiance let pFiance = p.fiance println("\(self.name) swapped partners with \(p.name)") if pFiance!= nil && thisFiance!= nil { self.engageTo(pFiance!) p.engageTo(thisFiance!) } } } func isStable(guys:[Person], gals:[Person]) -> Bool { for guy in guys { for gal in gals { if guy.prefers(gal) && gal.prefers(guy) { return false } } } return true } func engageEveryone(guys:[Person]) { var done = false while!done { done = true for guy in guys { if guy.fiance == nil { done = false if let gal = guy.nextCandidate() { if gal.fiance == nil || gal.prefers(guy) { guy.engageTo(gal) } } } } } } func doMarriage() { let abe = Person(name: "Abe") let bob = Person(name: "Bob") let col = Person(name: "Col") let dan = Person(name: "Dan") let ed = Person(name: "Ed") let fred = Person(name: "Fred") let gav = Person(name: "Gav") let hal = Person(name: "Hal") let ian = Person(name: "Ian") let jon = Person(name: "Jon") let abi = Person(name: "Abi") let bea = Person(name: "Bea") let cath = Person(name: "Cath") let dee = Person(name: "Dee") let eve = Person(name: "Eve") let fay = Person(name: "Fay") let gay = Person(name: "Gay") let hope = Person(name: "Hope") let ivy = Person(name: "Ivy") let jan = Person(name: "Jan") abe.candidates = [abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay] bob.candidates = [cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay] col.candidates = [hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan] dan.candidates = [ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi] ed.candidates = [jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay] fred.candidates = [bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay] gav.candidates = [gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay] hal.candidates = [abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee] ian.candidates = [hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve] jon.candidates = [abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope] abi.candidates = [bob, fred, jon, gav, ian, abe, dan, ed, col, hal] bea.candidates = [bob, abe, col, fred, gav, dan, ian, ed, jon, hal] cath.candidates = [fred, bob, ed, gav, hal, col, ian, abe, dan, jon] dee.candidates = [fred, jon, col, abe, ian, hal, gav, dan, bob, ed] eve.candidates = [jon, hal, fred, dan, abe, gav, col, ed, ian, bob] fay.candidates = [bob, abe, ed, ian, jon, dan, fred, gav, col, hal] gay.candidates = [jon, gav, hal, fred, bob, abe, col, ed, dan, ian] hope.candidates = [gav, jon, bob, abe, ian, dan, hal, ed, col, fred] ivy.candidates = [ian, col, hal, gav, fred, bob, abe, ed, jon, dan] jan.candidates = [ed, hal, gav, abe, bob, jon, col, ian, fred, dan] let guys = [abe, bob, col, dan, ed, fred, gav, hal, ian, jon] let gals = [abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan] engageEveryone(guys) for guy in guys { println("\(guy.name) is engaged to \(guy.fiance!.name)") } println("Stable = \(isStable(guys, gals))") jon.swapWith(fred) println("Stable = \(isStable(guys, gals))") } doMarriage()
214Stable marriage problem
17swift
9dfmj
package main import ( "fmt" "container/heap" "sort" ) type IntPile []int func (self IntPile) Top() int { return self[len(self)-1] } func (self *IntPile) Pop() int { x := (*self)[len(*self)-1] *self = (*self)[:len(*self)-1] return x } type IntPilesHeap []IntPile func (self IntPilesHeap) Len() int { return len(self) } func (self IntPilesHeap) Less(i, j int) bool { return self[i].Top() < self[j].Top() } func (self IntPilesHeap) Swap(i, j int) { self[i], self[j] = self[j], self[i] } func (self *IntPilesHeap) Push(x interface{}) { *self = append(*self, x.(IntPile)) } func (self *IntPilesHeap) Pop() interface{} { x := (*self)[len(*self)-1] *self = (*self)[:len(*self)-1] return x } func patience_sort (n []int) { var piles []IntPile
227Sorting algorithms/Patience sort
0go
9d1mt
public static void shell(int[] a) { int increment = a.length / 2; while (increment > 0) { for (int i = increment; i < a.length; i++) { int j = i; int temp = a[i]; while (j >= increment && a[j - increment] > temp) { a[j] = a[j - increment]; j = j - increment; } a[j] = temp; } if (increment == 2) { increment = 1; } else { increment *= (5.0 / 11); } } }
223Sorting algorithms/Shell sort
9java
9dxmu
public static int[] sort(int[] old) {
225Sorting algorithms/Radix sort
9java
kuzhm
import Control.Monad.ST import Control.Monad import Data.Array.ST import Data.List import qualified Data.Set as S newtype Pile a = Pile [a] instance Eq a => Eq (Pile a) where Pile (x:_) == Pile (y:_) = x == y instance Ord a => Ord (Pile a) where Pile (x:_) `compare` Pile (y:_) = x `compare` y patienceSort :: Ord a => [a] -> [a] patienceSort = mergePiles . sortIntoPiles where sortIntoPiles :: Ord a => [a] -> [[a]] sortIntoPiles lst = runST $ do piles <- newSTArray (1, length lst) [] let bsearchPiles x len = aux 1 len where aux lo hi | lo > hi = return lo | otherwise = do let mid = (lo + hi) `div` 2 m <- readArray piles mid if head m < x then aux (mid+1) hi else aux lo (mid-1) f len x = do i <- bsearchPiles x len writeArray piles i . (x:) =<< readArray piles i return $ if i == len+1 then len+1 else len len <- foldM f 0 lst e <- getElems piles return $ take len e where newSTArray :: Ix i => (i,i) -> e -> ST s (STArray s i e) newSTArray = newArray mergePiles :: Ord a => [[a]] -> [a] mergePiles = unfoldr f . S.fromList . map Pile where f pq = case S.minView pq of Nothing -> Nothing Just (Pile [x], pq') -> Just (x, pq') Just (Pile (x:xs), pq') -> Just (x, S.insert (Pile xs) pq') main :: IO () main = print $ patienceSort [4, 65, 2, -31, 0, 99, 83, 782, 1]
227Sorting algorithms/Patience sort
8haskell
b5tk2
from time import sleep from threading import Timer def sleepsort(values): sleepsort.result = [] def add1(x): sleepsort.result.append(x) mx = values[0] for v in values: if mx < v: mx = v Timer(v, add1, [v]).start() sleep(mx+1) return sleepsort.result if __name__ == '__main__': x = [3,2,4,7,3,6,9,1] if sleepsort(x) == sorted(x): print('sleep sort worked for:',x) else: print('sleep sort FAILED for:',x)
220Sorting algorithms/Sleep sort
3python
9d0mf
function shellSort (a) { for (var h = a.length; h > 0; h = parseInt(h / 2)) { for (var i = h; i < a.length; i++) { var k = a[i]; for (var j = i; j >= h && k < a[j - h]; j -= h) a[j] = a[j - h]; a[j] = k; } } return a; } var a = []; var n = location.href.match(/\?(\d+)|$/)[1] || 10; for (var i = 0; i < n; i++) a.push(parseInt(Math.random() * 100)); shellSort(a); document.write(a.join(" "));
223Sorting algorithms/Shell sort
10javascript
u6ovb
null
225Sorting algorithms/Radix sort
11kotlin
g9i4d
require 'thread' nums = ARGV.collect(&:to_i) sorted = [] mutex = Mutex.new threads = nums.collect do |n| Thread.new do sleep 0.01 * n mutex.synchronize {sorted << n} end end threads.each {|t| t.join} p sorted
220Sorting algorithms/Sleep sort
14ruby
ltocl