Initial data commit
This commit is contained in:
parent
72d218235f
commit
f23f22d71c
199087 changed files with 3378941 additions and 0 deletions
3
Task/Sorting-algorithms-Sleep-sort/00-META.yaml
Normal file
3
Task/Sorting-algorithms-Sleep-sort/00-META.yaml
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
---
|
||||
from: http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
|
||||
note: Sorting Algorithms
|
||||
9
Task/Sorting-algorithms-Sleep-sort/00-TASK.txt
Normal file
9
Task/Sorting-algorithms-Sleep-sort/00-TASK.txt
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
{{Sorting Algorithm}}
|
||||
[[Category:Sorting]]
|
||||
|
||||
In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time.
|
||||
|
||||
Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required.
|
||||
|
||||
Sleep sort was [https://archive.fo/xhGo presented] anonymously on 4chan and has been [http://news.ycombinator.com/item?id=2657277 discussed] on Hacker News.
|
||||
|
||||
|
|
@ -0,0 +1 @@
|
|||
sleepsort←{{r}⎕TSYNC{r,←⊃⍵,⎕DL ⍵}&¨⍵,r←⍬}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
with Ada.Text_IO;
|
||||
with Ada.Command_Line; use Ada.Command_Line;
|
||||
procedure SleepSort is
|
||||
task type PrintTask (num : Integer);
|
||||
task body PrintTask is begin
|
||||
delay Duration (num) / 100.0;
|
||||
Ada.Text_IO.Put(num'Img);
|
||||
end PrintTask;
|
||||
type TaskAcc is access PrintTask;
|
||||
TaskList : array (1 .. Argument_Count) of TaskAcc;
|
||||
begin
|
||||
for i in TaskList'Range loop
|
||||
TaskList(i) := new PrintTask(Integer'Value(Argument(i)));
|
||||
end loop;
|
||||
end SleepSort;
|
||||
|
|
@ -0,0 +1,113 @@
|
|||
format ELF64 executable 3
|
||||
entry start
|
||||
|
||||
; parameters: argc, argv[] on stack
|
||||
start:
|
||||
mov r12, [rsp] ; get argc
|
||||
mov r13, 1 ; skip argv[0]
|
||||
|
||||
.getargv:
|
||||
cmp r13, r12 ; check completion of args
|
||||
je .wait
|
||||
mov rdi, [rsp+8+8*r13] ; get argv[n]
|
||||
inc r13
|
||||
|
||||
mov rax, 57 ; sys_fork
|
||||
syscall
|
||||
|
||||
cmp rax, 0 ; continue loop in main process
|
||||
jnz .getargv
|
||||
|
||||
push rdi ; save pointer to sort item text
|
||||
|
||||
call atoi_simple ; convert text to integer
|
||||
test rax, rax ; throw out bad input
|
||||
js .done
|
||||
|
||||
sub rsp, 16 ; stack space for timespec
|
||||
mov [rsp], rax ; seconds
|
||||
mov qword [rsp+8], 0 ; nanoseconds
|
||||
|
||||
lea rdi, [rsp]
|
||||
xor rsi, rsi
|
||||
mov rax, 35 ; sys_nanosleep
|
||||
syscall
|
||||
|
||||
add rsp, 16
|
||||
|
||||
pop rdi ; retrieve item text
|
||||
call strlen_simple
|
||||
|
||||
mov rsi, rdi
|
||||
mov byte [rsi+rax], ' '
|
||||
mov rdi, 1
|
||||
mov rdx, rax
|
||||
inc rdx
|
||||
mov rax, 1 ; sys_write
|
||||
syscall
|
||||
|
||||
jmp .done
|
||||
|
||||
.wait:
|
||||
dec r12 ; wait for each child process
|
||||
jz .done
|
||||
mov rdi, 0 ; any pid
|
||||
mov rsi, 0
|
||||
mov rdx, 0
|
||||
mov r10, 4 ; that has terminated
|
||||
mov rax, 247 ; sys_waitid
|
||||
syscall
|
||||
|
||||
jmp .wait
|
||||
|
||||
.done:
|
||||
xor rdi, rdi
|
||||
mov rax, 60 ; sys_exit
|
||||
syscall
|
||||
|
||||
; parameter: rdi = string pointer
|
||||
; return: rax = integer conversion
|
||||
atoi_simple:
|
||||
push rdi
|
||||
push rsi
|
||||
|
||||
xor rax, rax
|
||||
|
||||
.convert:
|
||||
movzx rsi, byte [rdi]
|
||||
test rsi, rsi ; check for null
|
||||
jz .done
|
||||
|
||||
cmp rsi, '0'
|
||||
jl .baddigit
|
||||
cmp rsi, '9'
|
||||
jg .baddigit
|
||||
sub rsi, 48 ; get ascii code for digit
|
||||
|
||||
imul rax, 10 ; radix 10
|
||||
add rax, rsi ; add current digit to total
|
||||
|
||||
inc rdi
|
||||
jmp .convert
|
||||
|
||||
.baddigit:
|
||||
mov rax, -1 ; return error code on failed conversion
|
||||
|
||||
.done:
|
||||
pop rsi
|
||||
pop rdi
|
||||
ret ; return integer value
|
||||
|
||||
; parameter: rdi = string pointer
|
||||
; return: rax = length
|
||||
strlen_simple:
|
||||
xor rax, rax
|
||||
|
||||
.compare:
|
||||
cmp byte [rdi+rax], 0
|
||||
je .done
|
||||
inc rax
|
||||
jmp .compare
|
||||
|
||||
.done:
|
||||
ret
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
items := [1,5,4,9,3,4]
|
||||
for i, v in SleepSort(items)
|
||||
result .= v ", "
|
||||
MsgBox, 262144, , % result := "[" Trim(result, ", ") "]"
|
||||
return
|
||||
|
||||
SleepSort(items){
|
||||
global Sorted := []
|
||||
slp := 50
|
||||
for i, v in items{
|
||||
fn := Func("PushFn").Bind(v)
|
||||
SetTimer, %fn%, % v * -slp
|
||||
}
|
||||
Sleep % Max(items*) * slp
|
||||
return Sorted
|
||||
}
|
||||
|
||||
PushFn(v){
|
||||
global Sorted
|
||||
Sorted.Push(v)
|
||||
}
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
INSTALL @lib$+"TIMERLIB"
|
||||
|
||||
DIM test%(9)
|
||||
test%() = 4, 65, 2, 31, 0, 99, 2, 83, 782, 1
|
||||
|
||||
FOR i% = 0 TO DIM(test%(),1)
|
||||
p% = EVAL("!^PROCtask" + STR$(i%))
|
||||
tid% = FN_ontimer(100 + test%(i%), p%, 0)
|
||||
NEXT
|
||||
|
||||
REPEAT
|
||||
WAIT 0
|
||||
UNTIL FALSE
|
||||
|
||||
DEF PROCtask0 : PRINT test%(0) : ENDPROC
|
||||
DEF PROCtask1 : PRINT test%(1) : ENDPROC
|
||||
DEF PROCtask2 : PRINT test%(2) : ENDPROC
|
||||
DEF PROCtask3 : PRINT test%(3) : ENDPROC
|
||||
DEF PROCtask4 : PRINT test%(4) : ENDPROC
|
||||
DEF PROCtask5 : PRINT test%(5) : ENDPROC
|
||||
DEF PROCtask6 : PRINT test%(6) : ENDPROC
|
||||
DEF PROCtask7 : PRINT test%(7) : ENDPROC
|
||||
DEF PROCtask8 : PRINT test%(8) : ENDPROC
|
||||
DEF PROCtask9 : PRINT test%(9) : ENDPROC
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
>>>>>,----------[++++++++
|
||||
++[->+>+<<]>+>[-<<+>>]+++
|
||||
+++++[-<------>]>>+>,----
|
||||
------<<+[->>>>>+<<<<<]>>
|
||||
]>>>[<<<<[<<<[->>+<<[->+>
|
||||
[-]<<]]>[-<+>]>[-<<<.>>>>
|
||||
->>>>>[>>>>>]<-<<<<[<<<<<
|
||||
]+<]<<<<]>>>>>[>>>>>]<]
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
#include <chrono>
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
std::vector<std::thread> threads;
|
||||
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
threads.emplace_back([i, &argv]() {
|
||||
int arg = std::stoi(argv[i]);
|
||||
std::this_thread::sleep_for(std::chrono::seconds(arg));
|
||||
std::cout << argv[i] << std::endl;
|
||||
});
|
||||
}
|
||||
|
||||
for (auto& thread : threads) {
|
||||
thread.join();
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading;
|
||||
|
||||
class Program
|
||||
{
|
||||
static void ThreadStart(object item)
|
||||
{
|
||||
Thread.Sleep(1000 * (int)item);
|
||||
Console.WriteLine(item);
|
||||
}
|
||||
|
||||
static void SleepSort(IEnumerable<int> items)
|
||||
{
|
||||
foreach (var item in items)
|
||||
{
|
||||
new Thread(ThreadStart).Start(item);
|
||||
}
|
||||
}
|
||||
|
||||
static void Main(string[] arguments)
|
||||
{
|
||||
SleepSort(arguments.Select(int.Parse));
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
var input = new[] { 1, 9, 2, 1, 3 };
|
||||
|
||||
foreach (var n in input)
|
||||
Task.Run(() =>
|
||||
{
|
||||
Thread.Sleep(n * 1000);
|
||||
Console.WriteLine(n);
|
||||
});
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
|
||||
int main(int c, char **v)
|
||||
{
|
||||
while (--c > 1 && !fork());
|
||||
sleep(c = atoi(v[c]));
|
||||
printf("%d\n", c);
|
||||
wait(0);
|
||||
return 0;
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
% ./a.out 5 1 3 2 11 6 4
|
||||
1
|
||||
2
|
||||
3
|
||||
4
|
||||
5
|
||||
6
|
||||
11
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
(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)))))
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
(sleep-sort [4 5 3 1 2 7 6])
|
||||
;=> [1 2 3 4 5 6 7]
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
after = (s, f) -> setTimeout f, s*1000
|
||||
|
||||
# Setting Computer Science back at least a century, maybe more,
|
||||
# this algorithm sorts integers using a highly parallelized algorithm.
|
||||
sleep_sort = (arr) ->
|
||||
for n in arr
|
||||
do (n) -> after n, -> console.log n
|
||||
|
||||
do ->
|
||||
input = (parseInt(arg) for arg in process.argv[2...])
|
||||
sleep_sort input
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
> time coffee sleep_sort.coffee 5, 1, 3, 4, 2
|
||||
1
|
||||
2
|
||||
3
|
||||
4
|
||||
5
|
||||
|
||||
real 0m5.184s
|
||||
user 0m0.147s
|
||||
sys 0m0.024s
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
(defun sleeprint(n)
|
||||
(sleep (/ n 10))
|
||||
(format t "~a~%" n))
|
||||
|
||||
(loop for arg in (cdr sb-ext:*posix-argv*) doing
|
||||
(sb-thread:make-thread (lambda() (sleeprint (parse-integer arg)))))
|
||||
|
||||
(loop while (not (null (cdr (sb-thread:list-all-threads)))))
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
void main(string[] args)
|
||||
{
|
||||
import core.thread, std;
|
||||
args.drop(1).map!(a => a.to!uint).parallel.each!((a)
|
||||
{
|
||||
Thread.sleep(dur!"msecs"(a));
|
||||
write(a, " ");
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
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]);
|
||||
}
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
program SleepSortDemo;
|
||||
|
||||
{$APPTYPE CONSOLE}
|
||||
|
||||
uses
|
||||
Windows, SysUtils, Classes;
|
||||
|
||||
type
|
||||
TSleepThread = class(TThread)
|
||||
private
|
||||
FValue: Integer;
|
||||
FLock: PRTLCriticalSection;
|
||||
protected
|
||||
constructor Create(AValue: Integer; ALock: PRTLCriticalSection);
|
||||
procedure Execute; override;
|
||||
end;
|
||||
|
||||
constructor TSleepThread.Create(AValue: Integer; ALock: PRTLCriticalSection);
|
||||
begin
|
||||
FValue:= AValue;
|
||||
FLock:= ALock;
|
||||
inherited Create(False);
|
||||
end;
|
||||
|
||||
procedure TSleepThread.Execute;
|
||||
begin
|
||||
Sleep(1000 * FValue);
|
||||
EnterCriticalSection(FLock^);
|
||||
Write(FValue:3);
|
||||
LeaveCriticalSection(FLock^);
|
||||
end;
|
||||
|
||||
var
|
||||
A: array[0..15] of Integer;
|
||||
Handles: array[0..15] of THandle;
|
||||
Threads: array[0..15] of TThread;
|
||||
Lock: TRTLCriticalSection;
|
||||
I: Integer;
|
||||
|
||||
begin
|
||||
for I:= Low(A) to High(A) do
|
||||
A[I]:= Random(15);
|
||||
for I:= Low(A) to High(A) do
|
||||
Write(A[I]:3);
|
||||
Writeln;
|
||||
|
||||
InitializeCriticalSection(Lock);
|
||||
for I:= Low(A) to High(A) do begin
|
||||
Threads[I]:= TSleepThread.Create(A[I], @Lock);
|
||||
Handles[I]:= Threads[I].Handle;
|
||||
end;
|
||||
WaitForMultipleObjects(Length(A), @Handles, True, INFINITE);
|
||||
for I:= Low(A) to High(A) do
|
||||
Threads[I].Free;
|
||||
DeleteCriticalSection(Lock);
|
||||
|
||||
Writeln;
|
||||
ReadLn;
|
||||
end.
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
import extensions;
|
||||
import system'routines;
|
||||
import extensions'threading;
|
||||
import system'threading;
|
||||
|
||||
static sync = new object();
|
||||
|
||||
extension op
|
||||
{
|
||||
sleepSort()
|
||||
{
|
||||
self.forEach:(n)
|
||||
{
|
||||
threadControl.start(
|
||||
{
|
||||
threadControl.sleep(1000 * n);
|
||||
|
||||
lock(sync)
|
||||
{
|
||||
console.printLine(n)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public program()
|
||||
{
|
||||
program_arguments.skipping:1.selectBy(mssgconst toInt<convertorOp>[1]).toArray().sleepSort();
|
||||
|
||||
console.readChar()
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
defmodule Sort do
|
||||
def sleep_sort(args) do
|
||||
Enum.each(args, fn(arg) -> Process.send_after(self, arg, 5 * arg) end)
|
||||
loop(length(args))
|
||||
end
|
||||
|
||||
defp loop(0), do: :ok
|
||||
defp loop(n) do
|
||||
receive do
|
||||
num -> IO.puts num
|
||||
loop(n - 1)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Sort.sleep_sort [2, 4, 8, 12, 35, 2, 12, 1]
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
(dolist (i '(3 1 4 1 5 92 65 3 5 89 79 3))
|
||||
(run-with-timer (* i 0.001) nil 'message "%d" i))
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
#!/usr/bin/env escript
|
||||
%% -*- erlang -*-
|
||||
%%! -smp enable -sname sleepsort
|
||||
|
||||
main(Args) ->
|
||||
lists:foreach(fun(Arg) ->
|
||||
timer:send_after(5 * list_to_integer(Arg), self(), Arg)
|
||||
end, Args),
|
||||
loop(length(Args)).
|
||||
|
||||
loop(0) ->
|
||||
ok;
|
||||
loop(N) ->
|
||||
receive
|
||||
Num ->
|
||||
io:format("~s~n", [Num]),
|
||||
loop(N - 1)
|
||||
end.
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
include get.e
|
||||
|
||||
integer count
|
||||
|
||||
procedure sleeper(integer key)
|
||||
? key
|
||||
count -= 1
|
||||
end procedure
|
||||
|
||||
sequence s, val
|
||||
atom task
|
||||
|
||||
s = command_line()
|
||||
s = s[3..$]
|
||||
if length(s)=0 then
|
||||
puts(1,"Nothing to sort.\n")
|
||||
else
|
||||
count = 0
|
||||
for i = 1 to length(s) do
|
||||
val = value(s[i])
|
||||
if val[1] = GET_SUCCESS then
|
||||
task = task_create(routine_id("sleeper"),{val[2]})
|
||||
task_schedule(task,{val[2],val[2]}/10)
|
||||
count += 1
|
||||
end if
|
||||
end for
|
||||
|
||||
while count do
|
||||
task_yield()
|
||||
end while
|
||||
end if
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
let sleepSort (values: seq<int>) =
|
||||
values
|
||||
|> Seq.map (fun x -> async {
|
||||
do! Async.Sleep x
|
||||
Console.WriteLine x
|
||||
})
|
||||
|> Async.Parallel
|
||||
|> Async.Ignore
|
||||
|> Async.RunSynchronously
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
sleepSort [10; 33; 80; 32]
|
||||
10
|
||||
32
|
||||
33
|
||||
80
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
USING: threads calendar concurrency.combinators ;
|
||||
|
||||
: sleep-sort ( seq -- ) [ dup seconds sleep . ] parallel-each ;
|
||||
|
|
@ -0,0 +1 @@
|
|||
{ 1 9 2 6 3 4 5 8 7 0 } sleep-sort
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
program sleepSort
|
||||
use omp_lib
|
||||
implicit none
|
||||
integer::nArgs,myid,i,stat
|
||||
integer,allocatable::intArg(:)
|
||||
character(len=5)::arg
|
||||
|
||||
!$omp master
|
||||
nArgs=command_argument_count()
|
||||
if(nArgs==0)stop ' : No argument is given !'
|
||||
allocate(intArg(nArgs))
|
||||
do i=1,nArgs
|
||||
call get_command_argument(i, arg)
|
||||
read(arg,'(I5)',iostat=stat)intArg(i)
|
||||
if(intArg(i)<0 .or. stat/=0) stop&
|
||||
&' :Only 0 or positive integer allowed !'
|
||||
end do
|
||||
call omp_set_num_threads(nArgs)
|
||||
!$omp end master
|
||||
|
||||
|
||||
!$omp parallel private(myid)
|
||||
myid =omp_get_thread_num()
|
||||
call sleepNprint(intArg(myid+1))
|
||||
!$omp end parallel
|
||||
|
||||
contains
|
||||
subroutine sleepNprint(nSeconds)
|
||||
integer::nSeconds
|
||||
call sleep(nSeconds)
|
||||
print*,nSeconds
|
||||
end subroutine sleepNprint
|
||||
end program sleepSort
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
' version 21-10-2016
|
||||
' compile with: fbc -s console
|
||||
' compile with: fbc -s console -exx (for bondry check on the array's)
|
||||
' not very well suited for large numbers and large array's
|
||||
' positive numbers only
|
||||
|
||||
Sub sandman(sleepy() As ULong)
|
||||
Dim As Long lb = LBound(sleepy)
|
||||
Dim As Long ub = UBound(sleepy)
|
||||
Dim As Long i, count = ub
|
||||
Dim As Double wakeup(lb To ub)
|
||||
Dim As Double t = Timer
|
||||
|
||||
For i = lb To ub
|
||||
wakeup(i) = sleepy(i) +1 + t
|
||||
Next
|
||||
|
||||
Do
|
||||
t = Timer
|
||||
For i = lb To ub
|
||||
If wakeup(i) <= t Then
|
||||
Print Using "####";sleepy(i);
|
||||
wakeup(i) = 1e9 ' mark it as used
|
||||
count = count -1
|
||||
End If
|
||||
Next
|
||||
Sleep (1 - (Timer - t)) * 300, 1 ' reduce CPU load
|
||||
Loop Until count < lb
|
||||
|
||||
End Sub
|
||||
|
||||
' ------=< MAIN >=------
|
||||
|
||||
Dim As ULong i, arr(10)
|
||||
Dim As ULong lb = LBound(arr)
|
||||
Dim As ULong ub = UBound(arr)
|
||||
|
||||
Randomize Timer
|
||||
For i = lb To ub -1 ' leave last one zero
|
||||
arr(i) = Int(Rnd * 10) +1
|
||||
Next
|
||||
|
||||
Print "unsorted ";
|
||||
For i = lb To ub
|
||||
Print Using "####";arr(i);
|
||||
Next
|
||||
Print : Print
|
||||
|
||||
Print " sorted ";
|
||||
sandman(arr())
|
||||
|
||||
Print : Print
|
||||
|
||||
' empty keyboard buffer
|
||||
While InKey <> "" : Wend
|
||||
Print : Print "hit any key to end program"
|
||||
Sleep
|
||||
End
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
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)
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,28 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(len(os.Args[1:]))
|
||||
for _,i := range os.Args[1:] {
|
||||
x, err := strconv.ParseUint(i, 10, 64)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
}
|
||||
wg.Add(1)
|
||||
go func(i uint64, wg *sync.WaitGroup) {
|
||||
defer wg.Done()
|
||||
time.Sleep(time.Duration(i) * time.Second)
|
||||
fmt.Println(i)
|
||||
}(x, &wg)
|
||||
}
|
||||
wg.Wait()
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
@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
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
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
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
import System.Environment
|
||||
import Control.Concurrent
|
||||
import Control.Concurrent.Async
|
||||
|
||||
sleepSort :: [Int] -> IO ()
|
||||
sleepSort = mapConcurrently_ (\x -> threadDelay (x*10^4) >> print x)
|
||||
|
||||
main :: IO ()
|
||||
main = getArgs >>= sleepSort . map read
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
procedure main(A)
|
||||
every insert(t:=set(),mkThread(t,!A))
|
||||
every spawn(!t) # start threads as closely grouped as possible
|
||||
while (*t > 0) do write(<<@)
|
||||
end
|
||||
|
||||
procedure mkThread(t,n) # 10ms delay scale factor
|
||||
return create (delay(n*10),delete(t,¤t),n@>&main)
|
||||
end
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
scheduledumb=: {{
|
||||
id=:'dumb',":x:6!:9''
|
||||
wd 'pc ',id
|
||||
(t)=: u {{u y[erase n}} t=. id,'_timer'
|
||||
wd 'ptimer ',":n p.y
|
||||
}}
|
||||
|
||||
|
||||
ssort=: {{
|
||||
R=: ''
|
||||
poly=. 1,>./ y
|
||||
poly{{ y{{R=:R,m[y}}scheduledumb m y}}"0 y
|
||||
{{echo R}} scheduledumb poly"0 >:>./ y
|
||||
EMPTY
|
||||
}}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
t=: ?~30
|
||||
t
|
||||
11 7 22 16 17 2 1 19 23 29 9 21 15 10 12 27 3 4 24 20 14 5 26 18 8 6 0 13 25 28
|
||||
ssort t
|
||||
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
t=: ?~30
|
||||
t
|
||||
23 26 24 25 10 12 4 5 7 27 16 17 14 8 3 15 18 13 19 21 2 28 22 9 6 20 11 1 29 0
|
||||
ssort t
|
||||
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
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();
|
||||
|
||||
//using straight milliseconds produces unpredictable
|
||||
//results with small numbers
|
||||
//using 1000 here gives a nifty demonstration
|
||||
Thread.sleep(num * 1000);
|
||||
System.out.println(num);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
int[] nums = new int[args.length];
|
||||
for (int i = 0; i < args.length; i++)
|
||||
nums[i] = Integer.parseInt(args[i]);
|
||||
sleepSortAndPrint(nums);
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
Array.prototype.timeoutSort = function (f) {
|
||||
this.forEach(function (n) {
|
||||
setTimeout(function () { f(n) }, 5 * n)
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1 @@
|
|||
[1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0].timeoutSort(function(n) { document.write(n + '<br>'); })
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
Array.prototype.sleepSort = function(callback) {
|
||||
const res = [];
|
||||
for (let n of this)
|
||||
setTimeout(() => {
|
||||
res.push(n);
|
||||
if (this.length === res.length)
|
||||
callback(res);
|
||||
}, n + 1);
|
||||
return res;
|
||||
};
|
||||
|
||||
[1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0].sleepSort(console.log);
|
||||
// [ 1, 0, 2, 3, 4, 5, 5, 6, 7, 8, 9 ]
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
echo '[5, 1, 3, 2, 11, 6, 4]' | jq '
|
||||
def f:
|
||||
if .unsorted == [] then
|
||||
.sorted
|
||||
else
|
||||
{ unsorted: [.unsorted[] | .t = .t - 1 | select(.t != 0)]
|
||||
, sorted: (.sorted + [.unsorted[] | .t = .t - 1 | select(.t == 0) | .v]) }
|
||||
| f
|
||||
end;
|
||||
{unsorted: [.[] | {v: ., t: .}], sorted: []} | f | .[]
|
||||
'
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
function sleepsort(V::Vector{T}) where {T <: Real}
|
||||
U = Vector{T}()
|
||||
sizehint!(U, length(V))
|
||||
@sync for v in V
|
||||
@async begin
|
||||
sleep(abs(v))
|
||||
(v < 0 ? pushfirst! : push!)(U, v)
|
||||
end
|
||||
end
|
||||
return U
|
||||
end
|
||||
|
||||
|
||||
|
||||
v = rand(-10:10, 10)
|
||||
println("# unordered: $v\n -> ordered: ", sleepsort(v))
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
// version 1.1.51
|
||||
|
||||
import kotlin.concurrent.thread
|
||||
|
||||
fun sleepSort(list: List<Int>, interval: Long) {
|
||||
print("Sorted : ")
|
||||
for (i in list) {
|
||||
thread {
|
||||
Thread.sleep(i * interval)
|
||||
print("$i ")
|
||||
}
|
||||
}
|
||||
thread { // print a new line after displaying sorted list
|
||||
Thread.sleep ((1 + list.max()!!) * interval)
|
||||
println()
|
||||
}
|
||||
}
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val list = args.map { it.toInt() }.filter { it >= 0 } // ignore negative integers
|
||||
println("Unsorted: ${list.joinToString(" ")}")
|
||||
sleepSort(list, 50)
|
||||
}
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
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
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
socket = require 'socket'
|
||||
|
||||
function sleeprint(n)
|
||||
local t0 = socket.gettime()
|
||||
while (socket.gettime() - t0)*100 <= 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
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
SleepSort = RunScheduledTask[Print@#, {#, 1}] & /@ # &;
|
||||
SleepSort@{1, 9, 8, 7, 6, 5, 3, 4, 5, 2, 0};
|
||||
|
|
@ -0,0 +1,59 @@
|
|||
/* NetRexx */
|
||||
options replace format comments java crossref symbols nobinary
|
||||
import java.util.concurrent.CountDownLatch
|
||||
|
||||
-- =============================================================================
|
||||
class RSortingSleepsort
|
||||
properties constant private
|
||||
dflt = '-6 3 1 4 5 2 3 -7 1 6 001 3 -9 2 5 -009 -8 4 6 1 9 8 7 6 5 -7 3 4 5 2 0 -2 -1 -5 -4 -3 -0 000 0'
|
||||
properties indirect
|
||||
startLatch = CountDownLatch
|
||||
doneLatch = CountDownLatch
|
||||
floor = 0
|
||||
sorted = ''
|
||||
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
method main(args = String[]) public static
|
||||
arg = Rexx(args)
|
||||
if arg = '' then arg = dflt
|
||||
say ' unsorted:' arg
|
||||
say ' sorted:' (RSortingSleepsort()).sleepSort(arg)
|
||||
return
|
||||
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
method sleepSort(iArg) public
|
||||
setStartLatch(CountDownLatch(1)) -- used to put all threads on hold until we're ready to run
|
||||
setDoneLatch(CountDownLatch(iArg.words())) -- used to indicate all work is done
|
||||
loop mn = 1 to iArg.words()
|
||||
setFloor(getFloor().min(iArg.word(mn))) -- save smallest -ve number so we can use it as a scale for sleep
|
||||
Thread(SortThread(iArg.word(mn))).start() -- loop through input and create a thread for each element
|
||||
end mn
|
||||
getStartLatch().countDown() -- cry 'Havoc', and let slip the dogs of war.
|
||||
do
|
||||
getDoneLatch().await() -- wait for worker threads to complete
|
||||
catch ix = InterruptedException
|
||||
ix.printStackTrace()
|
||||
end
|
||||
return getSorted()
|
||||
|
||||
-- =============================================================================
|
||||
class RSortingSleepsort.SortThread dependent implements Runnable
|
||||
properties indirect
|
||||
num
|
||||
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
method SortThread(nm)
|
||||
setNum(nm)
|
||||
return
|
||||
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
method run() public
|
||||
do
|
||||
parent.getStartLatch().await() -- wait until all threads are constructed
|
||||
sleepTime = getNum() + parent.getFloor().abs() -- shifted by value of smallest number (permits numbers < 0)
|
||||
sleepTime = sleepTime * 250 -- scale up; milliseconds are not granular enough
|
||||
Thread.sleep(sleepTime) -- wait for this number's turn to run
|
||||
catch ie = InterruptedException
|
||||
ie.printStackTrace()
|
||||
end
|
||||
do protect parent -- lock the parent to prevent collisions
|
||||
parent.setSorted((parent.getSorted() num).strip()) -- stow the number in the results List
|
||||
end
|
||||
parent.getDoneLatch().countDown() -- this one's done; decrement the latch
|
||||
return
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
import os, strutils
|
||||
|
||||
proc single(n: int) =
|
||||
sleep n
|
||||
echo n
|
||||
|
||||
proc main =
|
||||
var thr = newSeq[TThread[int]](paramCount())
|
||||
for i,c in commandLineParams():
|
||||
thr[i].createThread(single, c.parseInt)
|
||||
thr.joinThreads
|
||||
|
||||
main()
|
||||
|
|
@ -0,0 +1,31 @@
|
|||
use System.Concurrency;
|
||||
use Collection;
|
||||
|
||||
bundle Default {
|
||||
class Item from Thread {
|
||||
@value : Int;
|
||||
|
||||
New(value : Int) {
|
||||
Parent();
|
||||
@value := value;
|
||||
}
|
||||
|
||||
method : public : Run(param : System.Base) ~ Nil {
|
||||
Sleep(1000 * @value);
|
||||
@value->PrintLine();
|
||||
}
|
||||
}
|
||||
|
||||
class SleepSort {
|
||||
function : Main(args : String[]) ~ Nil {
|
||||
items := Vector->New();
|
||||
each(i : args) {
|
||||
items->AddBack(Item->New(args[i]->ToInt()));
|
||||
};
|
||||
|
||||
each(i : items) {
|
||||
items->Get(i)->As(Item)->Execute(Nil);
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
#import <Foundation/Foundation.h>
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
|
||||
while (--argc) {
|
||||
int i = atoi(argv[argc]);
|
||||
[queue addOperationWithBlock: ^{
|
||||
sleep(i);
|
||||
NSLog(@"%d\n", i);
|
||||
}];
|
||||
}
|
||||
[queue waitUntilAllOperationsAreFinished];
|
||||
}
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
#import <Foundation/Foundation.h>
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
while (--argc) {
|
||||
int i = atoi(argv[argc]);
|
||||
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, i * NSEC_PER_SEC),
|
||||
dispatch_get_main_queue(),
|
||||
^{ NSLog(@"%d\n", i); });
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
import: parallel
|
||||
|
||||
: sleepSort(l)
|
||||
| ch n |
|
||||
Channel new ->ch
|
||||
l forEach: n [ #[ n dup 20 * sleep ch send drop ] & ]
|
||||
ListBuffer newSize(l size) #[ ch receive over add ] times(l size) ;
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
(define (sleep-sort lst)
|
||||
(for-each (lambda (timeout)
|
||||
(async (lambda ()
|
||||
(sleep timeout)
|
||||
(print timeout))))
|
||||
lst))
|
||||
|
||||
(sleep-sort '(5 8 2 7 9 10 5))
|
||||
|
|
@ -0,0 +1,23 @@
|
|||
<?php
|
||||
|
||||
$buffer = 1;
|
||||
$pids = [];
|
||||
|
||||
for ($i = 1; $i < $argc; $i++) {
|
||||
$pid = pcntl_fork();
|
||||
if ($pid < 0) {
|
||||
die("failed to start child process");
|
||||
}
|
||||
|
||||
if ($pid === 0) {
|
||||
sleep($argv[$i] + $buffer);
|
||||
echo $argv[$i] . "\n";
|
||||
exit();
|
||||
}
|
||||
|
||||
$pids[] = $pid;
|
||||
}
|
||||
|
||||
foreach ($pids as $pid) {
|
||||
pcntl_waitpid($pid, $status);
|
||||
}
|
||||
|
|
@ -0,0 +1,100 @@
|
|||
program sleepsort;
|
||||
{$IFDEF FPC}
|
||||
{$MODE DELPHI} {$Optimization ON,ALL}
|
||||
{$ElSE}
|
||||
{$APPTYPE CONSOLE}
|
||||
{$ENDIF}
|
||||
uses
|
||||
{$IFDEF UNIX}
|
||||
cthreads,
|
||||
{$ENDIF}
|
||||
SysUtils;
|
||||
|
||||
const
|
||||
HiLimit = 40;
|
||||
type
|
||||
tCombineForOneThread = record
|
||||
cft_count : Uint64;
|
||||
cft_ThreadID: NativeUint;
|
||||
cft_ThreadHandle: NativeUint;
|
||||
end;
|
||||
pThreadBlock = ^tCombineForOneThread;
|
||||
var
|
||||
SortIdx : array of INteger;
|
||||
ThreadBlocks : array of tCombineForOneThread;
|
||||
gblThreadCount,
|
||||
Finished: Uint32;
|
||||
|
||||
procedure PrepareThreads(thdCount:NativeInt);
|
||||
var
|
||||
i : NativeInt;
|
||||
Begin
|
||||
For i := 0 to thdCount-1 do
|
||||
ThreadBlocks[i].cft_count:= random(2*HiLimit);
|
||||
end;
|
||||
|
||||
procedure TestRunThd(parameter: pointer);
|
||||
var
|
||||
pThdBlk: pThreadBlock;
|
||||
fi: NativeInt;
|
||||
begin
|
||||
pThdBlk := @ThreadBlocks[NativeUint(parameter)];
|
||||
with pThdBlk^ do
|
||||
begin
|
||||
sleep(40*cft_count+1);
|
||||
fi := Finished-1;
|
||||
//write(fi:5,cft_count:8,#13);
|
||||
InterLockedDecrement(Finished);
|
||||
SortIdx[fi]:= NativeUint(parameter);
|
||||
end;
|
||||
EndThread(0);
|
||||
end;
|
||||
|
||||
procedure Test;
|
||||
var
|
||||
j,UsedThreads: NativeInt;
|
||||
begin
|
||||
randomize;
|
||||
UsedThreads:= GblThreadCount;
|
||||
Finished :=UsedThreads;
|
||||
PrepareThreads(UsedThreads);
|
||||
j := 0;
|
||||
while (j < UsedThreads) do
|
||||
begin
|
||||
with ThreadBlocks[j] do
|
||||
begin
|
||||
cft_ThreadHandle :=
|
||||
BeginThread(@TestRunThd, Pointer(j), cft_ThreadID,16384 {stacksize} );
|
||||
If cft_ThreadHandle = 0 then break;
|
||||
end;
|
||||
Inc(j);
|
||||
end;
|
||||
writeln(j);
|
||||
UsedThreads := j;
|
||||
Finished :=UsedThreads;
|
||||
repeat
|
||||
sleep(1);
|
||||
until finished = 0;
|
||||
For j := 0 to UsedThreads-1 do
|
||||
CloseThread(ThreadBlocks[j].cft_ThreadID);
|
||||
|
||||
//output of sleep-sorted data
|
||||
For j := UsedThreads-1 downto 1 do
|
||||
write(ThreadBlocks[SortIdx[j]].cft_count,',');
|
||||
writeln(ThreadBlocks[SortIdx[0]].cft_count);
|
||||
end;
|
||||
|
||||
|
||||
begin
|
||||
randomize;
|
||||
gblThreadCount := Hilimit;
|
||||
Writeln('Testthreads : ',gblThreadCount);
|
||||
setlength(ThreadBlocks,gblThreadCount);
|
||||
setlength(SortIdx,gblThreadCount);
|
||||
Test;
|
||||
|
||||
setlength(ThreadBlocks, 0);
|
||||
{$IFDEF WINDOWS}
|
||||
readln;
|
||||
{$ENDIF}
|
||||
end.
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
1 while ($_ = shift and @ARGV and !fork);
|
||||
sleep $_;
|
||||
print "$_\n";
|
||||
wait;
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
use Coro;
|
||||
$ret = Coro::Channel->new;
|
||||
@nums = qw(1 32 2 59 2 39 43 15 8 9 12 9 11);
|
||||
|
||||
for my $n (@nums){
|
||||
async {
|
||||
Coro::cede for 1..$n;
|
||||
$ret->put($n);
|
||||
}
|
||||
}
|
||||
|
||||
print $ret->get,"\n" for 1..@nums;
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
(notonline)-->
|
||||
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- (multitasking)</span>
|
||||
<span style="color: #004080;">integer</span> <span style="color: #000000;">count</span>
|
||||
|
||||
<span style="color: #008080;">procedure</span> <span style="color: #000000;">sleeper</span><span style="color: #0000FF;">(</span><span style="color: #004080;">integer</span> <span style="color: #000000;">key</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #0000FF;">?</span> <span style="color: #000000;">key</span> <span style="color: #000080;font-style:italic;">-- (or maybe res &= key)</span>
|
||||
<span style="color: #000000;">count</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
|
||||
|
||||
<span style="color: #000080;font-style:italic;">--sequence s = command_line()[3..$]</span>
|
||||
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"3 1 4 1 5 9 2 6 5"</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">if</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)=</span><span style="color: #000000;">0</span> <span style="color: #008080;">then</span>
|
||||
<span style="color: #7060A8;">puts</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"Nothing to sort.\n"</span><span style="color: #0000FF;">)</span>
|
||||
<span style="color: #008080;">else</span>
|
||||
<span style="color: #000000;">count</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">0</span>
|
||||
<span style="color: #008080;">for</span> <span style="color: #000000;">i</span><span style="color: #0000FF;">=</span><span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">do</span>
|
||||
<span style="color: #004080;">object</span> <span style="color: #000000;">si</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">to_number</span><span style="color: #0000FF;">(</span><span style="color: #000000;">s</span><span style="color: #0000FF;">[</span><span style="color: #000000;">i</span><span style="color: #0000FF;">])</span>
|
||||
<span style="color: #008080;">if</span> <span style="color: #004080;">integer</span><span style="color: #0000FF;">(</span><span style="color: #000000;">si</span><span style="color: #0000FF;">)</span> <span style="color: #008080;">then</span>
|
||||
<span style="color: #004080;">atom</span> <span style="color: #000000;">task</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">task_create</span><span style="color: #0000FF;">(</span><span style="color: #000000;">sleeper</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">si</span><span style="color: #0000FF;">})</span>
|
||||
<span style="color: #7060A8;">task_schedule</span><span style="color: #0000FF;">(</span><span style="color: #000000;">task</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">si</span><span style="color: #0000FF;">/</span><span style="color: #000000;">10</span><span style="color: #0000FF;">,</span><span style="color: #000000;">si</span><span style="color: #0000FF;">/</span><span style="color: #000000;">10</span><span style="color: #0000FF;">})</span>
|
||||
<span style="color: #000000;">count</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
|
||||
|
||||
<span style="color: #008080;">while</span> <span style="color: #000000;">count</span> <span style="color: #008080;">do</span>
|
||||
<span style="color: #7060A8;">task_yield</span><span style="color: #0000FF;">()</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
|
||||
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
|
||||
<!--
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
(de sleepSort (Lst)
|
||||
(make
|
||||
(for (I . N) Lst
|
||||
(task (- I) (* N 100) N N I I
|
||||
(link N)
|
||||
(pop 'Lst)
|
||||
(task (- I)) ) )
|
||||
(wait NIL (not Lst)) ) )
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
(de sleepSort (Lst)
|
||||
(make
|
||||
(for N Lst
|
||||
(task (pipe (wait (* N 100))) N N
|
||||
(link N)
|
||||
(pop 'Lst)
|
||||
(task (close @)) ) )
|
||||
(wait NIL (not Lst)) ) )
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
(for N (3 1 4 1 5 9 2 6 5)
|
||||
(unless (fork)
|
||||
(call 'sleep N)
|
||||
(msg N)
|
||||
(bye) ) )
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
#!/usr/bin/env pike
|
||||
|
||||
int main(int argc, array(string) argv)
|
||||
{
|
||||
foreach(argv[1..], string value)
|
||||
{
|
||||
int v = (int)value;
|
||||
if(v<0)
|
||||
continue;
|
||||
call_out(print, v, value);
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
void print(string value)
|
||||
{
|
||||
write("%s\n", value);
|
||||
if(find_call_out(print)==-1)
|
||||
exit(0);
|
||||
return;
|
||||
}
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
sleep_sort(L) :-
|
||||
thread_pool_create(rosetta, 1024, []) ,
|
||||
maplist(initsort, L, LID),
|
||||
maplist(thread_join, LID, _LStatus),
|
||||
thread_pool_destroy(rosetta).
|
||||
|
||||
initsort(V, Id) :-
|
||||
thread_create_in_pool(rosetta, (sleep(V), writeln(V)), Id, []).
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
NewMap threads()
|
||||
|
||||
Procedure Foo(n)
|
||||
Delay(n)
|
||||
PrintN(Str(n))
|
||||
EndProcedure
|
||||
|
||||
If OpenConsole()
|
||||
For i=1 To CountProgramParameters()
|
||||
threads(Str(i)) = CreateThread(@Foo(), Val(ProgramParameter()))
|
||||
Next
|
||||
|
||||
ForEach threads()
|
||||
WaitThread(threads())
|
||||
Next
|
||||
Print("Press ENTER to exit"): Input()
|
||||
EndIf
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
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)
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
#!/usr/bin/env python3
|
||||
from asyncio import run, sleep, wait
|
||||
from sys import argv
|
||||
|
||||
async def f(n):
|
||||
await sleep(n)
|
||||
print(n)
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(wait(map(f, map(int, argv[1:]))))
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
/*REXX program implements a sleep sort (with numbers entered from the command line (CL).*/
|
||||
numeric digits 300 /*over the top, but what the hey! */
|
||||
/* (above) ··· from vaudeville. */
|
||||
@.= /*placeholder for the array of numbers.*/
|
||||
stuff= 1e9 50 5 40 4 1 100 30 3 12 2 8 9 7 6 6 10 20 0 /*alphabetically ··· so far.*/
|
||||
parse arg numbers /*obtain optional arguments from the CL*/
|
||||
if numbers='' then numbers= stuff /*Not specified? Then use the default.*/
|
||||
N= words(numbers) /*N is the number of numbers in list. */
|
||||
w= length(N) /*width of N (used for nice output). */
|
||||
parse upper version !ver . /*obtain which REXX we're running under*/
|
||||
!regina= ('REXX-REGINA'==left(!ver, 11) ) /*indicate (or not) if this is Regina. */
|
||||
say N 'numbers to be sorted:' numbers /*informative informational information*/
|
||||
/*from department of redundancy depart.*/
|
||||
do j=1 for N /*let's start to boogie─woogie da sort.*/
|
||||
@.j= word(numbers, j) /*plug in a single number at a time. */
|
||||
if datatype(@.j, 'N') then @.j= @.j / 1 /*normalize it if it's a numeric number*/
|
||||
if !regina then call fork /*only REGINA REXX supports FORK BIF.*/
|
||||
call sortItem j /*start a sort for an array number. */
|
||||
end /*j*/
|
||||
|
||||
do forever while \inOrder(N) /*wait for the sorts to complete. */
|
||||
call delay 1 /*one second is minimum effective time.*/
|
||||
end /*forever while*/ /*well heck, other than zero seconds. */
|
||||
|
||||
m= max(length(@.1), length(@.N) ) /*width of smallest or largest number. */
|
||||
say; say 'after sort:' /*display a blank line and a title. */
|
||||
|
||||
do k=1 for N /*list the (sorted) array's elements.*/
|
||||
say left('', 20) 'array element' right(k, w) '───►' right(@.k, m)
|
||||
end /*k*/
|
||||
exit /*stick a fork in it, we're all done. */
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
sortItem: procedure expose @.; parse arg ? /*sorts a single (numeric) item. */
|
||||
do Asort=1 until \switched /*sort unsorted array until it's sorted*/
|
||||
switched= 0 /*it's all hunky─dorey, happy─dappy ···*/
|
||||
do i=1 while @.i\=='' & \switched
|
||||
if @.? >= @.i then iterate /*item is in order. */
|
||||
parse value @.? @.i with @.i @.?
|
||||
switched= 1 /* [↑] swapped one.*/
|
||||
end /*i*/
|
||||
if Asort//?==0 then call delay switched /*sleep if last item*/
|
||||
end /*Asort*/
|
||||
return /*Sleeping Beauty awakes. Not to worry: (c)=circa 1697.*/
|
||||
/*──────────────────────────────────────────────────────────────────────────────────────*/
|
||||
inOrder: procedure expose @.; parse arg howMany /*is the array in numerical order? */
|
||||
do m=1 for howMany-1; next= m+1; if @.m>@.next then return 0 /*¬ in order*/
|
||||
end /*m*/ /*keep looking for fountain of youth. */
|
||||
return 1 /*yes, indicate with an indicator. */
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
#lang racket
|
||||
|
||||
;; accepts a list to sort
|
||||
(define (sleep-sort lst)
|
||||
(define done (make-channel))
|
||||
(for ([elem lst])
|
||||
(thread
|
||||
(λ ()
|
||||
(sleep elem)
|
||||
(channel-put done elem))))
|
||||
(for/list ([_ (length lst)])
|
||||
(channel-get done)))
|
||||
|
||||
;; outputs '(2 5 5 7 8 9 10)
|
||||
(sleep-sort '(5 8 2 7 9 10 5))
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
await map -> $delay { start { sleep $delay ; say $delay } },
|
||||
<6 8 1 12 2 14 5 2 1 0>;
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
#!/usr/bin/env raku
|
||||
use v6;
|
||||
react whenever Supply.from-list(@*ARGS).start({ .&sleep // +$_ }).flat { .say }
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
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
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
use std::thread;
|
||||
|
||||
fn sleepsort<I: Iterator<Item=u32>>(nums: I) {
|
||||
let threads: Vec<_> = nums.map(|n|
|
||||
thread::spawn(move || {
|
||||
thread::sleep_ms(n);
|
||||
println!("{}", n); })).collect();
|
||||
for t in threads { t.join(); }
|
||||
}
|
||||
|
||||
fn main() {
|
||||
sleepsort(std::env::args().skip(1).map(|s| s.parse().unwrap()));
|
||||
}
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
/$>\ input until eof
|
||||
#/?<\?,/ foreach: fork
|
||||
\ &/:+ copy and\
|
||||
/:\?-; delay /
|
||||
\.# print and exit thread
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
object SleepSort {
|
||||
|
||||
def main(args: Array[String]): Unit = {
|
||||
val nums = args.map(_.toInt)
|
||||
sort(nums)
|
||||
Thread.sleep(nums.max * 21) // Keep the JVM alive for the example
|
||||
}
|
||||
|
||||
def sort(nums: Seq[Int]): Unit =
|
||||
nums.foreach(i => new Thread {
|
||||
override def run() {
|
||||
Thread.sleep(i * 20) // just `i` is unpredictable with small numbers
|
||||
print(s"$i ")
|
||||
}
|
||||
}.start())
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
$ scala SleepSort 1 3 6 0 9 7 4 2 5 8
|
||||
0 1 2 3 4 5 5 6 7 8 9
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
ARGV.map{.to_i}.map{ |i|
|
||||
{Sys.sleep(i); say i}.fork;
|
||||
}.each{.wait};
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
SIMULATION
|
||||
BEGIN
|
||||
|
||||
PROCESS CLASS SORTITEM(N); INTEGER N;
|
||||
BEGIN
|
||||
HOLD(N);
|
||||
OUTINT(N, 3);
|
||||
END;
|
||||
|
||||
INTEGER I;
|
||||
FOR I := 3, 2, 4, 7, 3, 6, 9, 1 DO
|
||||
BEGIN
|
||||
REF(SORTITEM) SI;
|
||||
SI :- NEW SORTITEM(I);
|
||||
ACTIVATE SI;
|
||||
END;
|
||||
HOLD(100000);
|
||||
OUTIMAGE;
|
||||
|
||||
END;
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
import Foundation
|
||||
|
||||
for i in [5, 2, 4, 6, 1, 7, 20, 14] {
|
||||
let time = dispatch_time(DISPATCH_TIME_NOW,
|
||||
Int64(i * Int(NSEC_PER_SEC)))
|
||||
|
||||
dispatch_after(time, dispatch_get_main_queue()) {
|
||||
print(i)
|
||||
}
|
||||
}
|
||||
|
||||
CFRunLoopRun()
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
#!/bin/env tclsh
|
||||
set count 0
|
||||
proc process val {
|
||||
puts $val
|
||||
incr ::count
|
||||
}
|
||||
# Schedule the output of the values
|
||||
foreach val $argv {
|
||||
after [expr {$val * 10}] [list process $val]
|
||||
}
|
||||
# Run event loop until all values output...
|
||||
while {$count < $argc} {
|
||||
vwait count
|
||||
}
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
set sorted {}
|
||||
lmap x $argv {after $x [list lappend sorted $x]}
|
||||
while {[llength $sorted] != $argc} {
|
||||
vwait sorted
|
||||
}
|
||||
puts $sorted
|
||||
|
|
@ -0,0 +1,37 @@
|
|||
#! /usr/bin/env tclsh
|
||||
|
||||
package require Tcl 8.6
|
||||
|
||||
# By aspect (https://wiki.tcl-lang.org/page/aspect). Modified slightly.
|
||||
# 1. Schedule N delayed calls to our own coroutine.
|
||||
# 2. Yield N times to grab the scheduled values. Print each.
|
||||
# 3. Store the sorted list in $varName.
|
||||
proc sleep-sort {ls varName} {
|
||||
foreach x $ls {
|
||||
after $x [info coroutine] $x
|
||||
}
|
||||
|
||||
set $varName [lmap x $ls {
|
||||
set newX [yield]
|
||||
puts $newX
|
||||
lindex $newX
|
||||
}]
|
||||
}
|
||||
|
||||
# Ensure the list is suitable for use with [sleep-sort].
|
||||
proc validate ls {
|
||||
if {[llength $ls] == 0} {
|
||||
error {list is empty}
|
||||
}
|
||||
|
||||
foreach x $ls {
|
||||
if {![string is integer -strict $x] || $x < 0} {
|
||||
error [list invalid value: $x]
|
||||
}
|
||||
}
|
||||
|
||||
return $ls
|
||||
}
|
||||
|
||||
coroutine c sleep-sort [validate $argv] ::sorted
|
||||
vwait sorted
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
f() {
|
||||
sleep "$1"
|
||||
echo "$1"
|
||||
}
|
||||
while [ -n "$1" ]
|
||||
do
|
||||
f "$1" &
|
||||
shift
|
||||
done
|
||||
wait
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
import time
|
||||
import sync
|
||||
|
||||
fn main() {
|
||||
mut wg := sync.new_waitgroup()
|
||||
test_arr := [3, 2, 1, 4, 1, 7]
|
||||
wg.add(test_arr.len)
|
||||
for i, value in test_arr {
|
||||
go sort(i, value, mut wg)
|
||||
}
|
||||
wg.wait()
|
||||
println('Printed sorted array')
|
||||
}
|
||||
|
||||
fn sort(id int, value int, mut wg sync.WaitGroup) {
|
||||
time.sleep(value * time.millisecond) // can change duration to second or others
|
||||
println(value)
|
||||
wg.done()
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
Imports System.Threading
|
||||
|
||||
Module Module1
|
||||
|
||||
Sub SleepSort(items As IEnumerable(Of Integer))
|
||||
For Each item In items
|
||||
Task.Factory.StartNew(Sub()
|
||||
Thread.Sleep(1000 * item)
|
||||
Console.WriteLine(item)
|
||||
End Sub)
|
||||
Next
|
||||
End Sub
|
||||
|
||||
Sub Main()
|
||||
SleepSort({1, 5, 2, 1, 8, 10, 3})
|
||||
Console.ReadKey()
|
||||
End Sub
|
||||
|
||||
End Module
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
import "timer" for Timer
|
||||
import "io" for Stdout
|
||||
import "os" for Process
|
||||
|
||||
var args = Process.arguments
|
||||
var n = args.count
|
||||
if (n < 2) Fiber.abort("There must be at least two arguments passed.")
|
||||
var list = args.map{ |a| Num.fromString(a) }.toList
|
||||
if (list.any { |i| i == null || !i.isInteger || i < 0 } ) {
|
||||
Fiber.abort("All arguments must be non-negative integers.")
|
||||
}
|
||||
var max = list.reduce { |acc, i| acc = (i > acc) ? i : acc }
|
||||
var fibers = List.filled(max+1, null)
|
||||
System.print("Before: %(list.join(" "))")
|
||||
for (i in list) {
|
||||
var sleepSort = Fiber.new { |i|
|
||||
Timer.sleep(1000)
|
||||
Fiber.yield(i)
|
||||
}
|
||||
fibers[i] = sleepSort
|
||||
}
|
||||
System.write("After : ")
|
||||
for (i in 0..max) {
|
||||
var fib = fibers[i]
|
||||
if (fib) {
|
||||
System.write("%(fib.call(i)) ")
|
||||
Stdout.flush()
|
||||
}
|
||||
}
|
||||
System.print()
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
vm.arglist.apply(fcn(n){ Atomic.sleep(n); print(n) }.launch);
|
||||
Atomic.waitFor(fcn{ vm.numThreads == 1 }); Atomic.sleep(2); println();
|
||||
Loading…
Add table
Add a link
Reference in a new issue