task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#Vlang
Vlang
import rand   fn shuffle_array(mut arr []int) { for i := arr.len - 1; i >= 0; i-- { j := rand.intn(i + 1) arr[i], arr[j] = arr[j], arr[i] } }   fn is_sorted(arr []int) bool { for i := 0; i < arr.len - 1; i++ { if arr[i] > arr[i + 1] { return false } } return true }   fn sort_array(mut arr []int) { for !is_sorted(arr) { shuffle_array(mut arr) println('After Shuffle: $arr') } }   fn main() { mut array := [6, 9, 1, 4] println('Input: $array') sort_array(mut array) println('Output: $array') }
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#g-fu
g-fu
  (fun bubbles (vs) (let done? F n (len vs))   (while (not done?) (set done? T n (- n 1))   (for (n i) (let x (# vs i) j (+ i 1) y (# vs j)) (if (> x y) (set done? F (# vs i) y (# vs j) x))))   vs)   (bubbles '(2 1 3)) --- (1 2 3)  
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#PL.2FI
PL/I
SORT: PROCEDURE OPTIONS (MAIN); DECLARE A(0:9) FIXED STATIC INITIAL (5, 2, 7, 1, 9, 8, 6, 3, 4, 0);   CALL GNOME_SORT (A); put skip edit (A) (f(7));   GNOME_SORT: PROCEDURE (A) OPTIONS (REORDER); /* 9 September 2015 */ declare A(*) fixed; declare t fixed; declare (i, j) fixed;   i = 1; j = 2; do while (i <= hbound(A)); if a(i-1) <= a(i) then do; i = j; j = j + 1; end; else do; t = a(i-1); a(i-1) = a(i); a(i) = t; i = i - 1; if i = 0 then do; i = j; j = j + 1; end; end; end;   END GNOME_SORT;   END SORT;
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#Pascal
Pascal
use strict; use warnings; use feature 'say';   sub cocktail_sort { my @a = @_; while (1) { my $swapped_forward = 0; for my $i (0..$#a-1) { if ($a[$i] gt $a[$i+1]) { @a[$i, $i+1] = @a[$i+1, $i]; $swapped_forward = 1; } } last if not $swapped_forward;   my $swapped_backward = 0; for my $i (reverse 0..$#a-1) { if ($a[$i] gt $a[$i+1]) { @a[$i, $i+1] = @a[$i+1, $i]; $swapped_backward = 1; } } last if not $swapped_backward; } @a }   say join ' ', cocktail_sort( <t h e q u i c k b r o w n f o x j u m p s o v e r t h e l a z y d o g> );
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Go
Go
package main   import ( "fmt" "net" )   func main() { conn, err := net.Dial("tcp", "localhost:256") if err != nil { fmt.Println(err) return } defer conn.Close() _, err = conn.Write([]byte("hello socket world")) if err != nil { fmt.Println(err) } }
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Groovy
Groovy
s = new java.net.Socket("localhost", 256) s << "hello socket world" s.close()
http://rosettacode.org/wiki/Sleeping_Beauty_problem
Sleeping Beauty problem
Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss. If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to estimate the probability that the coin toss was heads. Her estimate is recorded and she is then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied. If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to estimate the probability the coin toss was heads, but is then given a drug which makes her forget that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday. Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always estimate the probability of heads as 1/2, since she does not have any additional information. Others have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate should be 1/3 heads. Task Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty is asked the question.
#Swift
Swift
let experiments = 1000000 var heads = 0 var wakenings = 0 for _ in (1...experiments) { wakenings += 1 switch (Int.random(in: 0...1)) { case 0: heads += 1 default: wakenings += 1 } } print("Wakenings over \(experiments) experiments: \(wakenings)") print("Sleeping Beauty should estimate a credence of: \(Double(heads) / Double(wakenings))")
http://rosettacode.org/wiki/Sleeping_Beauty_problem
Sleeping Beauty problem
Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss. If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to estimate the probability that the coin toss was heads. Her estimate is recorded and she is then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied. If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to estimate the probability the coin toss was heads, but is then given a drug which makes her forget that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday. Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always estimate the probability of heads as 1/2, since she does not have any additional information. Others have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate should be 1/3 heads. Task Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty is asked the question.
#Vlang
Vlang
import rand import rand.seed   fn sleeping_beauty(reps int) f64 { mut wakings := 0 mut heads := 0 for _ in 0..reps { coin := rand.intn(2) or {0} // heads = 0, tails = 1 say wakings++ if coin == 0 { heads++ } else { wakings++ } } println("Wakings over $reps repetitions = $wakings") return f64(heads) / f64(wakings) * 100 }   fn main() { rand.seed(seed.time_seed_array(2)) pc := sleeping_beauty(1000000) println("Percentage probability of heads on waking = $pc%") }
http://rosettacode.org/wiki/Sleeping_Beauty_problem
Sleeping Beauty problem
Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss. If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to estimate the probability that the coin toss was heads. Her estimate is recorded and she is then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied. If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to estimate the probability the coin toss was heads, but is then given a drug which makes her forget that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday. Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always estimate the probability of heads as 1/2, since she does not have any additional information. Others have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate should be 1/3 heads. Task Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty is asked the question.
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var rand = Random.new()   var sleepingBeauty = Fn.new { |reps| var wakings = 0 var heads = 0 for (i in 0...reps) { var coin = rand.int(2) // heads = 0, tails = 1 say wakings = wakings + 1 if (coin == 0) { heads = heads + 1 } else { wakings = wakings + 1 } } Fmt.print("Wakings over $,d repetitions = $,d", reps, wakings) return heads/wakings * 100 }   var pc = sleepingBeauty.call(1e6) Fmt.print("Percentage probability of heads on waking = $f\%", pc)
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also OEIS A019546: Primes whose digits are primes. https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
#jq
jq
def Smarandache_primes: # Output: a naively constructed stream of candidate strings of length >= 1 def Smarandache_candidates: def unconstrained($length): if $length==1 then "2", "3", "5", "7" else ("2", "3", "5", "7") as $n | $n + unconstrained($length -1 ) end; unconstrained(. - 1) as $u | ("3", "7") as $tail | $u + $tail ;   2,3,5,7, (range(2; infinite) | Smarandache_candidates | tonumber | select(is_prime));   # Override jq's incorrect definition of nth/2 # Emit the $n-th value of the stream, counting from 0; or emit nothing def nth($n; s): if $n < 0 then error("nth/2 doesn't support negative indices") else label $out | foreach s as $x (-1; .+1; select(. >= $n) | $x, break $out) end;   "First 25:", [limit(25; Smarandache_primes)],   # jq counts from 0 so: "\nThe hundredth: \(nth(99; Smarandache_primes))"
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also OEIS A019546: Primes whose digits are primes. https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
#Julia
Julia
  using Combinatorics, Primes   combodigits(len) = sort!(unique(map(y -> join(y, ""), with_replacement_combinations("2357", len))))   function getprimes(N, maxdigits=9) ret = [2, 3, 5, 7] perms = Int[] for i in 1:maxdigits-1, combo in combodigits(i), perm in permutations(combo) n = parse(Int64, String(perm)) * 10 push!(perms, n + 3, n + 7) end for perm in sort!(perms) if isprime(perm) && !(perm in ret) push!(ret, perm) if length(ret) >= N return ret end end end end   const v = getprimes(10000) println("The first 25 Smarandache primes are: ", v[1:25]) println("The 100th Smarandache prime is: ", v[100]) println("The 10000th Smarandache prime is: ", v[10000])  
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also OEIS A019546: Primes whose digits are primes. https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
#Lua
Lua
-- FUNCS: local function T(t) return setmetatable(t, {__index=table}) end table.firstn = function(t,n) local s=T{} n=n>#t and #t or n for i = 1,n do s[i]=t[i] end return s end   -- SIEVE: local sieve, S = {}, 50000 for i = 2,S do sieve[i]=true end for i = 2,S do if sieve[i] then for j=i*i,S,i do sieve[j]=nil end end end   -- TASKS: local digs, cans, spds, N = {2,3,5,7}, T{0}, T{}, 100 while #spds < N do local c = cans:remove(1) for _,d in ipairs(digs) do cans:insert(c*10+d) end if sieve[c] then spds:insert(c) end end print("1-25 : " .. spds:firstn(25):concat(" ")) print("100th: " .. spds[100])
http://rosettacode.org/wiki/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Snake is a game where the player maneuvers a line which grows in length every time the snake reaches a food source. Task Implement a variant of the Snake game, in any interactive environment, in which a sole player attempts to eat items by running into them with the head of the snake. Each item eaten makes the snake longer and a new item is randomly generated somewhere else on the plane. The game ends when the snake attempts to eat himself.
#C.2B.2B
C++
  #include <windows.h> #include <ctime> #include <iostream> #include <string>   const int WID = 60, HEI = 30, MAX_LEN = 600; enum DIR { NORTH, EAST, SOUTH, WEST };   class snake { public: snake() { console = GetStdHandle( STD_OUTPUT_HANDLE ); SetConsoleTitle( "Snake" ); COORD coord = { WID + 1, HEI + 2 }; SetConsoleScreenBufferSize( console, coord ); SMALL_RECT rc = { 0, 0, WID, HEI + 1 }; SetConsoleWindowInfo( console, TRUE, &rc ); CONSOLE_CURSOR_INFO ci = { 1, false }; SetConsoleCursorInfo( console, &ci ); } void play() { std::string a; while( 1 ) { createField(); alive = true; while( alive ) { drawField(); readKey(); moveSnake(); Sleep( 50 ); } COORD c = { 0, HEI + 1 }; SetConsoleCursorPosition( console, c ); SetConsoleTextAttribute( console, 0x000b ); std::cout << "Play again [Y/N]? "; std::cin >> a; if( a.at( 0 ) != 'Y' && a.at( 0 ) != 'y' ) return; } } private: void createField() { COORD coord = { 0, 0 }; DWORD c; FillConsoleOutputCharacter( console, ' ', ( HEI + 2 ) * 80, coord, &c ); FillConsoleOutputAttribute( console, 0x0000, ( HEI + 2 ) * 80, coord, &c ); SetConsoleCursorPosition( console, coord ); int x = 0, y = 1; for( ; x < WID * HEI; x++ ) brd[x] = 0; for( x = 0; x < WID; x++ ) { brd[x] = brd[x + WID * ( HEI - 1 )] = '+'; } for( ; y < HEI; y++ ) { brd[0 + WID * y] = brd[WID - 1 + WID * y] = '+'; } do { x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 ); } while( brd[x + WID * y] ); brd[x + WID * y] = '@'; tailIdx = 0; headIdx = 4; x = 3; y = 2; for( int c = tailIdx; c < headIdx; c++ ) { brd[x + WID * y] = '#'; snk[c].X = 3 + c; snk[c].Y = 2; } head = snk[3]; dir = EAST; points = 0; } void readKey() { if( GetAsyncKeyState( 39 ) & 0x8000 ) dir = EAST; if( GetAsyncKeyState( 37 ) & 0x8000 ) dir = WEST; if( GetAsyncKeyState( 38 ) & 0x8000 ) dir = NORTH; if( GetAsyncKeyState( 40 ) & 0x8000 ) dir = SOUTH; } void drawField() { COORD coord; char t; for( int y = 0; y < HEI; y++ ) { coord.Y = y; for( int x = 0; x < WID; x++ ) { t = brd[x + WID * y]; if( !t ) continue; coord.X = x; SetConsoleCursorPosition( console, coord ); if( coord.X == head.X && coord.Y == head.Y ) { SetConsoleTextAttribute( console, 0x002e ); std::cout << 'O'; SetConsoleTextAttribute( console, 0x0000 ); continue; } switch( t ) { case '#': SetConsoleTextAttribute( console, 0x002a ); break; case '+': SetConsoleTextAttribute( console, 0x0019 ); break; case '@': SetConsoleTextAttribute( console, 0x004c ); break; } std::cout << t; SetConsoleTextAttribute( console, 0x0000 ); } } std::cout << t; SetConsoleTextAttribute( console, 0x0007 ); COORD c = { 0, HEI }; SetConsoleCursorPosition( console, c ); std::cout << "Points: " << points; } void moveSnake() { switch( dir ) { case NORTH: head.Y--; break; case EAST: head.X++; break; case SOUTH: head.Y++; break; case WEST: head.X--; break; } char t = brd[head.X + WID * head.Y]; if( t && t != '@' ) { alive = false; return; } brd[head.X + WID * head.Y] = '#'; snk[headIdx].X = head.X; snk[headIdx].Y = head.Y; if( ++headIdx >= MAX_LEN ) headIdx = 0; if( t == '@' ) { points++; int x, y; do { x = rand() % WID; y = rand() % ( HEI >> 1 ) + ( HEI >> 1 ); } while( brd[x + WID * y] ); brd[x + WID * y] = '@'; return; } SetConsoleCursorPosition( console, snk[tailIdx] ); std::cout << ' '; brd[snk[tailIdx].X + WID * snk[tailIdx].Y] = 0; if( ++tailIdx >= MAX_LEN ) tailIdx = 0; } bool alive; char brd[WID * HEI]; HANDLE console; DIR dir; COORD snk[MAX_LEN]; COORD head; int tailIdx, headIdx, points; }; int main( int argc, char* argv[] ) { srand( static_cast<unsigned>( time( NULL ) ) ); snake s; s.play(); return 0; }  
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers. Example Using the number 166 Find the prime factors of 166 which are: 2 x 83 Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13 Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13 Therefore, the number 166 is a Smith number. Task Write a program to find all Smith numbers below 10000. See also from Wikipedia:   [Smith number]. from MathWorld:   [Smith number]. from OEIS A6753:   [OEIS sequence A6753]. from OEIS A104170:   [Number of Smith numbers below 10^n]. from The Prime pages:   [Smith numbers].
#AWK
AWK
  # syntax: GAWK -f SMITH_NUMBERS.AWK # converted from C BEGIN { limit = 10000 printf("Smith Numbers < %d:\n",limit) for (a=4; a<limit; a++) { num_factors = num_prime_factors(a) if (num_factors < 2) { continue } prime_factors(a) if (sum_digits(a) == sum_factors(num_factors)) { printf("%4d ",a) if (++cr % 16 == 0) { printf("\n") } } delete arr } printf("\n") exit(0) } function num_prime_factors(x, p,pf) { p = 2 pf = 0 if (x == 1) { return(1) } while (1) { if (!(x % p)) { pf++ x = int(x/p) if (x == 1) { return(pf) } } else { p++ } } } function prime_factors(x, p,pf) { p = 2 pf = 0 if (x == 1) { arr[pf] = 1 } else { while (1) { if (!(x % p)) { arr[pf++] = p x = int(x/p) if (x == 1) { return } } else { p++ } } } } function sum_digits(x, sum,y) { while (x) { y = x % 10 sum += y x = int(x/10) } return(sum) } function sum_factors(x, a,sum) { sum = 0 for (a=0; a<x; a++) { sum += sum_digits(arr[a]) } return(sum) }  
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle
Solve a Hidato puzzle
The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always connected. The number “1” is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique. It may be assumed that the difference between numbers present on the grid is not greater than lucky 13. The aim is to place a natural number in each blank square so that in the sequence of numbered squares from “1” upwards, each square is in the wp:Moore neighborhood of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints). Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order. A square may only contain one number. In a proper Hidato puzzle, the solution is unique. For example the following problem has the following solution, with path marked on it: Related tasks A* search algorithm N-queens problem Solve a Holy Knight's tour Solve a Knight's tour Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle;
#Elixir
Elixir
# Solve a Hidato Like Puzzle with Warnsdorff like logic applied # defmodule HLPsolver do defmodule Cell do defstruct value: -1, used: false, adj: [] end   def solve(str, adjacent, print_out\\true) do board = setup(str) if print_out, do: print(board, "Problem:") {start, _} = Enum.find(board, fn {_,cell} -> cell.value==1 end) board = set_adj(board, adjacent) zbl = for %Cell{value: n} <- Map.values(board), into: %{}, do: {n, true} try do solve(board, start, 1, zbl, map_size(board)) IO.puts "No solution" catch {:ok, result} -> if print_out, do: print(result, "Solution:"), else: result end end   defp solve(board, position, seq_num, zbl, goal) do value = board[position].value cond do value > 0 and value != seq_num -> nil value == 0 and zbl[seq_num] -> nil true -> cell = %Cell{board[position] | value: seq_num, used: true} board = %{board | position => cell} if seq_num == goal, do: throw({:ok, board}) Enum.each(wdof(board, cell.adj), fn pos -> solve(board, pos, seq_num+1, zbl, goal) end) end end   defp setup(str) do lines = String.strip(str) |> String.split(~r/(\n|\r\n|\r)/) |> Enum.with_index for {line,i} <- lines, {char,j} <- Enum.with_index(String.split(line)),  :error != Integer.parse(char), into: %{} do {n,_} = Integer.parse(char) {{i,j}, %Cell{value: n}} end end   defp set_adj(board, adjacent) do Enum.reduce(Map.keys(board), board, fn {x,y},map -> adj = Enum.map(adjacent, fn {i,j} -> {x+i, y+j} end) |> Enum.reduce([], fn pos,acc -> if board[pos], do: [pos | acc], else: acc end) Map.update!(map, {x,y}, fn cell -> %Cell{cell | adj: adj} end) end) end   defp wdof(board, adj) do # Warnsdorf's rule Enum.reject(adj, fn pos -> board[pos].used end) |> Enum.sort_by(fn pos -> Enum.count(board[pos].adj, fn p -> not board[p].used end) end) end   def print(board, title) do IO.puts "\n#{title}" {xmin, xmax} = Map.keys(board) |> Enum.map(fn {x,_} -> x end) |> Enum.min_max {ymin, ymax} = Map.keys(board) |> Enum.map(fn {_,y} -> y end) |> Enum.min_max len = map_size(board) |> to_char_list |> length space = String.duplicate(" ", len) Enum.each(xmin..xmax, fn x -> Enum.map_join(ymin..ymax, " ", fn y -> case Map.get(board, {x,y}) do nil -> space cell -> to_string(cell.value) |> String.rjust(len) end end) |> IO.puts end) end end
http://rosettacode.org/wiki/Sokoban
Sokoban
Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character array where space is an empty square # is a wall @ is the player $ is a box . is a goal + is the player on a goal * is a box on a goal ####### # # # # #. # # #. $$ # #.$$ # #.# @# ####### Sokoban solutions are usually stored in the LURD format, where lowercase l, u, r and d represent a move in that (left, up, right, down) direction and capital LURD represents a push. Please state if you use some other format for either the input or output, and why. For more information, see the Sokoban wiki.
#Python
Python
from array import array from collections import deque import psyco   data = [] nrows = 0 px = py = 0 sdata = "" ddata = ""   def init(board): global data, nrows, sdata, ddata, px, py data = filter(None, board.splitlines()) nrows = max(len(r) for r in data)   maps = {' ':' ', '.': '.', '@':' ', '#':'#', '$':' '} mapd = {' ':' ', '.': ' ', '@':'@', '#':' ', '$':'*'}   for r, row in enumerate(data): for c, ch in enumerate(row): sdata += maps[ch] ddata += mapd[ch] if ch == '@': px = c py = r   def push(x, y, dx, dy, data): if sdata[(y+2*dy) * nrows + x+2*dx] == '#' or \ data[(y+2*dy) * nrows + x+2*dx] != ' ': return None   data2 = array("c", data) data2[y * nrows + x] = ' ' data2[(y+dy) * nrows + x+dx] = '@' data2[(y+2*dy) * nrows + x+2*dx] = '*' return data2.tostring()   def is_solved(data): for i in xrange(len(data)): if (sdata[i] == '.') != (data[i] == '*'): return False return True   def solve(): open = deque([(ddata, "", px, py)]) visited = set([ddata]) dirs = ((0, -1, 'u', 'U'), ( 1, 0, 'r', 'R'), (0, 1, 'd', 'D'), (-1, 0, 'l', 'L'))   lnrows = nrows while open: cur, csol, x, y = open.popleft()   for di in dirs: temp = cur dx, dy = di[0], di[1]   if temp[(y+dy) * lnrows + x+dx] == '*': temp = push(x, y, dx, dy, temp) if temp and temp not in visited: if is_solved(temp): return csol + di[3] open.append((temp, csol + di[3], x+dx, y+dy)) visited.add(temp) else: if sdata[(y+dy) * lnrows + x+dx] == '#' or \ temp[(y+dy) * lnrows + x+dx] != ' ': continue   data2 = array("c", temp) data2[y * lnrows + x] = ' ' data2[(y+dy) * lnrows + x+dx] = '@' temp = data2.tostring()   if temp not in visited: if is_solved(temp): return csol + di[2] open.append((temp, csol + di[2], x+dx, y+dy)) visited.add(temp)   return "No solution"     level = """\ ####### # # # # #. # # #. $$ # #.$$ # #.# @# #######"""   psyco.full() init(level) print level, "\n\n", solve()
http://rosettacode.org/wiki/Solve_a_Holy_Knight%27s_tour
Solve a Holy Knight's tour
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. This kind of knight's tour puzzle is similar to   Hidato. The present task is to produce a solution to such problems. At least demonstrate your program by solving the following: Example 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 Note that the zeros represent the available squares, not the pennies. Extra credit is available for other interesting examples. Related tasks A* search algorithm Knight's tour N-queens problem Solve a Hidato puzzle Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle
#Phix
Phix
with javascript_semantics sequence board, warnsdorffs integer size, limit, nchars string fmt, blank constant ROW = 1, COL = 2, moves = {{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}} function onboard(integer row, integer col) return row>=1 and row<=size and col>=nchars and col<=nchars*size end function procedure init_warnsdorffs() for row=1 to size do for col=nchars to nchars*size by nchars do for move=1 to length(moves) do integer nrow = row+moves[move][ROW], ncol = col+moves[move][COL]*nchars if onboard(nrow,ncol) then warnsdorffs[nrow][ncol] += 1 end if end for end for end for end procedure atom t0 = time(), t1 = time()+1 integer tries = 0, backtracks = 0 function solve(integer row, integer col, integer n) if time()>t1 and platform()!=JS then ?{row,floor(col/nchars),n,tries} puts(1,join(board,"\n")&"\n") t1 = time()+1 end if tries+= 1 if n>limit then return 1 end if sequence wmoves = {} integer nrow, ncol for move=1 to length(moves) do nrow = row+moves[move][ROW] ncol = col+moves[move][COL]*nchars if onboard(nrow,ncol) and board[nrow][ncol]=' ' then wmoves = append(wmoves,{warnsdorffs[nrow][ncol],nrow,ncol}) end if end for wmoves = sort(wmoves) -- avoid creating orphans if length(wmoves)<2 or wmoves[2][1]>1 then for m=1 to length(wmoves) do {?,nrow,ncol} = wmoves[m] warnsdorffs[nrow][ncol] -= 1 end for for m=1 to length(wmoves) do {?,nrow,ncol} = wmoves[m] integer scol = ncol-nchars+1 board[nrow][scol..ncol] = sprintf(fmt,n) if solve(nrow,ncol,n+1) then return 1 end if backtracks += 1 board[nrow][scol..ncol] = blank end for for m=1 to length(wmoves) do {?,nrow,ncol} = wmoves[m] warnsdorffs[nrow][ncol] += 1 end for end if return 0 end function procedure holyknight(sequence s) s = split(s,'\n') size = length(s) nchars = length(sprintf(" %d",size*size)) fmt = sprintf(" %%%dd",nchars-1) blank = repeat(' ',nchars) board = repeat(repeat(' ',size*nchars),size) limit = 1 integer sx, sy for x=1 to size do integer y = nchars for j=1 to size do integer ch = iff(j>length(s[x])?'-':s[x][j]) if ch=' ' then ch = '-' elsif ch='0' then ch = ' ' limit += 1 elsif ch='1' then sx = x sy = y end if board[x][y] = ch y += nchars end for end for warnsdorffs = repeat(repeat(0,size*nchars),size) init_warnsdorffs() t0 = time() tries = 0 backtracks = 0 t1 = time()+1 if solve(sx,sy,2) then puts(1,join(board,"\n")) printf(1,"\nsolution found in %d tries, %d backtracks (%3.2fs)\n",{tries,backtracks,time()-t0}) else puts(1,"no solutions found\n") end if end procedure constant board1 = """ 000 0 00 0000000 000 0 0 0 0 000 1000000 00 0 000""" holyknight(board1) constant board2 = """ -----1-0----- -----0-0----- ----00000---- -----000----- --0--0-0--0-- 00000---00000 --00-----00-- 00000---00000 --0--0-0--0-- -----000----- ----00000---- -----0-0----- -----0-0-----""" if platform()!=JS then holyknight(board2) end if {} = wait_key()
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Sort an array of composite structures by a key. For example, if you define a composite structure that presents a name-value pair (in pseudo-code): Define structure pair such that: name as a string value as a string and an array of such pairs: x: array of pairs then define a sort routine that sorts the array x by the key name. This task can always be accomplished with Sorting Using a Custom Comparator. If your language is not listed here, please see the other article.
#Go
Go
package main   import ( "fmt" "sort" )   type pair struct { name, value string } type csArray []pair   // three methods satisfy sort.Interface func (a csArray) Less(i, j int) bool { return a[i].name < a[j].name } func (a csArray) Len() int { return len(a) } func (a csArray) Swap(i, j int) { a[i], a[j] = a[j], a[i] }   var x = csArray{ pair{"joe", "120"}, pair{"foo", "31"}, pair{"bar", "251"}, }   func main() { sort.Sort(x) for _, p := range x { fmt.Printf("%5s: %s\n", p.name, p.value) } }
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You are also given eight pegs numbered   1-to-8. Objective Place the eight pegs in the holes so that the (absolute) difference between any two numbers connected by any line is greater than one. Example In this attempt: 4 7 /│\ /│\ / │ X │ \ / │/ \│ \ 8───1───6───2 \ │\ /│ / \ │ X │ / \│/ \│/ 3 5 Note that   7   and   6   are connected and have a difference of   1,   so it is   not   a solution. Task Produce and show here   one   solution to the puzzle. Related tasks   A* search algorithm   Solve a Holy Knight's tour   Knight's tour   N-queens problem   Solve a Hidato puzzle   Solve a Holy Knight's tour   Solve a Hopido puzzle   Solve a Numbrix puzzle   4-rings or 4-squares puzzle See also No Connection Puzzle (youtube).
#Phix
Phix
with javascript_semantics constant txt = """ A B /|\ /|\ / | X | \ / |/ \| \ C - D - E - F \ |\ /| / \ | X | / \|/ \|/ G H """ --constant links = "CA DA DB DC EA EB ED FB FE GC GD GE HD HE HF" constant links = {"","","A","ABC","ABD","BE","CDE","DEF"} function solve(sequence s, integer idx, sequence part) object res integer v, p for i=1 to length(s) do v = s[i] for j=1 to length(links[idx]) do p = links[idx][j]-'@' if abs(v-part[p])<2 then v=0 exit end if end for if v then if length(s)=1 then return part&v end if res = solve(s[1..i-1]&s[i+1..$],idx+1,part&v) if sequence(res) then return res end if end if end for return 0 end function printf(1,substitute_all(txt,"ABCDEFGH",solve("12345678",1,"")))
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#Golfscript
Golfscript
[2 4 3 1 2]$
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#Groovy
Groovy
println ([2,4,0,3,1,2,-12].sort())
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Object identifiers (OID) Task Show how to sort a list of OIDs, in their natural sort order. Details An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number. Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields. Test case Input (list of strings) Output (list of strings) 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11150.3.4.0.1 Related tasks Natural sorting Sort using a custom comparator
#Tcl
Tcl
  # Example input data: set oid_list [list \ 1.3.6.1.4.1.11.2.17.19.3.4.0.10 \ 1.3.6.1.4.1.11.2.17.5.2.0.79 \ 1.3.6.1.4.1.11.2.17.19.3.4.0.4 \ 1.3.6.1.4.1.11150.3.4.0.1 \ 1.3.6.1.4.1.11.2.17.19.3.4.0.1 \ 1.3.6.1.4.1.11150.3.4.0 ] set oid2_lists [list ] set dots_max 0 set i 0 foreach oid $oid_list { set oid_list [split $oid "."] set dot_count [llength $oid_list] incr dot_count -1 if { $dot_count > $dots_max } { set dots_max $dot_count } set dots_arr(${i}) $dot_count lappend oid2_lists $oid_list incr i } # pad for strings of different dot counts set oid3_lists [list] for {set ii 0} {$ii < $i} {incr ii} { set oid_list [lindex $oid2_lists $ii] set add_fields [expr { $dots_max - $dots_arr(${ii}) } ] if { $add_fields > 0 } { for {set j 0} {$j < $add_fields} {incr j} { lappend oid_list -1 } } lappend oid3_lists $oid_list } for {set n $dots_max} {$n >= 0 } {incr n -1} { set oid3_lists [lsort -integer -index $n -increasing $oid3_lists] } # unpad strings of different dot counts set oid4_lists [list] for {set ii 0} {$ii < $i} {incr ii} { set oid_list [lindex $oid3_lists $ii] set j [lsearch -exact -integer $oid_list -1] if { $j > -1 } { set oid2_list [lrange $oid_list 0 ${j}-1] lappend oid4_lists $oid2_list } else { lappend oid4_lists $oid_list } } foreach oid_list $oid4_lists { puts [join $oid_list "."] }  
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted. Make your example work with the following list of values and set of indices: Values: [7, 6, 5, 4, 3, 2, 1, 0] Indices: {6, 1, 7} Where the correct result would be: [7, 0, 5, 4, 3, 2, 1, 6]. In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead. The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given. Cf.   Order disjoint list items
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   @interface DisjointSublistView : NSMutableArray { NSMutableArray *array; int *indexes; int num_indexes; } - (instancetype)initWithArray:(NSMutableArray *)a andIndexes:(NSIndexSet *)ind; @end   @implementation DisjointSublistView - (instancetype)initWithArray:(NSMutableArray *)a andIndexes:(NSIndexSet *)ind { if ((self = [super init])) { array = a; num_indexes = [ind count]; indexes = malloc(num_indexes * sizeof(int)); for (NSUInteger i = [ind firstIndex], j = 0; i != NSNotFound; i = [ind indexGreaterThanIndex:i], j++) indexes[j] = i; } return self; } - (void)dealloc { free(indexes); } - (NSUInteger)count { return num_indexes; } - (id)objectAtIndex:(NSUInteger)i { return array[indexes[i]]; } - (void)replaceObjectAtIndex:(NSUInteger)i withObject:(id)x { array[indexes[i]] = x; } @end   @interface NSMutableArray (SortDisjoint) - (void)sortDisjointSublist:(NSIndexSet *)indexes usingSelector:(SEL)comparator; @end @implementation NSMutableArray (SortDisjoint) - (void)sortDisjointSublist:(NSIndexSet *)indexes usingSelector:(SEL)comparator { DisjointSublistView *d = [[DisjointSublistView alloc] initWithArray:self andIndexes:indexes]; [d sortUsingSelector:comparator]; } @end   int main(int argc, const char *argv[]) { @autoreleasepool {   NSMutableArray *a = [@[@7, @6, @5, @4, @3, @2, @1, @0] mutableCopy]; NSMutableIndexSet *ind = [NSMutableIndexSet indexSet]; [ind addIndex:6]; [ind addIndex:1]; [ind addIndex:7]; [a sortDisjointSublist:ind usingSelector:@selector(compare:)]; NSLog(@"%@", a);   } return 0; }
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort   (the values of)   three variables   (X,   Y,   and   Z)   that contain any value   (numbers and/or literals). If that isn't possible in your language, then just sort numbers   (and note if they can be floating point, integer, or other). I.E.:   (for the three variables   x,   y,   and   z),   where: x = 'lions, tigers, and' y = 'bears, oh my!' z = '(from the "Wizard of OZ")' After sorting, the three variables would hold: x = '(from the "Wizard of OZ")' y = 'bears, oh my!' z = 'lions, tigers, and' For numeric value sorting, use: I.E.:   (for the three variables   x,   y,   and   z),   where: x = 77444 y = -12 z = 0 After sorting, the three variables would hold: x = -12 y = 0 z = 77444 The variables should contain some form of a number, but specify if the algorithm used can be for floating point or integers.   Note any limitations. The values may or may not be unique. The method used for sorting can be any algorithm;   the goal is to use the most idiomatic in the computer programming language used. More than one algorithm could be shown if one isn't clearly the better choice. One algorithm could be: • store the three variables   x, y, and z into an array (or a list)   A   • sort (the three elements of) the array   A   • extract the three elements from the array and place them in the variables x, y, and z   in order of extraction Another algorithm   (only for numeric values): x= 77444 y= -12 z= 0 low= x mid= y high= z x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */ z= max(low, mid, high) /* " " highest " " " " " */ y= low + mid + high - x - z /* " " middle " " " " " */ Show the results of the sort here on this page using at least the values of those shown above.
#zkl
zkl
x,y,z := "lions, tigers, and", "bears, oh my!", 0'|(from the "Wizard of OZ")|; x,y,z = List(x,y,z).sort(); println(x," | ",y," | ",z);   x,y,z := 77444, -12, 0; x,y,z = List(x,y,z).sort(); println(x," ",y," ",z);
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#Perl
Perl
use feature 'say';   @strings = qw/Here are some sample strings to be sorted/;   # with a subroutine: sub mycmp { length $b <=> length $a || lc $a cmp lc $b } say join ' ', sort mycmp @strings;   # inline: say join ' ', sort {length $b <=> length $a || lc $a cmp lc $b} @strings   # for large inputs, can be faster with a 'Schwartzian' transform: say join ' ', map { $_->[0] } sort { $b->[1] <=> $a->[1] || $a->[2] cmp $b->[2] } map { [ $_, length, lc ] } @strings;
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#Wren
Wren
import "random" for Random import "/sort" for Sort   var bogoSort = Fn.new { |a| var rand = Random.new() while (!Sort.isSorted(a)) rand.shuffle(a) }   var a = [31, 41, 59, 26, 53, 58, 97, 93, 23, 84] System.print("Before: %(a)") bogoSort.call(a) System.print("After : %(a)")
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#Gambas
Gambas
Public Sub Main() Dim byToSort As Byte[] = [249, 28, 111, 36, 171, 98, 29, 448, 44, 147, 154, 46, 102, 183, 24, 120, 19, 123, 2, 17, 226, 11, 211, 25, 191, 205, 77] Dim byCount As Byte Dim bSorting As Boolean   Print "To sort: -" ShowWorking(byToSort) Print Repeat bSorting = False For byCount = 0 To byToSort.Max - 1 If byToSort[byCount] > byToSort[byCount + 1] Then Swap byToSort[byCount], byToSort[byCount + 1] bSorting = True Endif Next If bSorting Then ShowWorking(byToSort) Until bSorting = False End '----------------------------------------- Public Sub ShowWorking(byToSort As Byte[]) Dim byCount As Byte   For byCount = 0 To byToSort.Max Print Str(byToSort[byCount]); If byCount <> byToSort.Max Then Print ","; Next   Print   End
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#PowerBASIC
PowerBASIC
SUB gnomeSort (a() AS LONG) DIM i AS LONG, j AS LONG i = 1 j = 2 WHILE (i < UBOUND(a) + 1) IF (a(i - 1) <= a(i)) THEN i = j INCR j ELSE SWAP a(i - 1), a(i) DECR i IF 0 = i THEN i = j INCR j END IF END IF WEND END SUB   FUNCTION PBMAIN () AS LONG DIM n(9) AS LONG, x AS LONG RANDOMIZE TIMER OPEN "output.txt" FOR OUTPUT AS 1 FOR x = 0 TO 9 n(x) = INT(RND * 9999) PRINT #1, n(x); ","; NEXT PRINT #1, gnomeSort n() FOR x = 0 TO 9 PRINT #1, n(x); ","; NEXT CLOSE 1 END FUNCTION
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#Perl
Perl
use strict; use warnings; use feature 'say';   sub cocktail_sort { my @a = @_; while (1) { my $swapped_forward = 0; for my $i (0..$#a-1) { if ($a[$i] gt $a[$i+1]) { @a[$i, $i+1] = @a[$i+1, $i]; $swapped_forward = 1; } } last if not $swapped_forward;   my $swapped_backward = 0; for my $i (reverse 0..$#a-1) { if ($a[$i] gt $a[$i+1]) { @a[$i, $i+1] = @a[$i+1, $i]; $swapped_backward = 1; } } last if not $swapped_backward; } @a }   say join ' ', cocktail_sort( <t h e q u i c k b r o w n f o x j u m p s o v e r t h e l a z y d o g> );
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Haskell
Haskell
import Network   main = withSocketsDo $ sendTo "localhost" (PortNumber $ toEnum 256) "hello socket world"
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Icon_and_Unicon
Icon and Unicon
link cfunc procedure main () hello("localhost", 1024) end   procedure hello (host, port) write(tconnect(host, port) | stop("unable to connect to", host, ":", port) , "hello socket world") end
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also OEIS A019546: Primes whose digits are primes. https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[SmarandachePrimeQ] SmarandachePrimeQ[n_Integer] := MatchQ[IntegerDigits[n], {(2 | 3 | 5 | 7) ..}] \[And] PrimeQ[n] s = Select[Range[10^5], SmarandachePrimeQ]; Take[s, UpTo[25]] s[[100]]
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also OEIS A019546: Primes whose digits are primes. https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
#Nim
Nim
import math, strformat, strutils   const N = 35_000   # Sieve. var composite: array[0..N, bool] # Default is false and means prime. composite[0] = true composite[1] = true for n in 2..sqrt(N.toFloat).int: if not composite[n]: for k in countup(n * n, N, n): composite[k] = true     func digits(n: Positive): seq[0..9] = var n = n.int while n != 0: result.add n mod 10 n = n div 10     proc isSPDS(n: int): bool = if composite[n]: return false result = true for d in n.digits: if composite[d]: return false     iterator spds(maxCount: Positive): int {.closure.} = yield 2 var count = 1 var n = 3 while count != maxCount and n <= N: if n.isSPDS: inc count yield n inc n, 2 if count != maxCount: quit &"Too few values ({count}). Please, increase value of N.", QuitFailure     stdout.write "The first 25 SPDS are:" for n in spds(25): stdout.write ' ', n echo()   var count = 0 for n in spds(100): inc count if count == 100: echo "The 100th SPDS is: ", n
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also OEIS A019546: Primes whose digits are primes. https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
#Pascal
Pascal
program Smarandache;   uses sysutils,primsieve;// http://rosettacode.org/wiki/Extensible_prime_generator#Pascal const Digits : array[0..3] of Uint32 = (2,3,5,7); var i,j,pot10,DgtLimit,n,DgtCnt,v,cnt,LastPrime,Limit : NativeUint;   procedure Check(n:NativeUint); var p : NativeUint; Begin p := LastPrime; while p< n do p := nextprime; if p = n then begin inc(cnt); IF (cnt <= 25) then Begin IF cnt = 25 then Begin writeln(n); Limit := 100; end else Write(n,','); end else IF cnt = Limit then Begin Writeln(cnt:9,n:16); Limit *=10; if Limit > 10000 then HALT; end; end; LastPrime := p; end;   Begin Limit := 25; LastPrime:=1;   //Creating the numbers not the best way but all upto 11 digits take 0.05s //here only 9 digits i := 0; pot10 := 1; DgtLimit := 1; v := 4; repeat repeat j := i; DgtCnt := 0; pot10 := 1; n := 0; repeat n += pot10*Digits[j MOD 4]; j := j DIV 4; pot10 *=10; inc(DgtCnt); until DgtCnt = DgtLimit; Check(n); inc(i); until i=v; //one more digit v *=4; i :=0; inc(DgtLimit); until DgtLimit= 12; end.
http://rosettacode.org/wiki/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Snake is a game where the player maneuvers a line which grows in length every time the snake reaches a food source. Task Implement a variant of the Snake game, in any interactive environment, in which a sole player attempts to eat items by running into them with the head of the snake. Each item eaten makes the snake longer and a new item is randomly generated somewhere else on the plane. The game ends when the snake attempts to eat himself.
#Delphi
Delphi
  unit SnakeGame;   interface   uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.Dialogs, System.Generics.Collections, Vcl.ExtCtrls;   type TSnakeApp = class(TForm) procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormPaint(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure DoFrameStep(Sender: TObject); procedure Reset; private { Private declarations } FrameTimer: TTimer; public { Public declarations } end;   TSnake = class len: Integer; alive: Boolean; pos: TPoint; posArray: TList<TPoint>; dir: Byte; private function Eat(Fruit: TPoint): Boolean; function Overlap: Boolean; procedure update; public procedure Paint(Canvas: TCanvas); procedure Reset; constructor Create; destructor Destroy; override; end;   TFruit = class FruitTime: Boolean; pos: TPoint; constructor Create; procedure Reset; procedure Paint(Canvas: TCanvas); private procedure SetFruit; end;   const L = 1; R = 2; D = 4; U = 8;   var SnakeApp: TSnakeApp; block: Integer = 24; wid: Integer = 30; hei: Integer = 20; fruit: TFruit; snake: TSnake;   implementation   {$R *.dfm}   function Rect(x, y, w, h: Integer): TRect; begin Result := TRect.Create(x, y, x + w, y + h); end;   { TSnake }   constructor TSnake.Create; begin posArray := TList<TPoint>.Create; Reset; end;   procedure TSnake.Paint(Canvas: TCanvas); var pos: TPoint; i, l: Integer; r: TRect; begin with Canvas do begin Brush.Color := rgb(130, 190, 0);   i := posArray.count - 1; l := posArray.count; while True do begin pos := posArray[i]; dec(i); r := rect(pos.x * block, pos.y * block, block, block); FillRect(r); dec(l); if l = 0 then Break; end; end; end;   procedure TSnake.Reset; begin alive := true; pos := Tpoint.Create(1, 1); posArray.Clear; posArray.Add(Tpoint.Create(pos)); len := posArray.Count; dir := r; end;   destructor TSnake.Destroy; begin posArray.Free; inherited; end;   function TSnake.Eat(Fruit: TPoint): Boolean; begin result := (pos.X = Fruit.X) and (pos.y = Fruit.y); if result then begin inc(len); if len > 5000 then len := 500; end; end;   function TSnake.Overlap: Boolean; var aLen: Integer; tp: TPoint; i: Integer; begin aLen := posArray.count - 1;   for i := 0 to aLen - 1 do begin tp := posArray[i]; if (tp.x = pos.x) and (tp.y = pos.y) then Exit(True); end; Result := false; end;   procedure TSnake.update; begin if not alive then exit; case dir of l: begin dec(pos.X); if pos.X < 1 then pos.x := wid - 2 end; r: begin inc(pos.x); if (pos.x > (wid - 2)) then pos.x := 1; end; U: begin dec(pos.y);   if (pos.y < 1) then pos.y := hei - 2 end; D: begin inc(pos.y);   if (pos.y > hei - 2) then pos.y := 1; end; end; if Overlap then alive := False else begin posArray.Add(TPoint(pos));   if len < posArray.Count then posArray.Delete(0); end; end;   { TFruit }   constructor TFruit.Create; begin Reset; end;   procedure TFruit.Paint(Canvas: TCanvas); var r: TRect; begin with Canvas do begin Brush.Color := rgb(200, 50, 20);   r := Rect(pos.x * block, pos.y * block, block, block);   FillRect(r); end; end;   procedure TFruit.Reset; begin fruitTime := true; pos := Tpoint.Create(0, 0); end;   procedure TFruit.SetFruit; begin pos.x := Trunc(Random(wid - 2) + 1); pos.y := Trunc(Random(hei - 2) + 1); fruitTime := false; end;   procedure TSnakeApp.DoFrameStep(Sender: TObject); begin Invalidate; end;   procedure TSnakeApp.FormClose(Sender: TObject; var Action: TCloseAction); begin FrameTimer.Free; snake.Free; Fruit.Free; end;   procedure TSnakeApp.FormCreate(Sender: TObject); begin Canvas.pen.Style := psClear; ClientHeight := block * hei; ClientWidth := block * wid; DoubleBuffered := True; KeyPreview := True;   OnClose := FormClose; OnKeyDown := FormKeyDown; OnPaint := FormPaint;   snake := TSnake.Create; Fruit := TFruit.Create(); FrameTimer := TTimer.Create(nil); FrameTimer.Interval := 250; FrameTimer.OnTimer := DoFrameStep; FrameTimer.Enabled := True; end;   procedure TSnakeApp.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);   function ValidDir(value: Byte): Byte; var combination: Byte; begin combination := (value or snake.dir); if (combination = 3) or (combination = 12) then Result := snake.dir else Result := value; end;   begin case Key of VK_LEFT: snake.dir := ValidDir(l); VK_RIGHT: snake.dir := ValidDir(r); VK_UP: snake.dir := ValidDir(U); VK_DOWN: snake.dir := ValidDir(D); VK_ESCAPE: Reset; end; end;   procedure TSnakeApp.FormPaint(Sender: TObject); var i: Integer; r: TRect; frameR: Double; begin with Canvas do begin Brush.Color := rgb(0, $22, 0); FillRect(ClipRect); Brush.Color := rgb(20, 50, 120);   for i := 0 to wid - 1 do begin r := rect(i * block, 0, block, block); FillRect(r); r := rect(i * block, ClientHeight - block, block, block); FillRect(r); end;   for i := 1 to hei - 2 do begin r := Rect(1, i * block, block, block); FillRect(r); r := Rect(ClientWidth - block, i * block, block, block); FillRect(r); end;   if (Fruit.fruitTime) then begin Fruit.setFruit(); frameR := FrameTimer.Interval * 0.95; if frameR < 30 then frameR := 30; FrameTimer.Interval := trunc(frameR); end;   Fruit.Paint(Canvas); snake.update();   if not snake.alive then begin FrameTimer.Enabled := False; Application.ProcessMessages; ShowMessage('Game over'); Reset; exit; end;   if (snake.eat(Fruit.pos)) then Fruit.fruitTime := true; snake.Paint(Canvas);   Brush.Style := bsClear; Font.Color := rgb(200, 200, 200); Font.Size := 18; TextOut(50, 0, (snake.len - 1).ToString); end; end;   procedure TSnakeApp.Reset; begin snake.Reset; Fruit.Reset; FrameTimer.Interval := 250; FrameTimer.Enabled := True; end; end.
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers. Example Using the number 166 Find the prime factors of 166 which are: 2 x 83 Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13 Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13 Therefore, the number 166 is a Smith number. Task Write a program to find all Smith numbers below 10000. See also from Wikipedia:   [Smith number]. from MathWorld:   [Smith number]. from OEIS A6753:   [OEIS sequence A6753]. from OEIS A104170:   [Number of Smith numbers below 10^n]. from The Prime pages:   [Smith numbers].
#BASIC
BASIC
10 DEFINT A-Z 20 DIM F(32) 30 FOR I=2 TO 9999 40 F=0: N=I 50 IF N>0 AND (N AND 1)=0 THEN N=N\2: F(F)=2: F=F+1: GOTO 50 60 P=3 70 GOTO 100 80 IF N MOD P=0 THEN N=N\P: F(F)=P: F=F+1: GOTO 80 90 P=P+2 100 IF P<=N GOTO 80 110 IF F<=1 GOTO 190 120 N=I: S=0 130 IF N>0 THEN S=S+N MOD 10: N=N\10: GOTO 130 140 FOR J=0 TO F-1 150 N=F(J) 160 IF N>0 THEN S=S-N MOD 10: N=N\10: GOTO 160 170 NEXT 180 IF S=0 THEN PRINT USING " ####";I;: C=C+1 190 NEXT 200 PRINT 210 PRINT "Found";C;"Smith numbers."
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle
Solve a Hidato puzzle
The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always connected. The number “1” is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique. It may be assumed that the difference between numbers present on the grid is not greater than lucky 13. The aim is to place a natural number in each blank square so that in the sequence of numbered squares from “1” upwards, each square is in the wp:Moore neighborhood of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints). Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order. A square may only contain one number. In a proper Hidato puzzle, the solution is unique. For example the following problem has the following solution, with path marked on it: Related tasks A* search algorithm N-queens problem Solve a Holy Knight's tour Solve a Knight's tour Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle;
#Erlang
Erlang
  -module( solve_hidato_puzzle ).   -export( [create/2, solve/1, task/0] ).   -compile({no_auto_import,[max/2]}).   create( Grid_list, Number_list ) -> Squares = lists:flatten( [create_column(X, Y) || {X, Y} <- Grid_list] ), lists:foldl( fun store/2, dict:from_list(Squares), Number_list ).   print( Grid_list ) when is_list(Grid_list) -> print( create(Grid_list, []) ); print( Grid_dict ) -> Max_x = max_x( Grid_dict ), Max_y = max_y( Grid_dict ), Print_row = fun (Y) -> [print(X, Y, Grid_dict) || X <- lists:seq(1, Max_x)], io:nl() end, [Print_row(Y) || Y <- lists:seq(1, Max_y)].   solve( Dict ) -> {find_start, [Start]} = {find_start, dict:fold( fun start/3, [], Dict )}, Max = dict:size( Dict ), {stop_ok, {Max, Max, [Stop]}} = {stop_ok, dict:fold( fun stop/3, {Max, 0, []}, Dict )}, My_pid = erlang:self(), erlang:spawn( fun() -> path(Start, Stop, Dict, My_pid, []) end ), receive {grid, Grid, path, Path} -> {Grid, Path} end.   task() -> %% Square is {X, Y}, N}. N = 0 for empty square. These are created if not present. %% Leftmost column is X=1. Top row is Y=1. %% Optimised for the example, grid is a list of {X, {Y_min, Y_max}}. %% When there are holes, X is repeated as many times as needed with two new Y values each time. Start = {{7,5}, 1}, Stop = {{5,4}, 40}, Grid_list = [{1, {1,5}}, {2, {1,5}}, {3, {1,6}}, {4, {1,6}}, {5, {1,7}}, {6, {3,7}}, {7, {5,8}}, {8, {7,8}}], Number_list = [Start, Stop, {{1,5}, 27}, {{2,1}, 33}, {{2,4}, 26}, {{3,1}, 35}, {{3,2}, 24}, {{4,2}, 22}, {{4,3}, 21}, {{4,4}, 13}, {{5,5}, 9}, {{5,6}, 18}, {{6,4}, 11}, {{6,7}, 7}, {{7,8}, 5}], Grid = create( Grid_list, Number_list ), io:fwrite( "Start grid~n" ), print( Grid ), {New_grid, Path} = solve( create(Grid_list, Number_list) ), io:fwrite( "Start square ~p, Stop square ~p.~nPath ~p~n", [Start, Stop, Path] ), print( New_grid ).     create_column( X, {Y_min, Y_max} ) -> [{{X, Y}, 0} || Y <- lists:seq(Y_min, Y_max)].   is_filled( Dict ) -> [] =:= dict:fold( fun keep_0_square/3, [], Dict ).   keep_0_square( Key, 0, Acc ) -> [Key | Acc]; keep_0_square( _Key, _Value, Acc ) -> Acc.   max( Position, Keys ) -> [Square | _T] = lists:reverse( lists:keysort(Position, Keys) ), Square.   max_x( Dict ) -> {X, _Y} = max( 1, dict:fetch_keys(Dict) ), X.   max_y( Dict ) -> {_X, Y} = max( 2, dict:fetch_keys(Dict) ), Y.     neighbourhood( Square, Dict ) -> Potentials = neighbourhood_potential_squares( Square ), neighbourhood_squares( dict:find(Square, Dict), Potentials, Dict ).   neighbourhood_potential_squares( {X, Y} ) -> [{Sx, Sy} || Sx <- [X-1, X, X+1], Sy <- [Y-1, Y, Y+1], {X, Y} =/= {Sx, Sy}].   neighbourhood_squares( {ok, Value}, Potentials, Dict ) -> Square_values = lists:flatten( [neighbourhood_square_value(X, dict:find(X, Dict)) || X <- Potentials] ), Next_value = Value + 1, neighbourhood_squares_next_value( lists:keyfind(Next_value, 2, Square_values), Square_values, Next_value ).   neighbourhood_squares_next_value( {Square, Value}, _Square_values, Value ) -> [{Square, Value}]; neighbourhood_squares_next_value( false, Square_values, Value ) -> [{Square, Value} || {Square, Y} <- Square_values, Y =:= 0].   neighbourhood_square_value( Square, {ok, Value} ) -> [{Square, Value}]; neighbourhood_square_value( _Square, error ) -> [].   path( Square, Square, Dict, Pid, Path ) -> path_correct( is_filled(Dict), Pid, [Square | Path], Dict ); path( Square, Stop, Dict, Pid, Path ) -> Reversed_path = [Square | Path], Neighbours = neighbourhood( Square, Dict ), [erlang:spawn( fun() -> path(Next_square, Stop, dict:store(Next_square, Value, Dict), Pid, Reversed_path) end ) || {Next_square, Value} <- Neighbours].   path_correct( true, Pid, Path, Dict ) -> Pid ! {grid, Dict, path, lists:reverse( Path )}; path_correct( false, _Pid, _Path, _Dict ) -> dead_end.   print( X, Y, Dict ) -> print_number( dict:find({X, Y}, Dict) ).   print_number( {ok, 0} ) -> io:fwrite( "~3s", ["."] ); % . is less distracting than 0 print_number( {ok, Value} ) -> io:fwrite( "~3b", [Value] ); print_number( error ) -> io:fwrite( "~3s", [" "] ).   start( Key, 1, Acc ) -> [Key | Acc]; % Allow check that we only have one key with value 1. start( _Key, _Value, Acc ) -> Acc.   stop( Key, Max, {Max, Max_found, Stops} ) -> {Max, erlang:max(Max, Max_found), [Key | Stops]}; % Allow check that we only have one key with value Max. stop( _Key, Value, {Max, Max_found, Stops} ) -> {Max, erlang:max(Value, Max_found), Stops}. % Allow check that Max is Max.   store( {Key, Value}, Dict ) -> dict:store( Key, Value, Dict ).  
http://rosettacode.org/wiki/Sokoban
Sokoban
Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character array where space is an empty square # is a wall @ is the player $ is a box . is a goal + is the player on a goal * is a box on a goal ####### # # # # #. # # #. $$ # #.$$ # #.# @# ####### Sokoban solutions are usually stored in the LURD format, where lowercase l, u, r and d represent a move in that (left, up, right, down) direction and capital LURD represents a push. Please state if you use some other format for either the input or output, and why. For more information, see the Sokoban wiki.
#Racket
Racket
  #lang racket (require data/heap "../lib/vector2.rkt" "../lib/queue.rkt" (only-in "../lib/util.rkt" push! tstruct ret awhen))   (define level (list "#######" "# #" "# #" "#. # #" "#. $$ #" "#.$$ #" "#.# @#" "#######")) (define (strings->vec2 l) (lists->vec2 (map string->list l))) ;turn everything except walls into distance from goals (define (clear-level l) (ret ([l (vec2-copy l)]) (define dots (vec2-atsq l #\.)) (define q (list->q (map (λ (p) (cons p 0)) dots))) (let bfs () ;this search has implicit history in the mutated vector2 (unless (nilq? q) (match-define (cons p n) (deq! q)) (define x (vec2@ l p))  ;stop if position is either a wall or a previously filled number (cond [(or (eq? x #\#) (number? x)) (bfs)] [else (vec2! l p n) (for-adj l x [p p] #f (enq! (cons p (add1 n)) q)) (bfs)])))))   ;corresponds to PicoLisp's move table in "moves", while also adding a push direction mapping (tstruct move (f d)) (define-values (mu md ml mr LURD) (let () (define t (map (λ (x) (cons (car x) (apply pos (cdr x)))) '([#\u -1 0] [#\d 1 0] [#\l 0 -1] [#\r 0 1]))) (define (mv d) (define x (assoc d t)) (move (λ (p) (pos+ p (cdr x))) (car x))) (values (mv #\u) (mv #\d) (mv #\l) (mv #\r) (λ (d) (char-upcase (car (findf (λ (x) (equal? d (cdr x))) t)))))))   ;state = player pos * box poses (tstruct st (p b)) (define (st= s1 s2) (andmap (λ (b) (member b (st-b s2))) (st-b s1))) (define (box? p s) (member p (st-b s))) ;calculates value of a state for insertion into priority queue ;value is sum of box distances from goals (define (value s l) (apply + (map (λ (p) (vec2@ l p)) (st-b s)))) ;init state for a level (define (st0 l) (st (vec2-atq l #\@) (vec2-atsq l #\$))) (define (make-solution-checker l) (define dots (vec2-atsq l #\.)) (λ (s) (andmap (λ (b) (member b dots)) (st-b s))))   ;state after push * lurd history (tstruct push (st h)) (define (pushes s l) (ret ([pushes '()]) (for ([b (in-list (st-b s))]) (for-adj l a [p b] #f (define d (pos- p b)) ;direction of push (define op (pos- b d)) ;where player stands to push (define o (vec2@ l op))  ;make sure push pos and push dest are clear (when (and (number? a) (number? o) (not (box? p s)) (not (box? op s))) (awhen [@ (moves s op l)] (define new-st (st b (cons p (remove b (st-b s))))) (push! (push new-st (cons (LURD d) @)) pushes)))))))   ;state * goal pos * level -> lurd string (define (moves s g l) (define h '()) (define q (list->q (list (list (st-p s))))) (let bfs () (if (nilq? q) #f (match-let ([(cons p lurd) (deq! q)]) (cond [(equal? p g) lurd] [(or (char=? (vec2@ l p) #\#) (box? p s) (member p h)) (bfs)] [else (push! p h) (for-each (λ (m) (match-define (move f s) m) (enq! (cons (f p) (cons s lurd)) q)) (list mu md ml mr)) (bfs)])))))   (define (sokoban l) (define-values (clear s0 solved?) (let ([l (strings->vec2 l)]) (values (clear-level l) (st0 l) (make-solution-checker l)))) (define h '()) (tstruct q-elem (s lurd v)) ;priority queue stores state, lurd hist, and value (define (elem<= s1 s2) (<= (q-elem-v s1) (q-elem-v s2))) ;compare wrapped values  ;queue stores a single element at the beginning consisting of:  ;1. starting state, 2. empty lurd history, 3. value of starting state (define q (vector->heap elem<= (vector (q-elem s0 '() (value s0 clear))))) (let bfs () (match-define (q-elem s lurd _) (heap-min q)) (heap-remove-min! q) (cond [(solved? s) (list->string (reverse lurd))] [(memf (λ (s1) (st= s s1)) h) (bfs)] [else (push! s h) (for-each (λ (p) (define s (push-st p)) (heap-add! q (q-elem s (append (push-h p) lurd) (value s clear)))) (pushes s clear)) (bfs)])))  
http://rosettacode.org/wiki/Sokoban
Sokoban
Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character array where space is an empty square # is a wall @ is the player $ is a box . is a goal + is the player on a goal * is a box on a goal ####### # # # # #. # # #. $$ # #.$$ # #.# @# ####### Sokoban solutions are usually stored in the LURD format, where lowercase l, u, r and d represent a move in that (left, up, right, down) direction and capital LURD represents a push. Please state if you use some other format for either the input or output, and why. For more information, see the Sokoban wiki.
#Raku
Raku
sub MAIN() { my $level = q:to//; ####### # # # # #. # # #. $$ # #.$$ # #.# @# #######   say 'level:'; print $level; say 'solution:'; say solve($level); }   class State { has Str $.board; has Str $.sol; has Int $.pos;   method move(Int $delta --> Str) { my $new = $!board; if $new.substr($!pos,1) eq '@' { substr-rw($new,$!pos,1) = ' '; } else { substr-rw($new,$!pos,1) = '.'; } my $pos := $!pos + $delta; if $new.substr($pos,1) eq ' ' { substr-rw($new,$pos,1) = '@'; } else { substr-rw($new,$pos,1) = '+'; } return $new; }   method push(Int $delta --> Str) { my $pos := $!pos + $delta; my $box := $pos + $delta; return '' unless $!board.substr($box,1) eq ' ' | '.'; my $new = $!board; if $new.substr($!pos,1) eq '@' { substr-rw($new,$!pos,1) = ' '; } else { substr-rw($new,$!pos,1) = '.'; } if $new.substr($pos,1) eq '$' { substr-rw($new,$pos,1) = '@'; } else { substr-rw($new,$pos,1) = '+'; } if $new.substr($box,1) eq ' ' { substr-rw($new,$box,1) = '$'; } else { substr-rw($new,$box,1) = '*'; } return $new; } }   sub solve(Str $start --> Str) { my $board = $start; my $width = $board.lines[0].chars + 1; my @dirs = ["u", "U", -$width], ["r", "R", 1], ["d", "D", $width], ["l", "L", -1];   my %visited = $board => True;   my $pos = $board.index('@'); my @open = State.new(:$board, :sol(''), :$pos); while @open { my $state = @open.shift; for @dirs -> [$move, $push, $delta] { my $board; my $sol; my $pos = $state.pos + $delta; given $state.board.substr($pos,1) { when '$' | '*' { $board = $state.push($delta); next if $board eq "" || %visited{$board}; $sol = $state.sol ~ $push; return $sol unless $board ~~ /<[ . + ]>/; } when ' ' | '.' { $board = $state.move($delta); next if %visited{$board}; $sol = $state.sol ~ $move; } default { next } } @open.push: State.new: :$board, :$sol, :$pos; %visited{$board} = True; } } return "No solution"; }
http://rosettacode.org/wiki/Solve_a_Holy_Knight%27s_tour
Solve a Holy Knight's tour
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. This kind of knight's tour puzzle is similar to   Hidato. The present task is to produce a solution to such problems. At least demonstrate your program by solving the following: Example 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 Note that the zeros represent the available squares, not the pennies. Extra credit is available for other interesting examples. Related tasks A* search algorithm Knight's tour N-queens problem Solve a Hidato puzzle Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle
#Picat
Picat
import sat.   main => S = {".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000.."}, MaxR = len(S), MaxC = len(S[1]), M = new_array(MaxR,MaxC), StartR = _,  % make StartR and StartC global StartC = _, foreach (R in 1..MaxR) fill_row(R, S[R], M[R], 1, StartR, StartC) end, NZeros = len([1 : R in 1..MaxR, C in 1..MaxC, M[R,C] == 0]), M :: 0..MaxR*MaxC-NZeros, Vs = [{(R,C),1} : R in 1..MaxR, C in 1..MaxC, M[R,C] !== 0], Es = [{(R,C),(R1,C1),_} : R in 1..MaxR, C in 1..MaxC, M[R,C] !== 0, neibs(M,MaxR,MaxC,R,C,Neibs), (R1,C1) in Neibs, M[R1,C1] !== 0], hcp(Vs,Es), foreach ({(R,C),(R1,C1),B} in Es) B #/\ (R1 #!= StartR #\/ C1 #!= StartC) #=> M[R1,C1] #= M[R,C]+1 end, solve(M), foreach (R in 1..MaxR) foreach (C in 1..MaxC) if M[R,C] == 0 then printf("%4c", '.') else printf("%4d", M[R,C]) end end, nl end.   neibs(M,MaxR,MaxC,R,C,Neibs) => Connected = [(R+1, C+2), (R+1, C-2), (R-1, C+2), (R-1, C-2), (R+2, C+1), (R+2, C-1), (R-2, C+1), (R-2, C-1)], Neibs = [(R1,C1) : (R1,C1) in Connected, R1 >= 1, R1 =< MaxR, C1 >= 1, C1 =< MaxC, M[R1,C1] !== 0].     fill_row(_R, [], _Row, _C, _StartR, _StartC) => true. fill_row(R, ['.'|Str], Row, C, StartR, StartC) => Row[C] = 0, fill_row(R,Str, Row, C+1, StartR, StartC). fill_row(R, ['0'|Str], Row, C, StartR, StartC) => fill_row(R, Str, Row, C+1, StartR, StartC). fill_row(R, ['1'|Str], Row, C, StartR, StartC) => Row[C] = 1, StartR = R, StartC = C, fill_row(R, Str, Row, C+1, StartR, StartC).  
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Sort an array of composite structures by a key. For example, if you define a composite structure that presents a name-value pair (in pseudo-code): Define structure pair such that: name as a string value as a string and an array of such pairs: x: array of pairs then define a sort routine that sorts the array x by the key name. This task can always be accomplished with Sorting Using a Custom Comparator. If your language is not listed here, please see the other article.
#Groovy
Groovy
class Holiday { def date def name Holiday(dateStr, name) { this.name = name; this.date = format.parse(dateStr) } String toString() { "${format.format date}: ${name}" } static format = new java.text.SimpleDateFormat("yyyy-MM-dd") }   def holidays = [ new Holiday("2009-12-25", "Christmas Day"), new Holiday("2009-04-22", "Earth Day"), new Holiday("2009-09-07", "Labor Day"), new Holiday("2009-07-04", "Independence Day"), new Holiday("2009-10-31", "Halloween"), new Holiday("2009-05-25", "Memorial Day"), new Holiday("2009-03-14", "PI Day"), new Holiday("2009-01-01", "New Year's Day"), new Holiday("2009-12-31", "New Year's Eve"), new Holiday("2009-11-26", "Thanksgiving"), new Holiday("2009-02-14", "St. Valentine's Day"), new Holiday("2009-03-17", "St. Patrick's Day"), new Holiday("2009-01-19", "Martin Luther King Day"), new Holiday("2009-02-16", "President's Day") ]   holidays.sort { x, y -> x.date <=> y.date } holidays.each { println it }
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You are also given eight pegs numbered   1-to-8. Objective Place the eight pegs in the holes so that the (absolute) difference between any two numbers connected by any line is greater than one. Example In this attempt: 4 7 /│\ /│\ / │ X │ \ / │/ \│ \ 8───1───6───2 \ │\ /│ / \ │ X │ / \│/ \│/ 3 5 Note that   7   and   6   are connected and have a difference of   1,   so it is   not   a solution. Task Produce and show here   one   solution to the puzzle. Related tasks   A* search algorithm   Solve a Holy Knight's tour   Knight's tour   N-queens problem   Solve a Hidato puzzle   Solve a Holy Knight's tour   Solve a Hopido puzzle   Solve a Numbrix puzzle   4-rings or 4-squares puzzle See also No Connection Puzzle (youtube).
#Picat
Picat
import cp.   no_connection_puzzle(X) => N = 8, X = new_list(N), X :: 1..N, Graph = {{1,3}, {1,4}, {1,5}, {2,4}, {2,5}, {2,6}, {3,1}, {3,4}, {3,7}, {4,1}, {4,2}, {4,3}, {4,5}, {4,7}, {4,8}, {5,1}, {5,2}, {5,4}, {5,6}, {5,7}, {5,8}, {6,2}, {6,5}, {6,8}, {7,3}, {7,4}, {7,5}, {8,4}, {8,5}, {8,6}},   all_distinct(X), foreach(I in 1..Graph.length) abs(X[Graph[I,1]]-X[Graph[I,2]]) #> 1 end,    % symmetry breaking X[1] #< X[N],   solve(X), println(X), nl, [A,B,C,D,E,F,G,H] = X, Solution = to_fstring( "  %d  %d \n"++ " /|\\ /|\\ \n"++ " / | X | \\ \n"++ " / |/ \\| \\ \n"++ "%d - %d - %d - %d \n"++ " \\ |\\ /| / \n"++ " \\ | X | / \n"++ " \\|/ \\|/ \n"++ "  %d  %d \n", A,B,C,D,E,F,G,H), println(Solution).
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You are also given eight pegs numbered   1-to-8. Objective Place the eight pegs in the holes so that the (absolute) difference between any two numbers connected by any line is greater than one. Example In this attempt: 4 7 /│\ /│\ / │ X │ \ / │/ \│ \ 8───1───6───2 \ │\ /│ / \ │ X │ / \│/ \│/ 3 5 Note that   7   and   6   are connected and have a difference of   1,   so it is   not   a solution. Task Produce and show here   one   solution to the puzzle. Related tasks   A* search algorithm   Solve a Holy Knight's tour   Knight's tour   N-queens problem   Solve a Hidato puzzle   Solve a Holy Knight's tour   Solve a Hopido puzzle   Solve a Numbrix puzzle   4-rings or 4-squares puzzle See also No Connection Puzzle (youtube).
#Prolog
Prolog
:- use_module(library(clpfd)).   edge(a, c). edge(a, d). edge(a, e). edge(b, d). edge(b, e). edge(b, f). edge(c, d). edge(c, g). edge(d, e). edge(d, g). edge(d, h). edge(e, f). edge(e, g). edge(e, h). edge(f, h).   connected(A, B) :- ( edge(A,B); edge(B, A)).   no_connection_puzzle(Vs) :- % construct the arranged list of the nodes bagof(A, B^(edge(A,B); edge(B, A)), Lst), sort(Lst, L), length(L, Len),   % construct the list of the values length(Vs, Len), Vs ins 1..Len, all_distinct(Vs),   % two connected nodes must have values different for more than 1 set_constraints(L, Vs), label(Vs).     set_constraints([], []).   set_constraints([H | T], [VH | VT]) :- set_constraint(H, T, VH, VT), set_constraints(T, VT).       set_constraint(_, [], _, []). set_constraint(H, [H1 | T1], V, [VH | VT]) :- connected(H, H1), ( V - VH #> 1; VH - V #> 1), set_constraint(H, T1, V, VT).   set_constraint(H, [H1 | T1], V, [_VH | VT]) :- \+connected(H, H1), set_constraint(H, T1, V, VT).    
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#Haskell
Haskell
nums = [2,4,3,1,2] :: [Int] sorted = List.sort nums
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#HicEst
HicEst
DIMENSION array(100)   array = INT( RAN(100) ) SORT(Vector=array, Sorted=array)
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Object identifiers (OID) Task Show how to sort a list of OIDs, in their natural sort order. Details An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number. Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields. Test case Input (list of strings) Output (list of strings) 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11150.3.4.0.1 Related tasks Natural sorting Sort using a custom comparator
#VBScript
VBScript
' Sort a list of object identifiers - VBScript function myCompare(x,y) dim i,b sx=split(x,".") sy=split(y,".") b=false for i=0 to ubound(sx) if i > ubound(sy) then b=true: exit for select case sgn(int(sx(i))-int(sy(i))) case 1: b=true: exit for case -1: b=false: exit for end select next myCompare=b end function   function bubbleSort(t) dim i,n n=ubound(t) do changed=false n= n-1 for i=0 to n if myCompare(t(i),t(i+1)) then tmp=t(i): t(i)=t(i+1): t(i+1)=tmp changed=true end if next loop until not changed bubbleSort=t end function   a=array( _ "1.3.6.1.4.1.11.2.17.19.3.4.0.10", _ "1.3.6.1.4.1.11.2.17.5.2.0.79", _ "1.3.6.1.4.1.11.2.17.19.3.4.0.4", _ "1.3.6.1.4.1.11150.3.4.0.1", _ "1.3.6.1.4.1.11.2.17.19.3.4.0.1", _ "1.3.6.1.4.1.11150.3.4.0") bubbleSort a wscript.echo join(a,vbCrlf)
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Object identifiers (OID) Task Show how to sort a list of OIDs, in their natural sort order. Details An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number. Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields. Test case Input (list of strings) Output (list of strings) 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11150.3.4.0.1 Related tasks Natural sorting Sort using a custom comparator
#Wren
Wren
import "/fmt" for Fmt import "/sort" for Sort   var oids = [ "1.3.6.1.4.1.11.2.17.19.3.4.0.10", "1.3.6.1.4.1.11.2.17.5.2.0.79", "1.3.6.1.4.1.11.2.17.19.3.4.0.4", "1.3.6.1.4.1.11150.3.4.0.1", "1.3.6.1.4.1.11.2.17.19.3.4.0.1", "1.3.6.1.4.1.11150.3.4.0" ]   oids = oids.map { |oid| Fmt.v("s", 5, oid.split("."), 0, ".", "") }.toList Sort.quick(oids) oids = oids.map { |oid| oid.replace(" ", "") }.toList System.print(oids.join("\n"))
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted. Make your example work with the following list of values and set of indices: Values: [7, 6, 5, 4, 3, 2, 1, 0] Indices: {6, 1, 7} Where the correct result would be: [7, 0, 5, 4, 3, 2, 1, 6]. In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead. The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given. Cf.   Order disjoint list items
#OCaml
OCaml
let disjoint_sort cmp values indices = let temp = Array.map (Array.get values) indices in Array.sort cmp temp; Array.sort compare indices; Array.iteri (fun i j -> values.(j) <- temp.(i)) indices   let () = let values = [| 7; 6; 5; 4; 3; 2; 1; 0 |] and indices = [| 6; 1; 7 |] in disjoint_sort compare values indices; Array.iter (Printf.printf " %d") values; print_newline()
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#Phix
Phix
function my_compare(sequence a, b) integer c = -compare(length(a),length(b)) -- descending length if c=0 then c = compare(lower(a),lower(b)) -- ascending lexical within same length end if return c end function ?custom_sort(my_compare,{"Here", "are", "some", "sample", "strings", "to", "be", "sorted"})
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#XPL0
XPL0
code Ran=1, ChOut=8, IntOut=11;   proc BogoSort(A, L); \Sort array A of length L int A, L; int I, J, T; [loop [I:= 0; loop [if A(I) > A(I+1) then quit; I:= I+1; if I >= L-1 then return; ]; I:= Ran(L); J:= Ran(L); T:= A(I); A(I):= A(J); A(J):= T; ]; ];   int A, I; [A:= [3, 1, 4, 1, -5, 9, 2, 6, 5, 4]; BogoSort(A, 10); for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )]; ]
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#Yabasic
Yabasic
  sub shuffle(a()) n = arraysize(a(),1) m = arraysize(a(),1)*2   for k = 1 to m i = int(Ran(n)) j = int(Ran(n)) tmp = a(i) //swap a(i), a(j) a(i) = a(j) a(j) = tmp next k end sub   sub inorder(a()) n = arraysize(a(),1)   for i = 0 to n-2 if a(i) > a(i+1) then return false : fi next i return true end sub   sub Bogosort(a()) while not inorder(a()) shuffle(a()) wend end sub   dim a(5) a (0) = 10: a (1) = 1: a (2) = 2: a (3) = -6: a (4) = 3   Bogosort(a())   for i = 0 to arraysize(a(),1) - 1 print a(i), " "; next i end  
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#Go
Go
package main   import "fmt"   func main() { list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} fmt.Println("unsorted:", list)   bubblesort(list) fmt.Println("sorted! ", list) }   func bubblesort(a []int) { for itemCount := len(a) - 1; ; itemCount-- { hasChanged := false for index := 0; index < itemCount; index++ { if a[index] > a[index+1] { a[index], a[index+1] = a[index+1], a[index] hasChanged = true } } if hasChanged == false { break } } }
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#PowerShell
PowerShell
  function gnomesort($a) { $size, $i, $j = $a.Count, 1, 2 while($i -lt $size) { if ($a[$i-1] -le $a[$i]) { $i = $j $j++ } else { $a[$i-1], $a[$i] = $a[$i], $a[$i-1] $i-- if($i -eq 0) { $i = $j $j++ } } } $a } $array = @(60, 21, 19, 36, 63, 8, 100, 80, 3, 87, 11) "$(gnomesort $array)"  
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#Phix
Phix
with javascript_semantics function cocktail_sort(sequence s) s = deep_copy(s) integer swapped = 1, f = 1, t = length(s)-1, d = 1 while swapped do swapped = 0 for i=f to t by d do object si = s[i], sn = s[i+1] if si>sn then s[i] = sn s[i+1] = si swapped = 1 end if end for -- swap to and from, and flip direction. -- additionally, we can reduce one element to be -- examined, depending on which way we just went. {f,t,d} = {t-d,f,-d} end while return s end function constant s = sq_rand(repeat(1000,10)) printf(1,"original: %V\n",{s}) printf(1," sorted: %V\n",{cocktail_sort(s)})
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#IDL
IDL
socket, unit, 'localhost',256,/get_lun printf,unit,"hello socket world" close, unit
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#J
J
coinsert'jsocket' [ require 'socket' NB. Sockets library socket =. >{.sdcheck sdsocket'' NB. Open a socket host =. sdcheck sdgethostbyname 'localhost' NB. Resolve host sdcheck sdconnect socket ; host ,< 256 NB. Create connection to port 256 sdcheck 'hello socket world' sdsend socket , 0 NB. Send msg
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also OEIS A019546: Primes whose digits are primes. https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
#Perl
Perl
use strict; use warnings; use feature 'say'; use feature 'state'; use ntheory qw<is_prime>; use Lingua::EN::Numbers qw(num2en_ordinal);   my @prime_digits = <2 3 5 7>; my @spds = grep { is_prime($_) && /^[@{[join '',@prime_digits]}]+$/ } 1..100; my @p = map { $_+3, $_+7 } map { 10*$_ } @prime_digits;   while ($#spds < 100_000) { state $o++; my $oom = 10**(1+$o); my @q; for my $l (@prime_digits) { push @q, map { $l*$oom + $_ } @p; } push @spds, grep { is_prime($_) } @p = @q; }   say 'Smarandache prime-digitals:'; printf "%22s: %s\n", ucfirst(num2en_ordinal($_)), $spds[$_-1] for 1..25, 100, 1000, 10_000, 100_000;
http://rosettacode.org/wiki/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Snake is a game where the player maneuvers a line which grows in length every time the snake reaches a food source. Task Implement a variant of the Snake game, in any interactive environment, in which a sole player attempts to eat items by running into them with the head of the snake. Each item eaten makes the snake longer and a new item is randomly generated somewhere else on the plane. The game ends when the snake attempts to eat himself.
#Go
Go
package main   import ( "errors" "fmt" "log" "math/rand" "time"   termbox "github.com/nsf/termbox-go" )   func main() { rand.Seed(time.Now().UnixNano()) score, err := playSnake() if err != nil { log.Fatal(err) } fmt.Println("Final score:", score) }   type snake struct { body []position // tail to head positions of the snake heading direction width, height int cells []termbox.Cell }   type position struct { X int Y int }   type direction int   const ( North direction = iota East South West )   func (p position) next(d direction) position { switch d { case North: p.Y-- case East: p.X++ case South: p.Y++ case West: p.X-- } return p }   func playSnake() (int, error) { err := termbox.Init() if err != nil { return 0, err } defer termbox.Close()   termbox.Clear(fg, bg) termbox.HideCursor() s := &snake{ // It would be more efficient to use a circular // buffer instead of a plain slice for s.body. body: make([]position, 0, 32), cells: termbox.CellBuffer(), } s.width, s.height = termbox.Size() s.drawBorder() s.startSnake() s.placeFood() s.flush()   moveCh, errCh := s.startEventLoop() const delay = 125 * time.Millisecond for t := time.NewTimer(delay); ; t.Reset(delay) { var move direction select { case err = <-errCh: return len(s.body), err case move = <-moveCh: if !t.Stop() { <-t.C // handles race between moveCh and t.C } case <-t.C: move = s.heading } if s.doMove(move) { time.Sleep(1 * time.Second) break } }   return len(s.body), err }   func (s *snake) startEventLoop() (<-chan direction, <-chan error) { moveCh := make(chan direction) errCh := make(chan error, 1) go func() { defer close(errCh) for { switch ev := termbox.PollEvent(); ev.Type { case termbox.EventKey: switch ev.Ch { // WSAD and HJKL movement case 'w', 'W', 'k', 'K': moveCh <- North case 'a', 'A', 'h', 'H': moveCh <- West case 's', 'S', 'j', 'J': moveCh <- South case 'd', 'D', 'l', 'L': moveCh <- East case 0: switch ev.Key { // Cursor key movement case termbox.KeyArrowUp: moveCh <- North case termbox.KeyArrowDown: moveCh <- South case termbox.KeyArrowLeft: moveCh <- West case termbox.KeyArrowRight: moveCh <- East case termbox.KeyEsc: // Quit return } } case termbox.EventResize: // TODO errCh <- errors.New("terminal resizing unsupported") return case termbox.EventError: errCh <- ev.Err return case termbox.EventInterrupt: return } } }() return moveCh, errCh }   func (s *snake) flush() { termbox.Flush() s.cells = termbox.CellBuffer() }   func (s *snake) getCellRune(p position) rune { i := p.Y*s.width + p.X return s.cells[i].Ch } func (s *snake) setCell(p position, c termbox.Cell) { i := p.Y*s.width + p.X s.cells[i] = c }   func (s *snake) drawBorder() { for x := 0; x < s.width; x++ { s.setCell(position{x, 0}, border) s.setCell(position{x, s.height - 1}, border) } for y := 0; y < s.height-1; y++ { s.setCell(position{0, y}, border) s.setCell(position{s.width - 1, y}, border) } }   func (s *snake) placeFood() { for { // a random empty cell x := rand.Intn(s.width-2) + 1 y := rand.Intn(s.height-2) + 1 foodp := position{x, y} r := s.getCellRune(foodp) if r != ' ' { continue } s.setCell(foodp, food) return } }   func (s *snake) startSnake() { // a random cell somewhat near the center x := rand.Intn(s.width/2) + s.width/4 y := rand.Intn(s.height/2) + s.height/4 head := position{x, y} s.setCell(head, snakeHead) s.body = append(s.body[:0], head) s.heading = direction(rand.Intn(4)) }   func (s *snake) doMove(move direction) bool { head := s.body[len(s.body)-1] s.setCell(head, snakeBody) head = head.next(move) s.heading = move s.body = append(s.body, head) r := s.getCellRune(head) s.setCell(head, snakeHead) gameOver := false switch r { case food.Ch: s.placeFood() case border.Ch, snakeBody.Ch: gameOver = true fallthrough case empty.Ch: s.setCell(s.body[0], empty) s.body = s.body[1:] default: panic(r) } s.flush() return gameOver }   const ( fg = termbox.ColorWhite bg = termbox.ColorBlack )   // Symbols to use. // Could use Unicode instead of simple ASCII. var ( empty = termbox.Cell{Ch: ' ', Bg: bg, Fg: fg} border = termbox.Cell{Ch: '+', Bg: bg, Fg: termbox.ColorBlue} snakeBody = termbox.Cell{Ch: '#', Bg: bg, Fg: termbox.ColorGreen} snakeHead = termbox.Cell{Ch: 'O', Bg: bg, Fg: termbox.ColorYellow | termbox.AttrBold} food = termbox.Cell{Ch: '@', Bg: bg, Fg: termbox.ColorRed} )
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers. Example Using the number 166 Find the prime factors of 166 which are: 2 x 83 Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13 Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13 Therefore, the number 166 is a Smith number. Task Write a program to find all Smith numbers below 10000. See also from Wikipedia:   [Smith number]. from MathWorld:   [Smith number]. from OEIS A6753:   [OEIS sequence A6753]. from OEIS A104170:   [Number of Smith numbers below 10^n]. from The Prime pages:   [Smith numbers].
#BCPL
BCPL
get "libhdr"   // Find the sum of the digits of N let digsum(n) = n<10 -> n, n rem 10 + digsum(n/10)   // Factorize N let factors(n, facs) = valof $( let count = 0 and fac = 3   // Powers of 2 while n>0 & (n & 1)=0 $( n := n >> 1 facs!count := 2 count := count + 1 $)   // Odd factors while fac <= n $( while n rem fac=0 $( n := n / fac facs!count := fac count := count + 1 $) fac := fac + 2 $)   resultis count $)   // Is N a Smith number? let smith(n) = valof $( let facs = vec 32 let nfacs = factors(n, facs) let facsum = 0 if nfacs<=1 resultis false // primes are not Smith numbers for fac = 0 to nfacs-1 do facsum := facsum + digsum(facs!fac) resultis digsum(n) = facsum $)   // Count and print Smith numbers below 10,000 let start() be $( let count = 0 for i = 2 to 9999 if smith(i) $( writed(i, 5) count := count + 1 if count rem 16 = 0 then wrch('*N') $) writef("*NFound %N Smith numbers.*N", count) $)
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers. Example Using the number 166 Find the prime factors of 166 which are: 2 x 83 Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13 Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13 Therefore, the number 166 is a Smith number. Task Write a program to find all Smith numbers below 10000. See also from Wikipedia:   [Smith number]. from MathWorld:   [Smith number]. from OEIS A6753:   [OEIS sequence A6753]. from OEIS A104170:   [Number of Smith numbers below 10^n]. from The Prime pages:   [Smith numbers].
#C
C
  #include <stdlib.h> #include <stdio.h> #include <stdbool.h>   int numPrimeFactors(unsigned x) { unsigned p = 2; int pf = 0; if (x == 1) return 1; else { while (true) { if (!(x % p)) { pf++; x /= p; if (x == 1) return pf; } else ++p; } } }   void primeFactors(unsigned x, unsigned* arr) { unsigned p = 2; int pf = 0; if (x == 1) arr[pf] = 1; else { while (true) { if (!(x % p)) { arr[pf++] = p; x /= p; if (x == 1) return; } else p++; } } }   unsigned sumDigits(unsigned x) { unsigned sum = 0, y; while (x) { y = x % 10; sum += y; x /= 10; } return sum; }   unsigned sumFactors(unsigned* arr, int size) { unsigned sum = 0; for (int a = 0; a < size; a++) sum += sumDigits(arr[a]); return sum; }   void listAllSmithNumbers(unsigned x) { unsigned *arr; for (unsigned a = 4; a < x; a++) { int numfactors = numPrimeFactors(a); arr = (unsigned*)malloc(numfactors * sizeof(unsigned)); if (numfactors < 2) continue; primeFactors(a, arr); if (sumDigits(a) == sumFactors(arr,numfactors)) printf("%4u ",a); free(arr); } }   int main(int argc, char* argv[]) { printf("All the Smith Numbers < 10000 are:\n"); listAllSmithNumbers(10000); return 0; }  
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle
Solve a Hidato puzzle
The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always connected. The number “1” is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique. It may be assumed that the difference between numbers present on the grid is not greater than lucky 13. The aim is to place a natural number in each blank square so that in the sequence of numbered squares from “1” upwards, each square is in the wp:Moore neighborhood of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints). Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order. A square may only contain one number. In a proper Hidato puzzle, the solution is unique. For example the following problem has the following solution, with path marked on it: Related tasks A* search algorithm N-queens problem Solve a Holy Knight's tour Solve a Knight's tour Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle;
#Go
Go
package main   import ( "fmt" "sort" "strconv" "strings" )   var board [][]int var start, given []int   func setup(input []string) { /* This task is not about input validation, so we're going to trust the input to be valid */ puzzle := make([][]string, len(input)) for i := 0; i < len(input); i++ { puzzle[i] = strings.Fields(input[i]) } nCols := len(puzzle[0]) nRows := len(puzzle) list := make([]int, nRows*nCols) board = make([][]int, nRows+2) for i := 0; i < nRows+2; i++ { board[i] = make([]int, nCols+2) for j := 0; j < nCols+2; j++ { board[i][j] = -1 } } for r := 0; r < nRows; r++ { row := puzzle[r] for c := 0; c < nCols; c++ { switch cell := row[c]; cell { case "_": board[r+1][c+1] = 0 case ".": break default: val, _ := strconv.Atoi(cell) board[r+1][c+1] = val list = append(list, val) if val == 1 { start = append(start, r+1, c+1) } } } } sort.Ints(list) given = make([]int, len(list)) for i := 0; i < len(given); i++ { given[i] = list[i] } }   func solve(r, c, n, next int) bool { if n > given[len(given)-1] { return true }   back := board[r][c] if back != 0 && back != n { return false }   if back == 0 && given[next] == n { return false }   if back == n { next++ }   board[r][c] = n for i := -1; i < 2; i++ { for j := -1; j < 2; j++ { if solve(r+i, c+j, n+1, next) { return true } } }   board[r][c] = back return false }   func printBoard() { for _, row := range board { for _, c := range row { switch { case c == -1: fmt.Print(" . ") case c > 0: fmt.Printf("%2d ", c) default: fmt.Print("__ ") } } fmt.Println() } }   func main() { input := []string{ "_ 33 35 _ _ . . .", "_ _ 24 22 _ . . .", "_ _ _ 21 _ _ . .", "_ 26 _ 13 40 11 . .", "27 _ _ _ 9 _ 1 .", ". . _ _ 18 _ _ .", ". . . . _ 7 _ _", ". . . . . . 5 _", } setup(input) printBoard() fmt.Println("\nFound:") solve(start[0], start[1], 1, 0) printBoard() }
http://rosettacode.org/wiki/Sokoban
Sokoban
Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character array where space is an empty square # is a wall @ is the player $ is a box . is a goal + is the player on a goal * is a box on a goal ####### # # # # #. # # #. $$ # #.$$ # #.# @# ####### Sokoban solutions are usually stored in the LURD format, where lowercase l, u, r and d represent a move in that (left, up, right, down) direction and capital LURD represents a push. Please state if you use some other format for either the input or output, and why. For more information, see the Sokoban wiki.
#Ring
Ring
  #--------------------------------------------------# # Sokoban Game # #--------------------------------------------------#   # Game Data   aPlayer = [ :Row = 3, :Col = 4 ]   aLevel1 = [ [1,1,1,2,2,2,2,2,1,1,1,1,1,1], [1,2,2,2,1,1,1,2,1,1,1,1,1,1], [1,2,4,3,5,1,1,2,1,1,1,1,1,1], [1,2,2,2,1,5,4,2,1,1,1,1,1,1], [1,2,4,2,2,5,1,2,1,1,1,1,1,1], [1,2,1,2,1,4,1,2,2,1,1,1,1,1], [1,2,5,1,6,5,5,4,2,1,1,1,1,1], [1,2,1,1,1,4,1,1,2,1,1,1,1,1], [1,2,2,2,2,2,2,2,2,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1] ]   aLevel2 = [ [1,1,1,2,2,2,2,2,2,2,2,2,1,1], [1,2,2,2,1,5,1,4,1,1,1,2,1,1], [1,2,4,3,5,1,1,1,5,1,1,2,1,1], [1,2,2,2,1,1,4,1,1,1,1,2,1,1], [1,2,4,2,2,1,5,4,1,5,1,2,1,1], [1,2,1,2,1,4,1,5,1,1,2,2,1,1], [1,2,5,1,6,5,1,4,1,1,1,2,1,1], [1,2,1,1,1,4,1,4,1,5,1,2,1,1], [1,2,2,2,2,2,2,2,2,2,2,2,1,1], [1,1,1,1,1,1,1,1,1,1,1,1,1,1] ]   aLevel = aLevel1 nActiveLevel = 1   # For Game Restart aLevel1Copy = aLevel1 aLevel2Copy = aLevel2 aPlayerCopy = aPlayer   C_LEVEL_ROWSCOUNT = 10 C_LEVEL_COLSCOUNT = 14   C_EMPTY = 1 C_WALL = 2 C_PLAYER = 3 C_DOOR = 4 C_BOX = 5 C_BOXONDOOR = 6 C_PLAYERONDOOR = 7   nKeyClock = clock()   # Will be used when moving a Box aCurrentBox = [ :Row = 0, :Col = 0 ] nRowDiff = 0 nColDiff = 0   # When the player win lPlayerWin = False   load "gameengine.ring"   func main   oGame = New Game {   title = "Sokoban"   Map {   blockwidth = 60 blockheight = 60   aMap = aLevel   aImages = [ "images/empty.jpg", "images/wall.jpg", "images/player.jpg", "images/door.jpg", "images/box.jpg", "images/boxondoor.jpg", "images/player.jpg" # Player on Door ]   keypress = func oGame,oSelf,nkey { # Avoid getting many keys in short time if (clock() - nKeyClock) < clockspersecond()/4 return ok nKeyClock = Clock() Switch nkey on Key_Esc oGame.Shutdown() on Key_Space # Restart the Level if nActiveLevel = 1 aLevel = aLevel1Copy else aLevel = aLevel2Copy ok aPlayer = aPlayerCopy UpdateGameMap(oGame) lPlayerWin = False on Key_Right if aPlayer[:col] < C_LEVEL_COLSCOUNT nRowDiff = 0 nColDiff = 1 MoveObject(oGame,PlayerType(),aPlayer[:row],aPlayer[:col]+1) ok on Key_Left if aPlayer[:col] > 1 nRowDiff = 0 nColDiff = -1 MoveObject(oGame,PlayerType(),aPlayer[:row],aPlayer[:col]-1) ok on Key_Up if aPlayer[:row] > 1 nRowDiff = -1 nColDiff = 0 MoveObject(oGame,PlayerType(),aPlayer[:row]-1,aPlayer[:col]) ok on Key_Down if aPlayer[:row] < C_LEVEL_ROWSCOUNT nRowDiff = 1 nColDiff = 0 MoveObject(oGame,PlayerType(),aPlayer[:row]+1,aPlayer[:col]) ok off if lPlayerWin = False if CheckWin() lPlayerWin = True DisplayYouWin(oGame) ok ok }   }   text { x = 70 y=550 animate = false size = 20 file = "fonts/pirulen.ttf" text = "Level:" color = rgb(0,0,0) } NewButton(oGame,180,550,150,30,"Level 1",:Click1) NewButton(oGame,350,550,150,30,"Level 2",:Click2) }   func MoveObject oGame,nObjectType,nNewRow,nNewCol lMove = False switch nObjectType on C_PLAYER switch aLevel[nNewRow][nNewCol] on C_EMPTY aLevel[aPlayer[:row]][aPlayer[:col]] = C_EMPTY aLevel[nNewRow][nNewCol] = C_PLAYER UpdateGameMap(oGame) aPlayer[:row] = nNewRow aPlayer[:col] = nNewCol lMove = True on C_DOOR aLevel[aPlayer[:row]][aPlayer[:col]] = C_EMPTY aLevel[nNewRow][nNewCol] = C_PLAYERONDOOR UpdateGameMap(oGame) aPlayer[:row] = nNewRow aPlayer[:col] = nNewCol lMove = True on C_BOX aCurrentBox[:row] = nNewRow aCurrentBox[:col] = nNewCol if MoveObject(oGame,C_BOX,nNewRow+nRowDiff,nNewCol+nColDiff) aLevel[aPlayer[:row]][aPlayer[:col]] = C_EMPTY aLevel[nNewRow][nNewCol] = C_PLAYER UpdateGameMap(oGame) aPlayer[:row] = nNewRow aPlayer[:col] = nNewCol lMove = True ok on C_BOXONDOOR aCurrentBox[:row] = nNewRow aCurrentBox[:col] = nNewCol if MoveObject(oGame,C_BOXONDOOR,nNewRow+nRowDiff,nNewCol+nColDiff) aLevel[aPlayer[:row]][aPlayer[:col]] = C_EMPTY aLevel[nNewRow][nNewCol] = C_PLAYERONDOOR UpdateGameMap(oGame) aPlayer[:row] = nNewRow aPlayer[:col] = nNewCol lMove = True ok off on C_PLAYERONDOOR switch aLevel[nNewRow][nNewCol] on C_EMPTY aLevel[aPlayer[:row]][aPlayer[:col]] = C_DOOR aLevel[nNewRow][nNewCol] = C_PLAYER UpdateGameMap(oGame) aPlayer[:row] = nNewRow aPlayer[:col] = nNewCol lMove = True on C_DOOR aLevel[aPlayer[:row]][aPlayer[:col]] = C_DOOR aLevel[nNewRow][nNewCol] = C_PLAYERONDOOR UpdateGameMap(oGame) aPlayer[:row] = nNewRow aPlayer[:col] = nNewCol lMove = True on C_BOX aCurrentBox[:row] = nNewRow aCurrentBox[:col] = nNewCol if MoveObject(oGame,C_BOX,nNewRow+nRowDiff,nNewCol+nColDiff) aLevel[aPlayer[:row]][aPlayer[:col]] = C_DOOR aLevel[nNewRow][nNewCol] = C_PLAYER UpdateGameMap(oGame) aPlayer[:row] = nNewRow aPlayer[:col] = nNewCol lMove = True ok on C_BOXONDOOR aCurrentBox[:row] = nNewRow aCurrentBox[:col] = nNewCol if MoveObject(oGame,C_BOXONDOOR,nNewRow+nRowDiff,nNewCol+nColDiff) aLevel[aPlayer[:row]][aPlayer[:col]] = C_DOOR aLevel[nNewRow][nNewCol] = C_PLAYER UpdateGameMap(oGame) aPlayer[:row] = nNewRow aPlayer[:col] = nNewCol lMove = True ok off on C_BOX switch aLevel[nNewRow][nNewCol] on C_EMPTY aLevel[aCurrentBox[:row]][aCurrentBox[:col]] = C_EMPTY aLevel[nNewRow][nNewCol] = C_BOX UpdateGameMap(oGame) lMove = True on C_DOOR aLevel[aCurrentBox[:row]][aCurrentBox[:col]] = C_EMPTY aLevel[nNewRow][nNewCol] = C_BOXONDOOR UpdateGameMap(oGame) lMove = True on C_BOX aOldBox = aCurrentBox aCurrentBox[:row] = nNewRow aCurrentBox[:col] = nNewCol if MoveObject(oGame,C_BOX,nNewRow+nRowDiff,nNewCol+nColDiff) aCurrentBox = aOldBox aLevel[aCurrentBox[:row]][aCurrentBox[:col]] = C_EMPTY aLevel[nNewRow][nNewCol] = C_BOX UpdateGameMap(oGame) lMove = True ok on C_BOXONDOOR aOldBox = aCurrentBox aCurrentBox[:row] = nNewRow aCurrentBox[:col] = nNewCol if MoveObject(oGame,C_BOXONDOOR,nNewRow+nRowDiff,nNewCol+nColDiff) aCurrentBox = aOldBox aLevel[aCurrentBox[:row]][aCurrentBox[:col]] = C_EMPTY aLevel[nNewRow][nNewCol] = C_BOXONDOOR UpdateGameMap(oGame) lMove = True ok off on C_BOXONDOOR switch aLevel[nNewRow][nNewCol] on C_EMPTY aLevel[aCurrentBox[:row]][aCurrentBox[:col]] = C_DOOR aLevel[nNewRow][nNewCol] = C_BOX UpdateGameMap(oGame) lMove = True on C_DOOR aLevel[aCurrentBox[:row]][aCurrentBox[:col]] = C_DOOR aLevel[nNewRow][nNewCol] = C_BOXONDOOR UpdateGameMap(oGame) lMove = True on C_BOX aOldBox = aCurrentBox aCurrentBox[:row] = nNewRow aCurrentBox[:col] = nNewCol if MoveObject(oGame,C_BOX,nNewRow+nRowDiff,nNewCol+nColDiff) aCurrentBox = aOldBox aLevel[aCurrentBox[:row]][aCurrentBox[:col]] = C_DOOR aLevel[nNewRow][nNewCol] = C_BOX UpdateGameMap(oGame) lMove = True ok on C_BOXONDOOR aOldBox = aCurrentBox aCurrentBox[:row] = nNewRow aCurrentBox[:col] = nNewCol if MoveObject(oGame,C_BOXONDOOR,nNewRow+nRowDiff,nNewCol+nColDiff) aCurrentBox = aOldBox aLevel[aCurrentBox[:row]][aCurrentBox[:col]] = C_DOOR aLevel[nNewRow][nNewCol] = C_BOXONDOOR UpdateGameMap(oGame) lMove = True ok   off off return lMove   func UpdateGameMap oGame # The Map is our first object in Game Objects oGame.aObjects[1].aMap = aLevel   func PlayerType # It could be (Player) or (Player on door) return aLevel[aPlayer[:row]][aPlayer[:col]]   func CheckWin for aRow in aLevel if find(aRow,C_DOOR) or find(aRow,C_PLAYERONDOOR) return False ok next return True   func DisplayYouWin oGame oGame { text { point = 400 size = 30 nStep = 9 file = "fonts/pirulen.ttf" text = "You Win !!!" x = 500 y=10 state = func ogame,oself { if oself.y >= 400 ogame.remove(oSelf.nIndex) ok } } }   func NewButton oGame,nX,nY,nWidth,nHeight,cText,cFunc oGame { Object { x = nX y=nY width = nWidth height=nHeight AddAttribute(self,:Text) AddAttribute(self,:EventCode) Text = cText EventCode = cFunc draw = func oGame,oSelf { oSelf { gl_draw_filled_rectangle(x,y,x+width,y+height,gl_map_rgb(0,100,255)) gl_draw_rectangle(x,y,x+width,y+height,gl_map_rgb(0,0,0),2) oFont = oResources.LoadFont("fonts/pirulen.ttf",20) gl_draw_text(oFont,gl_map_rgb(0,0,0),x+width/2,y+5,1,Text) } } mouse = func oGame,oSelf,nType,aMouseList { if nType = GE_MOUSE_UP MouseX = aMouseList[GE_MOUSE_X] MouseY = aMouseList[GE_MOUSE_Y] oSelf { if MouseX >= x and MouseX <= X+270 and MouseY >= y and MouseY <= Y+40 call EventCode(oGame,oSelf) ok } ok } } } return len(oGame.aObjects)   func Click1 oGame,oSelf aLevel = aLevel1 nActiveLevel = 1 aPlayer = aPlayerCopy UpdateGameMap(oGame) lPlayerWin = False   func Click2 oGame,oSelf aLevel = aLevel2 nActiveLevel = 2 aPlayer = aPlayerCopy UpdateGameMap(oGame) lPlayerWin = False  
http://rosettacode.org/wiki/Solve_a_Holy_Knight%27s_tour
Solve a Holy Knight's tour
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. This kind of knight's tour puzzle is similar to   Hidato. The present task is to produce a solution to such problems. At least demonstrate your program by solving the following: Example 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 Note that the zeros represent the available squares, not the pennies. Extra credit is available for other interesting examples. Related tasks A* search algorithm Knight's tour N-queens problem Solve a Hidato puzzle Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle
#Python
Python
  from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ]     def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1   for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > -1 and pz[x][y] == 0: pz[x][y] = idx if 1 == solve(pz, sz, x, y, idx + 1, cnt): return 1 pz[x][y] = 0   return 0     def find_solution(pz, sz): p = [[-1 for j in range(sz)] for i in range(sz)] idx = x = y = cnt = 0 for j in range(sz): for i in range(sz): if pz[idx] == "x": p[i][j] = 0 cnt += 1 elif pz[idx] == "s": p[i][j] = 1 cnt += 1 x = i y = j idx += 1   if 1 == solve(p, sz, x, y, 2, cnt): for j in range(sz): for i in range(sz): if p[i][j] != -1: stdout.write(" {:0{}d}".format(p[i][j], 2)) else: stdout.write(" ") print() else: print("Cannot solve this puzzle!")     # entry point find_solution(".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8) print() find_solution(".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13)  
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Sort an array of composite structures by a key. For example, if you define a composite structure that presents a name-value pair (in pseudo-code): Define structure pair such that: name as a string value as a string and an array of such pairs: x: array of pairs then define a sort routine that sorts the array x by the key name. This task can always be accomplished with Sorting Using a Custom Comparator. If your language is not listed here, please see the other article.
#Haskell
Haskell
import Data.List import Data.Function (on)   data Person = P String Int deriving (Eq)   instance Show Person where show (P name val) = "Person " ++ name ++ " with value " ++ show val   instance Ord Person where compare (P a _) (P b _) = compare a b   pVal :: Person -> Int pVal (P _ x) = x   people :: [Person] people = [P "Joe" 12, P "Bob" 8, P "Alice" 9, P "Harry" 2]     main :: IO () main = do mapM_ print $ sort people putStrLn [] mapM_ print $ sortBy (on compare pVal) people
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You are also given eight pegs numbered   1-to-8. Objective Place the eight pegs in the holes so that the (absolute) difference between any two numbers connected by any line is greater than one. Example In this attempt: 4 7 /│\ /│\ / │ X │ \ / │/ \│ \ 8───1───6───2 \ │\ /│ / \ │ X │ / \│/ \│/ 3 5 Note that   7   and   6   are connected and have a difference of   1,   so it is   not   a solution. Task Produce and show here   one   solution to the puzzle. Related tasks   A* search algorithm   Solve a Holy Knight's tour   Knight's tour   N-queens problem   Solve a Hidato puzzle   Solve a Holy Knight's tour   Solve a Hopido puzzle   Solve a Numbrix puzzle   4-rings or 4-squares puzzle See also No Connection Puzzle (youtube).
#Python
Python
from __future__ import print_function from itertools import permutations from enum import Enum   A, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H')   connections = ((A, C), (A, D), (A, E), (B, D), (B, E), (B, F), (G, C), (G, D), (G, E), (H, D), (H, E), (H, F), (C, D), (D, E), (E, F))     def ok(conn, perm): """Connected numbers ok?""" this, that = (c.value - 1 for c in conn) return abs(perm[this] - perm[that]) != 1     def solve(): return [perm for perm in permutations(range(1, 9)) if all(ok(conn, perm) for conn in connections)]     if __name__ == '__main__': solutions = solve() print("A, B, C, D, E, F, G, H =", ', '.join(str(i) for i in solutions[0]))
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#Huginn
Huginn
main() { nums = [2, 4, 3, 1, 2]; nums.sort(); }
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#Icon_and_Unicon
Icon and Unicon
S := sort(L:= [63, 92, 51, 92, 39, 15, 43, 89, 36, 69]) # will sort a list
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Object identifiers (OID) Task Show how to sort a list of OIDs, in their natural sort order. Details An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number. Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields. Test case Input (list of strings) Output (list of strings) 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11150.3.4.0.1 Related tasks Natural sorting Sort using a custom comparator
#zkl
zkl
fcn sortOIDS(oids){ // oids is not modified, a new list is created // pad each oid with a terminal (-1) so zip won't short cut oids=oids.pump(List(),fcn(oid){ (oid + ".-1").split(".").apply("toInt") }); oids.sort( // in place sort fcn(a,b){ // a & b are (x,y,z,...-1), eg (0,4,2,54,-1), (4,6,-1) a.zip(b).reduce(fcn(_,[(a,b)]){ // if one list longer, zip truncates if(a==b) return(True); // continue to next field return(Void.Stop,a<b); // OIDa<OIDb == cmp this field },True); }); oids.pump(List,fcn(list){ list[0,-1].concat(".") }) // back to strings }
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted. Make your example work with the following list of values and set of indices: Values: [7, 6, 5, 4, 3, 2, 1, 0] Indices: {6, 1, 7} Where the correct result would be: [7, 0, 5, 4, 3, 2, 1, 6]. In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead. The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given. Cf.   Order disjoint list items
#ooRexx
ooRexx
data = .array~of(7, 6, 5, 4, 3, 2, 1, 0) -- this could be a list, array, or queue as well because of polymorphism -- also, ooRexx arrays are 1-based, so using the alternate index set for the -- problem. indexes = .set~of(7, 2, 8) call disjointSorter data, indexes   say "Sorted data is: ["data~toString("l", ", ")"]"   ::routine disjointSorter use arg data, indexes temp = .array~new(indexes~items) -- we want to process these in a predictable order, so make an array tempIndexes = indexes~makearray -- we can't just assign things back in the same order. The expected -- result requires the items be inserted back in first-to-last index -- order, so we need to sort the index values too tempIndexes~sortWith(.numberComparator~new) do index over tempIndexes temp~append(data[index]) end -- sort as numbers temp~sortwith(.numberComparator~new)   do i = 1 to tempIndexes~items data[tempIndexes[i]] = temp[i] end   -- a custom comparator that sorts strings as numeric values rather than -- strings ::class numberComparator subclass comparator ::method compare use strict arg left, right -- perform the comparison on the names. By subtracting -- the two and returning the sign, we give the expected -- results for the compares return (left - right)~sign
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#PHP
PHP
<?php function mycmp($s1, $s2) { if ($d = strlen($s2) - strlen($s1)) return $d; return strcasecmp($s1, $s2); }   $strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted"); usort($strings, "mycmp"); ?>
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Bogosort a list of numbers. Bogosort simply shuffles a collection randomly until it is sorted. "Bogosort" is a perversely inefficient algorithm only used as an in-joke. Its average run-time is   O(n!)   because the chance that any given shuffle of a set will end up in sorted order is about one in   n   factorial,   and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence. Its best case is   O(n)   since a single pass through the elements may suffice to order them. Pseudocode: while not InOrder(list) do Shuffle(list) done The Knuth shuffle may be used to implement the shuffle part of this algorithm.
#zkl
zkl
fcn increasing(list){ list.len()<2 or list.reduce(fcn(a,b){ if(b<a) return(Void.Stop,False); b }).toBool() }   ns:=L(5,23,1,6,123,7,23); while(not increasing(ns)){ ns=ns.shuffle() } ns.println();
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#Groovy
Groovy
def makeSwap = { a, i, j = i+1 -> print "."; a[[i,j]] = a[[j,i]] }   def checkSwap = { a, i, j = i+1 -> [(a[i] > a[j])].find { it }.each { makeSwap(a, i, j) } }   def bubbleSort = { list -> boolean swapped = true while (swapped) { swapped = (1..<list.size()).any { checkSwap(list, it-1) } } list }
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#PureBasic
PureBasic
Procedure GnomeSort(Array a(1)) Protected Size = ArraySize(a()) + 1 Protected i = 1, j = 2   While i < Size If a(i - 1) <= a(i) ;for descending SORT, use >= for comparison i = j j + 1 Else Swap a(i - 1), a(i) i - 1 If i = 0 i = j j + 1 EndIf EndIf Wend EndProcedure
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#PHP
PHP
function cocktailSort($arr){ if (is_string($arr)) $arr = str_split(preg_replace('/\s+/','',$arr));   do{ $swapped = false; for($i=0;$i<count($arr);$i++){ if(isset($arr[$i+1])){ if($arr[$i] > $arr[$i+1]){ list($arr[$i], $arr[$i+1]) = array($arr[$i+1], $arr[$i]); $swapped = true; } } }   if ($swapped == false) break;   $swapped = false; for($i=count($arr)-1;$i>=0;$i--){ if(isset($arr[$i-1])){ if($arr[$i] < $arr[$i-1]) { list($arr[$i],$arr[$i-1]) = array($arr[$i-1],$arr[$i]); $swapped = true; } } } }while($swapped);   return $arr; } $arr = array(5, 1, 7, 3, 6, 4, 2); $arr2 = array("John", "Kate", "Alice", "Joe", "Jane"); $strg = "big fjords vex quick waltz nymph"; $arr = cocktailSort($arr); $arr2 = cocktailSort($arr2); $strg = cocktailSort($strg); echo implode(',',$arr) . '<br>'; echo implode(',',$arr2) . '<br>'; echo implode('',$strg) . '<br>';
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Java
Java
import java.io.IOException; import java.net.*; public class SocketSend { public static void main(String args[]) throws IOException { sendData("localhost", "hello socket world"); }   public static void sendData(String host, String msg) throws IOException { Socket sock = new Socket( host, 256 ); sock.getOutputStream().write(msg.getBytes()); sock.getOutputStream().flush(); sock.close(); } }
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Jsish
Jsish
#!/usr/bin/env jsish function sockets() { var sock = new Socket({client:true, port:256, noAsync:true, udp:true}); sock.send(-1, 'hello socket world'); sock.close(); }   ;sockets();   /* =!EXPECTSTART!= sockets() ==> undefined =!EXPECTEND!= */
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also OEIS A019546: Primes whose digits are primes. https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
#Phix
Phix
with javascript_semantics atom t0 = time() sequence spds = {2,3,5,7} atom nxt_candidate = 23 sequence adj = {{4,-4},sq_mul({1,2,2,-5},10)}, adjn = {1,1} include mpfr.e mpz zprime = mpz_init() procedure populate_spds(integer n) while length(spds)<n do mpz_set_d(zprime,nxt_candidate) if mpz_prime(zprime) then spds &= nxt_candidate end if for i=1 to length(adjn) do sequence adjs = adj[i] integer adx = adjn[i] nxt_candidate += adjs[adx] adx += 1 if adx<=length(adjs) then adjn[i] = adx exit end if adjn[i] = 1 if i=length(adjn) then -- (this is eg 777, by now 223 carry 1, -> 2223) adj = append(adj,sq_mul(adj[$],10)) adjn = append(adjn, 1) nxt_candidate += adj[$][2] exit end if end for end while end procedure populate_spds(25) printf(1,"spds[1..25]:%v\n",{spds[1..25]}) for n=2 to 5 do integer p = power(10,n) populate_spds(p) printf(1,"spds[%,d]:%,d\n",{p,spds[p]}) end for for n=7 to 10 do atom p = power(10,n), dx = abs(binary_search(p,spds))-1 printf(1,"largest spds prime less than %,15d:%,14d\n",{p,spds[dx]}) end for ?elapsed(time()-t0)
http://rosettacode.org/wiki/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Snake is a game where the player maneuvers a line which grows in length every time the snake reaches a food source. Task Implement a variant of the Snake game, in any interactive environment, in which a sole player attempts to eat items by running into them with the head of the snake. Each item eaten makes the snake longer and a new item is randomly generated somewhere else on the plane. The game ends when the snake attempts to eat himself.
#Haskell
Haskell
{-# LANGUAGE TemplateHaskell #-} import Control.Monad.Random (getRandomRs) import Graphics.Gloss.Interface.Pure.Game import Lens.Micro ((%~), (^.), (&), set) import Lens.Micro.TH (makeLenses)   -------------------------------------------------------------------------------- -- all data types   data Snake = Snake { _body :: [Point], _direction :: Point } makeLenses ''Snake   data World = World { _snake :: Snake , _food :: [Point] , _score :: Int , _maxScore :: Int } makeLenses ''World   -------------------------------------------------------------------------------- -- everything snake can do   moves (Snake b d) = Snake (step b d : init b) d eats (Snake b d) = Snake (step b d : b) d bites (Snake b _) = any (== head b) step ((x,y):_) (a,b) = (x+a, y+b)   turn (x',y') (Snake b (x,y)) | (x+x',y+y') == (0,0) = Snake b (x,y) | otherwise = Snake b (x',y')   -------------------------------------------------------------------------------- -- all randomness   createWorld = do xs <- map fromIntegral <$> getRandomRs (2, 38 :: Int) ys <- map fromIntegral <$> getRandomRs (2, 38 :: Int) return (Ok, World snake (zip xs ys) 0 0) where snake = Snake [(20, 20)] (1,0)   ------------------------------------------------------------------------------- -- A tyny DSL for declarative description of business logic   data Status = Ok | Fail | Stop   continue = \x -> (Ok, x) stop = \x -> (Stop, x) f >>> g = \x -> case f x of { (Ok, y) -> g y; b -> b } -- chain composition f <|> g = \x -> case f x of { (Fail, _) -> g x; b -> b } -- alternative p ==> f = \x -> if p x then f x else (Fail, x) -- condition l .& f = continue . (l %~ f) -- modification l .= y = continue . set l y -- setting   -------------------------------------------------------------------------------- -- all business logic   updateWorld _ = id >>> (snakeEats <|> snakeMoves) where snakeEats = (snakeFindsFood ==> (snake .& eats)) >>> (score .& (+1)) >>> (food .& tail)   snakeMoves = (snakeBitesTail ==> stop) <|> (snakeHitsWall ==> stop) <|> (snake .& moves)   snakeFindsFood w = (w^.snake & moves) `bites` (w^.food & take 1) snakeBitesTail w = (w^.snake) `bites` (w^.snake.body & tail) snakeHitsWall w = (w^.snake.body) & head & isOutside isOutside (x,y) = or [x <= 0, 40 <= x, y <= 0, 40 <= y]   -------------------------------------------------------------------------------- -- all event handing   handleEvents e (s,w) = f w where f = case s of Ok -> case e of EventKey (SpecialKey k) _ _ _ -> case k of KeyRight -> snake .& turn (1,0) KeyLeft -> snake .& turn (-1,0) KeyUp -> snake .& turn (0,1) KeyDown -> snake .& turn (0,-1) _-> continue _-> continue _-> \w -> w & ((snake.body) .= [(20,20)]) >>> (maxScore .& max (w^.score)) >>> (score .= 0)   -------------------------------------------------------------------------------- -- all graphics   renderWorld (s, w) = pictures [frame, color c drawSnake, drawFood, showScore] where c = case s of { Ok -> orange; _-> red } drawSnake = foldMap (rectangleSolid 10 10 `at`) (w^.snake.body) drawFood = color blue $ circleSolid 5 `at` (w^.food & head) frame = color black $ rectangleWire 400 400 showScore = color orange $ scale 0.2 0.2 $ txt `at` (-80,130) txt = Text $ mconcat ["Score: ", w^.score & show ," Maximal score: ", w^.maxScore & show] at p (x,y) = Translate (10*x-200) (10*y-200) p   --------------------------------------------------------------------------------   main = do world <- createWorld play inW white 7 world renderWorld handleEvents updateWorld where inW = InWindow "The Snake" (400, 400) (10, 10)
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers. Example Using the number 166 Find the prime factors of 166 which are: 2 x 83 Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13 Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13 Therefore, the number 166 is a Smith number. Task Write a program to find all Smith numbers below 10000. See also from Wikipedia:   [Smith number]. from MathWorld:   [Smith number]. from OEIS A6753:   [OEIS sequence A6753]. from OEIS A104170:   [Number of Smith numbers below 10^n]. from The Prime pages:   [Smith numbers].
#C.23
C#
using System; using System.Collections.Generic;   namespace SmithNumbers { class Program { static int SumDigits(int n) { int sum = 0; while (n > 0) { n = Math.DivRem(n, 10, out int rem); sum += rem; } return sum; }   static List<int> PrimeFactors(int n) { List<int> result = new List<int>();   for (int i = 2; n % i == 0; n /= i) { result.Add(i); }   for (int i = 3; i * i < n; i += 2) { while (n % i == 0) { result.Add(i); n /= i; } }   if (n != 1) { result.Add(n); }   return result; }   static void Main(string[] args) { const int SIZE = 8; int count = 0; for (int n = 1; n < 10_000; n++) { var factors = PrimeFactors(n); if (factors.Count > 1) { int sum = SumDigits(n); foreach (var f in factors) { sum -= SumDigits(f); } if (sum == 0) { Console.Write("{0,5}", n); if (count == SIZE - 1) { Console.WriteLine(); } count = (count + 1) % SIZE; } } } } } }
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle
Solve a Hidato puzzle
The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always connected. The number “1” is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique. It may be assumed that the difference between numbers present on the grid is not greater than lucky 13. The aim is to place a natural number in each blank square so that in the sequence of numbered squares from “1” upwards, each square is in the wp:Moore neighborhood of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints). Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order. A square may only contain one number. In a proper Hidato puzzle, the solution is unique. For example the following problem has the following solution, with path marked on it: Related tasks A* search algorithm N-queens problem Solve a Holy Knight's tour Solve a Knight's tour Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle;
#Haskell
Haskell
{-# LANGUAGE TupleSections #-} {-# LANGUAGE Rank2Types #-}   import qualified Data.IntMap as I import Data.IntMap (IntMap) import Data.List import Data.Maybe import Data.Time.Clock   data BoardProblem = Board { cells :: IntMap (IntMap Int) , endVal :: Int , onePos :: (Int, Int) , givens :: [Int] } deriving (Show, Eq)   tupIns x y v m = I.insert x (I.insert y v (I.findWithDefault I.empty x m)) m   tupLookup x y m = I.lookup x m >>= I.lookup y   makeBoard = (\x -> x { givens = dropWhile (<= 1) $ sort $ givens x }) . foldl' --' f (Board I.empty 0 (0, 0) []) . concatMap (zip [0 ..]) . zipWith (\y w -> map (y, ) $ words w) [0 ..] where f bd (x, (y, v)) = if v == "." then bd else Board (tupIns x y (read v) (cells bd)) (if read v > endVal bd then read v else endVal bd) (if v == "1" then (x, y) else onePos bd) (read v : givens bd)   hidato brd = listToMaybe $ h 2 (cells brd) (onePos brd) (givens brd) where h nval pmap (x, y) gs | nval == endVal brd = [pmap] | nval == head gs = if null nvalAdj then [] else h (nval + 1) pmap (fst $ head nvalAdj) (tail gs) | not $ null nvalAdj = h (nval + 1) pmap (fst $ head nvalAdj) gs | otherwise = hEmptyAdj where around = [ (x - 1, y - 1) , (x, y - 1) , (x + 1, y - 1) , (x - 1, y) , (x + 1, y) , (x - 1, y + 1) , (x, y + 1) , (x + 1, y + 1) ] lkdUp = map (\(x, y) -> ((x, y), tupLookup x y pmap)) around nvalAdj = filter ((== Just nval) . snd) lkdUp hEmptyAdj = concatMap (\((nx, ny), _) -> h (nval + 1) (tupIns nx ny nval pmap) (nx, ny) gs) $ filter ((== Just 0) . snd) lkdUp   printCellMap cellmap = putStrLn $ concat strings where maxPos = xyBy I.findMax maximum minPos = xyBy I.findMin minimum xyBy :: (forall a. IntMap a -> (Int, a)) -> ([Int] -> Int) -> (Int, Int) xyBy a b = (fst (a cellmap), b $ map (fst . a . snd) $ I.toList cellmap) strings = map f [ (x, y) | y <- [snd minPos .. snd maxPos] , x <- [fst minPos .. fst maxPos] ] f (x, y) = let z = if x == fst maxPos then "\n" else " " in case tupLookup x y cellmap of Nothing -> " " ++ z Just n -> (if n < 10 then ' ' : show n else show n) ++ z   main = do let sampleBoard = makeBoard sample printCellMap $ cells sampleBoard printCellMap $ fromJust $ hidato sampleBoard   sample = [ " 0 33 35 0 0" , " 0 0 24 22 0" , " 0 0 0 21 0 0" , " 0 26 0 13 40 11" , "27 0 0 0 9 0 1" , ". . 0 0 18 0 0" , ". . . . 0 7 0 0" , ". . . . . . 5 0" ]
http://rosettacode.org/wiki/Sokoban
Sokoban
Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character array where space is an empty square # is a wall @ is the player $ is a box . is a goal + is the player on a goal * is a box on a goal ####### # # # # #. # # #. $$ # #.$$ # #.# @# ####### Sokoban solutions are usually stored in the LURD format, where lowercase l, u, r and d represent a move in that (left, up, right, down) direction and capital LURD represents a push. Please state if you use some other format for either the input or output, and why. For more information, see the Sokoban wiki.
#Ruby
Ruby
require 'set'   class Sokoban def initialize(level) board = level.each_line.map(&:rstrip) @nrows = board.map(&:size).max board.map!{|line| line.ljust(@nrows)} board.each_with_index do |row, r| row.each_char.with_index do |ch, c| @px, @py = c, r if ch == '@' or ch == '+' end end @goal = board.join.tr(' .@#$+*', ' . ..') .each_char.with_index.select{|ch, c| ch == '.'} .map(&:last) @board = board.join.tr(' .@#$+*', ' @#$ $') end   def pos(x, y) y * @nrows + x end   def push(x, y, dx, dy, board) # modify board return if board[pos(x+2*dx, y+2*dy)] != ' ' board[pos(x , y )] = ' ' board[pos(x + dx, y + dy)] = '@' board[pos(x+2*dx, y+2*dy)] = '$' end   def solved?(board) @goal.all?{|i| board[i] == '$'} end   DIRS = [[0, -1, 'u', 'U'], [ 1, 0, 'r', 'R'], [0, 1, 'd', 'D'], [-1, 0, 'l', 'L']] def solve queue = [[@board, "", @px, @py]] visited = Set[@board]   until queue.empty? current, csol, x, y = queue.shift   for dx, dy, cmove, cpush in DIRS work = current.dup case work[pos(x+dx, y+dy)] # next character when '$' next unless push(x, y, dx, dy, work) next unless visited.add?(work) return csol+cpush if solved?(work) queue << [work, csol+cpush, x+dx, y+dy] when ' ' work[pos(x, y)] = ' ' work[pos(x+dx, y+dy)] = '@' queue << [work, csol+cmove, x+dx, y+dy] if visited.add?(work) end end end "No solution" end end
http://rosettacode.org/wiki/Solve_a_Holy_Knight%27s_tour
Solve a Holy Knight's tour
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. This kind of knight's tour puzzle is similar to   Hidato. The present task is to produce a solution to such problems. At least demonstrate your program by solving the following: Example 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 Note that the zeros represent the available squares, not the pennies. Extra credit is available for other interesting examples. Related tasks A* search algorithm Knight's tour N-queens problem Solve a Hidato puzzle Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle
#Racket
Racket
#lang racket (require "hidato-family-solver.rkt")   (define knights-neighbour-offsets '((+1 +2) (-1 +2) (+1 -2) (-1 -2) (+2 +1) (-2 +1) (+2 -1) (-2 -1)))   (define solve-a-knights-tour (solve-hidato-family knights-neighbour-offsets))   (displayln (puzzle->string (solve-a-knights-tour #(#(_ 0 0 0 _ _ _ _) #(_ 0 _ 0 0 _ _ _) #(_ 0 0 0 0 0 0 0) #(0 0 0 _ _ 0 _ 0) #(0 _ 0 _ _ 0 0 0) #(1 0 0 0 0 0 0 _) #(_ _ 0 0 _ 0 _ _) #(_ _ _ 0 0 0 _ _)))))   (newline)   (displayln (puzzle->string (solve-a-knights-tour #(#(- - - - - 1 - 0 - - - - -) #(- - - - - 0 - 0 - - - - -) #(- - - - 0 0 0 0 0 - - - -) #(- - - - - 0 0 0 - - - - -) #(- - 0 - - 0 - 0 - - 0 - -) #(0 0 0 0 0 - - - 0 0 0 0 0) #(- - 0 0 - - - - - 0 0 - -) #(0 0 0 0 0 - - - 0 0 0 0 0) #(- - 0 - - 0 - 0 - - 0 - -) #(- - - - - 0 0 0 - - - - -) #(- - - - 0 0 0 0 0 - - - -) #(- - - - - 0 - 0 - - - - -) #(- - - - - 0 - 0 - - - - -)))))
http://rosettacode.org/wiki/Solve_a_Holy_Knight%27s_tour
Solve a Holy Knight's tour
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. This kind of knight's tour puzzle is similar to   Hidato. The present task is to produce a solution to such problems. At least demonstrate your program by solving the following: Example 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 Note that the zeros represent the available squares, not the pennies. Extra credit is available for other interesting examples. Related tasks A* search algorithm Knight's tour N-queens problem Solve a Hidato puzzle Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle
#Raku
Raku
my @adjacent = [ -2, -1], [ -2, 1], [-1,-2], [-1,+2], [+1,-2], [+1,+2], [ +2, -1], [ +2, 1];   put "\n" xx 60;   solveboard q:to/END/; . 0 0 0 . 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0 0 0 0 . . 0 0 . 0 . . . 0 0 0 END   sub solveboard($board) { my $max = +$board.comb(/\w+/); my $width = $max.chars;   my @grid; my @known; my @neigh; my @degree;   @grid = $board.lines.map: -> $line { [ $line.words.map: { /^_/ ?? 0 !! /^\./ ?? Rat !! $_ } ] }   sub neighbors($y,$x --> List) { eager gather for @adjacent { my $y1 = $y + .[0]; my $x1 = $x + .[1]; take [$y1,$x1] if defined @grid[$y1][$x1]; } }   for ^@grid -> $y { for ^@grid[$y] -> $x { if @grid[$y][$x] -> $v { @known[$v] = [$y,$x]; } if @grid[$y][$x].defined { @neigh[$y][$x] = neighbors($y,$x); @degree[$y][$x] = +@neigh[$y][$x]; } } } print "\e[0H\e[0J";   my $tries = 0;   try_fill 1, @known[1];   sub try_fill($v, $coord [$y,$x] --> Bool) { return True if $v > $max; $tries++;   my $old = @grid[$y][$x];   return False if +$old and $old != $v; return False if @known[$v] and @known[$v] !eqv $coord;   @grid[$y][$x] = $v; # conjecture grid value   print "\e[0H"; # show conjectured board for @grid -> $r { say do for @$r { when Rat { ' ' x $width } when 0 { '_' x $width } default { .fmt("%{$width}d") } } }     my @neighbors = @neigh[$y][$x][];   my @degrees; for @neighbors -> \n [$yy,$xx] { my $d = --@degree[$yy][$xx]; # conjecture new degrees push @degrees[$d], n; # and categorize by degree }   for @degrees.grep(*.defined) -> @ties { for @ties.reverse { # reverse works better for this hidato anyway return True if try_fill $v + 1, $_; } }   for @neighbors -> [$yy,$xx] { ++@degree[$yy][$xx]; # undo degree conjectures }   @grid[$y][$x] = $old; # undo grid value conjecture return False; }   say "$tries tries"; }
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Sort an array of composite structures by a key. For example, if you define a composite structure that presents a name-value pair (in pseudo-code): Define structure pair such that: name as a string value as a string and an array of such pairs: x: array of pairs then define a sort routine that sorts the array x by the key name. This task can always be accomplished with Sorting Using a Custom Comparator. If your language is not listed here, please see the other article.
#Icon_and_Unicon
Icon and Unicon
record star(name,HIP)   procedure main()   Ori := [ star("Betelgeuse",27989), star("Rigel",24436), star("Belatrix", 25336), star("Alnilam",26311) ]   write("Some Orion stars by HIP#") every write( (x := !sortf(Ori,2)).name, " HIP ",x.HIP) end
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Sort an array of composite structures by a key. For example, if you define a composite structure that presents a name-value pair (in pseudo-code): Define structure pair such that: name as a string value as a string and an array of such pairs: x: array of pairs then define a sort routine that sorts the array x by the key name. This task can always be accomplished with Sorting Using a Custom Comparator. If your language is not listed here, please see the other article.
#J
J
names =: ;: 'Perlis Wilkes Hamming Minsky Wilkinson McCarthy' values=: ;: 'Alan Maurice Richard Marvin James John' pairs =: values ,. names pairs /: names +-------+---------+ |Richard|Hamming | +-------+---------+ |John |McCarthy | +-------+---------+ |Marvin |Minsky | +-------+---------+ |Alan |Perlis | +-------+---------+ |Maurice|Wilkes | +-------+---------+ |James |Wilkinson| +-------+---------+
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You are also given eight pegs numbered   1-to-8. Objective Place the eight pegs in the holes so that the (absolute) difference between any two numbers connected by any line is greater than one. Example In this attempt: 4 7 /│\ /│\ / │ X │ \ / │/ \│ \ 8───1───6───2 \ │\ /│ / \ │ X │ / \│/ \│/ 3 5 Note that   7   and   6   are connected and have a difference of   1,   so it is   not   a solution. Task Produce and show here   one   solution to the puzzle. Related tasks   A* search algorithm   Solve a Holy Knight's tour   Knight's tour   N-queens problem   Solve a Hidato puzzle   Solve a Holy Knight's tour   Solve a Hopido puzzle   Solve a Numbrix puzzle   4-rings or 4-squares puzzle See also No Connection Puzzle (youtube).
#Racket
Racket
#lang racket ;; Solve the no connection puzzle. Tim Brown Oct. 2014   ;; absolute difference of a and b if they are both true (define (and- a b) (and a b (abs (- a b))))   ;; Finds the differences of all established connections in the network (define (network-diffs (A #f) (B #f) (C #f) (D #f) (E #f) (F #f) (G #f) (H #f)) (list (and- A C) (and- A D) (and- A E) (and- B D) (and- B E) (and- B F) (and- C D) (and- C G) (and- D E) (and- D G) (and- D H) (and- E F) (and- E G) (and- E H) (and- F G)))   ;; Make sure there is “no connection” in the network N; return N if good (define (good-network? N) (and (for/and ((d (filter values (apply network-diffs N)))) (> d 1)) N))   ;; possible optimisation is to reverse the arguments to network-diffs, reverse the return value from ;; this function and make this a cons but we're pretty quick here as it is. (define (find-good-network pegs (n/w null)) (if (null? pegs) n/w (for*/or ((p pegs)) (define n/w+ (append n/w (list p))) (and (good-network? n/w+) (find-good-network (remove p pegs =) n/w+)))))   (define (render-puzzle pzl) (apply printf (regexp-replace* "O" #<<EOS O O /|\ /|\ / | X | \ / |/ \| \ O - O - O - O \ |\ /| / \ | X | / \|/ \|/ O O~% EOS "~a") pzl))   (render-puzzle (find-good-network '(1 2 3 4 5 6 7 8)))
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You are also given eight pegs numbered   1-to-8. Objective Place the eight pegs in the holes so that the (absolute) difference between any two numbers connected by any line is greater than one. Example In this attempt: 4 7 /│\ /│\ / │ X │ \ / │/ \│ \ 8───1───6───2 \ │\ /│ / \ │ X │ / \│/ \│/ 3 5 Note that   7   and   6   are connected and have a difference of   1,   so it is   not   a solution. Task Produce and show here   one   solution to the puzzle. Related tasks   A* search algorithm   Solve a Holy Knight's tour   Knight's tour   N-queens problem   Solve a Hidato puzzle   Solve a Holy Knight's tour   Solve a Hopido puzzle   Solve a Numbrix puzzle   4-rings or 4-squares puzzle See also No Connection Puzzle (youtube).
#Raku
Raku
my @adjacent = gather -> $y, $x { take [$y,$x] if abs($x|$y) > 2; } for flat -5 .. 5 X -5 .. 5;   solveboard q:to/END/; . _ . . _ . . . . . . . _ . _ 1 . _ . . . . . . . _ . . _ . END   sub solveboard($board) { my $max = +$board.comb(/\w+/); my $width = $max.chars;   my @grid; my @known; my @neigh; my @degree;   @grid = $board.lines.map: -> $line { [ $line.words.map: { /^_/ ?? 0 !! /^\./ ?? Rat !! $_ } ] }   sub neighbors($y,$x --> List) { eager gather for @adjacent { my $y1 = $y + .[0]; my $x1 = $x + .[1]; take [$y1,$x1] if defined @grid[$y1][$x1]; } }   for ^@grid -> $y { for ^@grid[$y] -> $x { if @grid[$y][$x] -> $v { @known[$v] = [$y,$x]; } if @grid[$y][$x].defined { @neigh[$y][$x] = neighbors($y,$x); @degree[$y][$x] = +@neigh[$y][$x]; } } } print "\e[0H\e[0J";   my $tries = 0;   try_fill 1, @known[1];   sub try_fill($v, $coord [$y,$x] --> Bool) { return True if $v > $max; $tries++;   my $old = @grid[$y][$x];   return False if +$old and $old != $v; return False if @known[$v] and @known[$v] !eqv $coord;   @grid[$y][$x] = $v; # conjecture grid value   print "\e[0H"; # show conjectured board for @grid -> $r { say do for @$r { when Rat { ' ' x $width } when 0 { '_' x $width } default { .fmt("%{$width}d") } } }     my @neighbors = @neigh[$y][$x][];   my @degrees; for @neighbors -> \n [$yy,$xx] { my $d = --@degree[$yy][$xx]; # conjecture new degrees push @degrees[$d], n; # and categorize by degree }   for @degrees.grep(*.defined) -> @ties { for @ties.reverse { # reverse works better for this hidato anyway return True if try_fill $v + 1, $_; } }   for @neighbors -> [$yy,$xx] { ++@degree[$yy][$xx]; # undo degree conjectures }   @grid[$y][$x] = $old; # undo grid value conjecture return False; }   say "$tries tries"; }
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#IDL
IDL
result = array[sort(array)]
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#Inform_7
Inform 7
let L be {5, 4, 7, 1, 18}; sort L;
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted. Make your example work with the following list of values and set of indices: Values: [7, 6, 5, 4, 3, 2, 1, 0] Indices: {6, 1, 7} Where the correct result would be: [7, 0, 5, 4, 3, 2, 1, 6]. In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead. The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given. Cf.   Order disjoint list items
#Order
Order
#include <order/interpreter.h>   #define ORDER_PP_DEF_8sort_disjoint_sublist ORDER_PP_FN( \ 8fn(8L, 8I, \ 8lets((8I, 8seq_sort(8less, 8tuple_to_seq(8I))) \ (8J, \ 8seq_sort(8less, 8seq_map(8fn(8X, 8seq_at(8X, 8L)), 8I))), \ 8replace(8L, 8I, 8J))) )   #define ORDER_PP_DEF_8replace ORDER_PP_FN( \ 8fn(8L, 8I, 8V, \ 8if(8is_nil(8I), \ 8L, \ 8replace(8seq_set(8seq_head(8I), 8L, 8seq_head(8V)), \ 8seq_tail(8I), 8seq_tail(8V)))) )   ORDER_PP( 8sort_disjoint_sublist(8seq(7, 6, 5, 4, 3, 2, 1, 0), 8tuple(6, 1, 7)) )
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted. Make your example work with the following list of values and set of indices: Values: [7, 6, 5, 4, 3, 2, 1, 0] Indices: {6, 1, 7} Where the correct result would be: [7, 0, 5, 4, 3, 2, 1, 6]. In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead. The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given. Cf.   Order disjoint list items
#PARI.2FGP
PARI/GP
sortsome(v,which)={ my(x=sum(i=1,#which,1<<(which[i]-1)),u=vecextract(v,x)); u=vecsort(u); which=vecsort(which); for(i=1,#which,v[which[i]]=u[i]); v };
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#PicoLisp
PicoLisp
: (sort '("def" "abc" "ghi") >) -> ("ghi" "def" "abc")
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#PL.2FI
PL/I
MRGEPKG: package exports(MERGESORT,MERGE,RMERGE);   DCL (T(4)) CHAR(20) VAR; /* scratch space of length N/2 */   MERGE: PROCEDURE (A,LA,B,LB,C,CMPFN); DECLARE (A(*),B(*),C(*)) CHAR(*) VAR; DECLARE (LA,LB) FIXED BIN(31) NONASGN; DECLARE (I,J,K) FIXED BIN(31); DECLARE CMPFN ENTRY( NONASGN CHAR(*) VAR, NONASGN CHAR(*) VAR) RETURNS (FIXED bin(31));   I=1; J=1; K=1; DO WHILE ((I <= LA) & (J <= LB)); IF CMPFN(A(I),B(J)) <= 0 THEN DO; C(K)=A(I); K=K+1; I=I+1; END; ELSE DO; C(K)=B(J); K=K+1; J=J+1; END; END; DO WHILE (I <= LA); C(K)=A(I); I=I+1; K=K+1; END; return; END MERGE;   MERGESORT: PROCEDURE (A,N,CMPFN) RECURSIVE ; DECLARE (A(*)) CHAR(*) VAR; DECLARE N FIXED BINARY(31) NONASGN; DECLARE CMPFN ENTRY( NONASGN CHAR(*) VAR, NONASGN CHAR(*) VAR) RETURNS (FIXED bin(31)); DECLARE (M,I) FIXED BINARY; DECLARE AMP1(N) CHAR(20) VAR BASED(P); DECLARE P POINTER;   IF (N=1) THEN RETURN; M = trunc((N+1)/2); IF M > 1 THEN CALL MERGESORT(A,M,CMPFN); P=ADDR(A(M+1)); IF (N-M > 1) THEN CALL MERGESORT(AMP1,N-M,CMPFN); IF CMPFN(A(M),AMP1(1)) <= 0 THEN RETURN; DO I=1 to M; T(I)=A(I); END; CALL MERGE(T,M,AMP1,N-M,A,CMPFN); END MERGESORT;   RMERGE: PROC OPTIONS(MAIN); DCL I FIXED BIN(31); DCL A(8) CHAR(20) VAR INIT("this","is","a","set","of","strings","to","sort");   MyCMP: PROCEDURE(A,B) RETURNS (FIXED BIN(31)); DCL (A,B) CHAR(*) VAR NONASGN; DCL (I,J) FIXED BIN(31);   I = length(trim(A)); J = length(trim(B)); IF I < J THEN RETURN(+1); IF I > J THEN RETURN(-1); IF lowercase(A) < lowercase(B) THEN RETURN(-1); IF lowercase(A) > lowercase(B) THEN RETURN(+1); RETURN (0); END MyCMP;   CALL MERGESORT(A,8,MyCMP); DO I=1 TO 8; put edit (I,A(I)) (F(5),X(2),A(10)) skip; END;   put skip; END RMERGE;
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#Haskell
Haskell
bsort :: Ord a => [a] -> [a] bsort s = case _bsort s of t | t == s -> t | otherwise -> bsort t where _bsort (x:x2:xs) | x > x2 = x2:(_bsort (x:xs)) | otherwise = x:(_bsort (x2:xs)) _bsort s = s
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is: function gnomeSort(a[0..size-1]) i := 1 j := 2 while i < size do if a[i-1] <= a[i] then // for descending sort, use >= for comparison i := j j := j + 1 else swap a[i-1] and a[i] i := i - 1 if i = 0 then i := j j := j + 1 endif endif done Task Implement the Gnome sort in your language to sort an array (or list) of numbers.
#Python
Python
>>> def gnomesort(a): i,j,size = 1,2,len(a) while i < size: if a[i-1] <= a[i]: i,j = j, j+1 else: a[i-1],a[i] = a[i],a[i-1] i -= 1 if i == 0: i,j = j, j+1 return a   >>> gnomesort([3,4,2,5,1,6]) [1, 2, 3, 4, 5, 6] >>>
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#PicoLisp
PicoLisp
(de cocktailSort (Lst) (use (Swapped L) (loop (off Swapped) (setq L Lst) (while (cdr L) (when (> (car L) (cadr L)) (xchg L (cdr L)) (on Swapped) ) (pop 'L) ) (NIL Swapped Lst) (off Swapped) (loop (setq L (prior L Lst)) # Not recommended (inefficient) (when (> (car L) (cadr L)) (xchg L (cdr L)) (on Swapped) ) (T (== Lst L)) ) (NIL Swapped Lst) ) ) )
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Julia
Julia
  socket = connect("localhost",256) write(socket, "hello socket world") close(socket)  
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Kotlin
Kotlin
// version 1.2.21   import java.net.Socket   fun main(args: Array<String>) { val sock = Socket("localhost", 256) sock.use { it.outputStream.write("hello socket world".toByteArray()) } }
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also OEIS A019546: Primes whose digits are primes. https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
#Python
Python
  def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs))     def is_prime(n): return len(divisors(n)) == 2     def digit_check(n): if len(str(n))<2: return True else: for digit in str(n): if not is_prime(int(digit)): return False return True     def sequence(max_n=None): ii = 0 n = 0 while True: ii += 1 if is_prime(ii): if max_n is not None: if n>max_n: break if digit_check(ii): n += 1 yield ii     if __name__ == '__main__': generator = sequence(100) for index, item in zip(range(1, 16), generator): print(index, item) for index, item in zip(range(16, 100), generator): pass print(100, generator.__next__())  
http://rosettacode.org/wiki/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Snake is a game where the player maneuvers a line which grows in length every time the snake reaches a food source. Task Implement a variant of the Snake game, in any interactive environment, in which a sole player attempts to eat items by running into them with the head of the snake. Each item eaten makes the snake longer and a new item is randomly generated somewhere else on the plane. The game ends when the snake attempts to eat himself.
#J
J
require'ide/qt/gl2' coinsert 'jgl2'   open=: wd@{{)n pc s closeok; cc n isidraw; set n wh 400 400; pshow; }}   start=: {{ speed=: {.y,200 open'' snake=: 10 10,10 11,:10 12 newdot'' draw'' }}   newdot=: {{ dot=: ({~ ?@#) snake -.~ ,/(#: i.)40 40 }}   s_n_char=: {{ select. {.toupper sysdata case. 'W' do. move 0 _1 case. 'A' do. move _1 0 case. 'S' do. move 0 1 case. 'D' do. move 1 0 end. }}   move=: {{ s_timer=: move@y wd 'ptimer ',":speed head=. y+{.snake if. head e. snake do. head gameover'' return. end. if. _1 e. head do. (0>.head) gameover'' return. end. if. 1 e. 40 <: head do. (39<.head) gameover'' return. end. if. dot -: head do. snake=: dot,snake newdot'' else. snake=: head,}: snake end. draw'' }}   draw=: {{ glclear'' glbrush glrgb 0 0 255 glrect 10*}.snake,"1(1 1) glbrush glrgb 0 255 0 glrect 10*({.snake),1 1 glbrush glrgb 255 0 0 glrect 10*dot,1 1 glpaint'' EMPTY }}   gameover=: {{ wd 'ptimer 0' if. 1<#snake do. echo 'game over' echo 'score: ',":(#snake)*1000%speed draw'' glbrush glrgb 255 255 0 glrect 10*x,1 1 end. snake=: ,:_ _ }}