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/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.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols binary   import java.util.List   i1 = ArrayList(Arrays.asList([Integer(3), Integer(3), Integer(1), Integer(2), Integer(4), Integer(3), Integer(5), Integer(6)])) say i1.toString say gnomeSort(i1).toString   return   method isTrue public constant binary returns boolean return 1 == 1   method isFalse public constant binary returns boolean return \isTrue   method gnomeSort(a = String[], sAsc = isTrue) public constant binary returns String[]   rl = String[a.length] al = List gnomeSort(Arrays.asList(a), sAsc) al.toArray(rl)   return rl   method gnomeSort(a = List, sAsc = isTrue) public constant binary returns ArrayList   sDsc = \sAsc -- Ascending/descending switches ra = ArrayList(a) i_ = 1 j_ = 2 loop label i_ while i_ < ra.size ctx = (Comparable ra.get(i_ - 1)).compareTo(Comparable ra.get(i_)) if (sAsc & ctx <= 0) | (sDsc & ctx >= 0) then do i_ = j_ j_ = j_ + 1 end else do swap = ra.get(i_) ra.set(i_, ra.get(i_ - 1)) ra.set(i_ - 1, swap) i_ = i_ - 1 if i_ = 0 then do i_ = j_ j_ = j_ + 1 end end end i_   return ra  
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead 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 Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Standard_ML
Standard ML
fun columns l = case List.filter (not o null) l of [] => [] | l => map hd l :: columns (map tl l)   fun replicate (n, x) = List.tabulate (n, fn _ => x)   fun bead_sort l = map length (columns (columns (map (fn e => replicate (e, 1)) l)))
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead 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 Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Tcl
Tcl
package require Tcl 8.5   proc beadsort numList { # Special case: empty list is empty when sorted. if {![llength $numList]} return # Set up the abacus... foreach n $numList { for {set i 0} {$i<$n} {incr i} { dict incr vals $i } } # Make the beads fall... foreach n [dict values $vals] { for {set i 0} {$i<$n} {incr i} { dict incr result $i } } # And the result is... dict values $result }   # Demonstration code puts [beadsort {5 3 1 7 4 1 1}]
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
#M2000_Interpreter
M2000 Interpreter
  Module cocktailSort { k=(3,2,1) print k cocktailSort(k) print k k=("c","b","a") print k cocktailSortString(k) print k Dim a(5) a(0)=1,2,5,6,3 print a() cocktailSort(a()) print a() End Sub cocktailSort(a) \\ this is like Link a to a() but using new for a() - shadow any a() push &a : read new &a() local swapped, lenA2=len(a)-2 do for i=0 to lenA2 if a(i) > a(i+1) then swap a(i), a(i+1): swapped = true next if swapped then swapped~ for i=lenA2 to 0 if a(i) > a(i+1) then swap a(i), a(i+1): swapped = true next end if until not swapped End Sub Sub cocktailSortString(a) push &a : read new &a$() local swapped, lenA2=len(a)-2 do for i=0 to lenA2 if a$(i) > a$(i+1) then swap a$(i), a$(i+1) swapped = true end if next if swapped then swapped~ for i=lenA2 to 0 if a$(i) > a$(i+1) then swap a$(i), a$(i+1) swapped = true end if next end if until not swapped   End Sub } cocktailSort  
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.
#11l
11l
[String] data V nrows = 0 V px = 0 V py = 0 V sdata = ‘’ V ddata = ‘’   F init(board)  :data = board.split("\n")  :nrows = max(:data.map(r -> r.len))   V maps = [‘ ’ = ‘ ’, ‘.’ = ‘.’, ‘@’ = ‘ ’, ‘#’ = ‘#’, ‘$’ = ‘ ’] V mapd = [‘ ’ = ‘ ’, ‘.’ = ‘ ’, ‘@’ = ‘@’, ‘#’ = ‘ ’, ‘$’ = ‘*’]   L(row) :data V r = L.index L(ch) row V c = L.index  :sdata ‘’= maps[ch]  :ddata ‘’= mapd[ch] I ch == ‘@’  :px = c  :py = r   F push(x, y, dx, dy, &data) I :sdata[(y + 2 * dy) * :nrows + x + 2 * dx] == ‘#’ | data[(y + 2 * dy) * :nrows + x + 2 * dx] != ‘ ’ data = ‘’ R   data[y * :nrows + x] = ‘ ’ data[(y + dy) * :nrows + x + dx] = ‘@’ data[(y + 2 * dy) * :nrows + x + 2 * dx] = ‘*’   F is_solved(data) L(i) 0 .< data.len I (:sdata[i] == ‘.’) != (data[i] == ‘*’) R 0B R 1B   F solve() V open = Deque([(:ddata, ‘’, :px, :py)]) V visited = Set([:ddata]) V dirs = ((0, -1, ‘u’, ‘U’), ( 1, 0, ‘r’, ‘R’), (0, 1, ‘d’, ‘D’), (-1, 0, ‘l’, ‘L’))   L !open.empty V (cur, csol, x, y) = open.pop_left()   L(di) dirs V temp = copy(cur) V (dx, dy) = (di[0], di[1])   I temp[(y + dy) * :nrows + x + dx] == ‘*’ push(x, y, dx, dy, &temp) I temp != ‘’ & temp !C visited I is_solved(temp) R csol‘’di[3] open.append((temp, csol‘’di[3], x + dx, y + dy)) visited.add(temp) E I :sdata[(y + dy) * :nrows + x + dx] == ‘#’ | temp[(y + dy) * :nrows + x + dx] != ‘ ’ L.continue   temp[y * :nrows + x] = ‘ ’ temp[(y + dy) * :nrows + x + dx] = ‘@’   I temp !C visited I is_solved(temp) R csol‘’di[2] open.append((temp, csol‘’di[2], x + dx, y + dy)) visited.add(temp)   R ‘No solution’   V level = |‘####### # # # # #. # # #. $$ # #.$$ # #.# @# #######’   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
#D
D
import std.stdio, std.conv, std.string, std.range, std.algorithm, std.typecons, std.typetuple;     struct HolyKnightPuzzle { private alias InputCellBaseType = char; private enum InputCell : InputCellBaseType { available = '#', unavailable = '.', start='1' } private alias Cell = uint; private enum : Cell { unknownCell = 0, unavailableCell = Cell.max, startCell=1 } // Special Cell values.   // Neighbors, [shift row, shift column]. static struct P { int x, y; } alias shifts = TypeTuple!(P(-2, -1), P(2, -1), P(-2, 1), P(2, 1), P(-1, -2), P(1, -2), P(-1, 2), P(1, 2));   immutable size_t gridWidth, gridHeight; private immutable Cell nAvailableCells; private /*immutable*/ const InputCell[] flatPuzzle; private Cell[] grid; // Flattened mutable game grid.   @disable this();     this(in string[] rawPuzzle) pure @safe in { assert(!rawPuzzle.empty); assert(!rawPuzzle[0].empty); assert(rawPuzzle.all!(row => row.length == rawPuzzle[0].length)); // Is rectangular. assert(rawPuzzle.join.count(InputCell.start) == 1); // Exactly one start point. } body { //immutable puzzle = rawPuzzle.to!(InputCell[][]); immutable puzzle = rawPuzzle.map!representation.array.to!(InputCell[][]);   gridWidth = puzzle[0].length; gridHeight = puzzle.length; flatPuzzle = puzzle.join;   // This counts the start cell too. nAvailableCells = flatPuzzle.representation.count!(ic => ic != InputCell.unavailable);   grid = flatPuzzle .map!(ic => ic.predSwitch(InputCell.available, unknownCell, InputCell.unavailable, unavailableCell, InputCell.start, startCell)) .array; }     Nullable!(string[][]) solve(size_t width)() pure /*nothrow*/ @safe out(result) { if (!result.isNull) assert(!grid.canFind(unknownCell)); } body { assert(width == gridWidth);   // Find start position. foreach (immutable r; 0 .. gridHeight) foreach (immutable c; 0 .. width) if (grid[r * width + c] == startCell && search!width(r, c, startCell + 1)) { auto result = zip(flatPuzzle, grid) // Not nothrow. //.map!({p, c} => ... .map!(pc => (pc[0] == InputCell.available) ? pc[1].text : InputCellBaseType(pc[0]).text) .array .chunks(width) .array; return typeof(return)(result); }   return typeof(return)(); }     private bool search(size_t width)(in size_t r, in size_t c, in Cell cell) pure nothrow @safe @nogc { if (cell > nAvailableCells) return true; // One solution found.   // This doesn't use the Warnsdorff rule. foreach (immutable sh; shifts) { immutable r2 = r + sh.x, c2 = c + sh.y, pos = r2 * width + c2; // No need to test for >= 0 because uint wraps around. if (c2 < width && r2 < gridHeight && grid[pos] == unknownCell) { grid[pos] = cell; // Try. if (search!width(r2, c2, cell + 1)) return true; grid[pos] = unknownCell; // Restore. } }   return false; } }     void main() @safe { // Enum HolyKnightPuzzle to catch malformed puzzles at compile-time. enum puzzle1 = ".###.... .#.##... .####### ###..#.# #.#..### 1######. ..##.#.. ...###..".split.HolyKnightPuzzle;   enum puzzle2 = ".....1.#..... .....#.#..... ....#####.... .....###..... ..#..#.#..#.. #####...##### ..##.....##.. #####...##### ..#..#.#..#.. .....###..... ....#####.... .....#.#..... .....#.#.....".split.HolyKnightPuzzle;   foreach (/*enum*/ puzzle; TypeTuple!(puzzle1, puzzle2)) { //immutable solution = puzzle.solve!(puzzle.gridWidth); enum width = puzzle.gridWidth; immutable solution = puzzle.solve!width; // Solved at run-time. if (solution.isNull) writeln("No solution found for puzzle.\n"); else writefln("One solution:\n%(%-(%2s %)\n%)\n", solution); } }
http://rosettacode.org/wiki/SOAP
SOAP
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
#Clojure
Clojure
(require '[clj-soap.core :as soap])   (let [client (soap/client-fn "http://example.com/soap/wsdl")] (client :soapFunc) (client :anotherSoapFunc))
http://rosettacode.org/wiki/SOAP
SOAP
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
#ColdFusion
ColdFusion
<cfset client = createObject("webservice","http://example.com/soap/wsdl")> <cfset result = client.soapFunc("hello")> <cfset result = client.anotherSoapFunc(34234)>
http://rosettacode.org/wiki/SOAP
SOAP
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
#Diego
Diego
apt_knowledge(webservices); // Commanding apt_protocol(SOAP); will also apt_knowledge(webservices);   set_namespace(rosettacode);   add_webserv(ws)_protocol(SOAP)_wdsl(http://example.com/soap/wsdl)_me(); invoke_webserv(ws)_soapFunc(hello)_msg()_result()_me(); me_msg()_invoke(ws)_anotherSoapFunc(32234); // alternative syntax   reset_namespace();
http://rosettacode.org/wiki/Solve_a_Hopido_puzzle
Solve a Hopido puzzle
Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following: "Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7×7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!" Knowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds. Example: . 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 . . . Extra credits are available for other interesting designs. 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 Numbrix puzzle Solve the no connection puzzle
#Julia
Julia
using .Hidato # Note that the . here means to look locally for the module rather than in the libraries   const hopid = """ . 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 . . . """   const hopidomoves = [[-3, 0], [0, -3], [-2, -2], [-2, 2], [2, -2], [0, 3], [3, 0], [2, 2]]   board, maxmoves, fixed, starts = hidatoconfigure(hopid) printboard(board, " 0", " ") hidatosolve(board, maxmoves, hopidomoves, fixed, starts[1][1], starts[1][2], 1) printboard(board)  
http://rosettacode.org/wiki/Solve_a_Hopido_puzzle
Solve a Hopido puzzle
Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following: "Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7×7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!" Knowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds. Example: . 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 . . . Extra credits are available for other interesting designs. 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 Numbrix puzzle Solve the no connection puzzle
#Kotlin
Kotlin
// version 1.2.0   val board = listOf( ".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0..." )   val moves = listOf( -3 to 0, 0 to 3, 3 to 0, 0 to -3, 2 to 2, 2 to -2, -2 to 2, -2 to -2 )   lateinit var grid: List<IntArray> var totalToFill = 0   fun solve(r: Int, c: Int, count: Int): Boolean { if (count > totalToFill) return true val nbrs = neighbors(r, c) if (nbrs.isEmpty() && count != totalToFill) return false nbrs.sortBy { it[2] } for (nb in nbrs) { val rr = nb[0] val cc = nb[1] grid[rr][cc] = count if (solve(rr, cc, count + 1)) return true grid[rr][cc] = 0 } return false }   fun neighbors(r: Int, c: Int): MutableList<IntArray> { val nbrs = mutableListOf<IntArray>() for (m in moves) { val x = m.first val y = m.second if (grid[r + y][c + x] == 0) { val num = countNeighbors(r + y, c + x) - 1 nbrs.add(intArrayOf(r + y, c + x, num)) } } return nbrs }   fun countNeighbors(r: Int, c: Int): Int { var num = 0 for (m in moves) if (grid[r + m.second][c + m.first] == 0) num++ return num }   fun printResult() { for (row in grid) { for (i in row) { print(if (i == -1) " " else "%2d ".format(i)) } println() } }   fun main(args: Array<String>) { val nRows = board.size + 6 val nCols = board[0].length + 6 grid = List(nRows) { IntArray(nCols) { -1} } for (r in 0 until nRows) { for (c in 3 until nCols - 3) { if (r in 3 until nRows - 3) { if (board[r - 3][c - 3] == '0') { grid[r][c] = 0 totalToFill++ } } } } var pos = -1 var rr: Int var cc: Int do { do { pos++ rr = pos / nCols cc = pos % nCols } while (grid[rr][cc] == -1)   grid[rr][cc] = 1 if (solve(rr, cc, 2)) break grid[rr][cc] = 0 } while (pos < nRows * nCols)   printResult() }
http://rosettacode.org/wiki/Smallest_number_k_such_that_k%2B2%5Em_is_composite_for_all_m_less_than_k
Smallest number k such that k+2^m is composite for all m less than k
Generate the sequence of numbers a(k), where each k is the smallest positive integer such that k + 2m is composite for every positive integer m less than k. For example Suppose k == 7; test m == 1 through m == 6. If any are prime, the test fails. Is 7 + 21 (9) prime? False Is 7 + 22 (11) prime? True So 7 is not an element of this sequence. It is only necessary to test odd natural numbers k. An even number, plus any positive integer power of 2 is always composite. Task Find and display, here on this page, the first 5 elements of this sequence. See also OEIS:A033939 - Odd k for which k+2^m is composite for all m < k
#Julia
Julia
using Lazy using Primes   a(k) = all(m -> !isprime(k + big"2"^m), 1:k-1)   A033939 = @>> Lazy.range(2) filter(isodd) filter(a)   println(take(5, A033939)) # List: (773 2131 2491 4471 5101)  
http://rosettacode.org/wiki/Smallest_number_k_such_that_k%2B2%5Em_is_composite_for_all_m_less_than_k
Smallest number k such that k+2^m is composite for all m less than k
Generate the sequence of numbers a(k), where each k is the smallest positive integer such that k + 2m is composite for every positive integer m less than k. For example Suppose k == 7; test m == 1 through m == 6. If any are prime, the test fails. Is 7 + 21 (9) prime? False Is 7 + 22 (11) prime? True So 7 is not an element of this sequence. It is only necessary to test odd natural numbers k. An even number, plus any positive integer power of 2 is always composite. Task Find and display, here on this page, the first 5 elements of this sequence. See also OEIS:A033939 - Odd k for which k+2^m is composite for all m < k
#Perl
Perl
use strict; use warnings; use bigint; use ntheory 'is_prime';   my $cnt; LOOP: for my $k (2..1e10) { next unless 1 == $k % 2; for my $m (1..$k-1) { next LOOP if is_prime $k + (1<<$m) } print "$k "; last if ++$cnt == 5; }
http://rosettacode.org/wiki/Smallest_number_k_such_that_k%2B2%5Em_is_composite_for_all_m_less_than_k
Smallest number k such that k+2^m is composite for all m less than k
Generate the sequence of numbers a(k), where each k is the smallest positive integer such that k + 2m is composite for every positive integer m less than k. For example Suppose k == 7; test m == 1 through m == 6. If any are prime, the test fails. Is 7 + 21 (9) prime? False Is 7 + 22 (11) prime? True So 7 is not an element of this sequence. It is only necessary to test odd natural numbers k. An even number, plus any positive integer power of 2 is always composite. Task Find and display, here on this page, the first 5 elements of this sequence. See also OEIS:A033939 - Odd k for which k+2^m is composite for all m < k
#Phix
Phix
with javascript_semantics atom t0 = time() include mpfr.e mpz z = mpz_init() function a(integer k) if k=1 then return false end if for m=1 to k-1 do mpz_ui_pow_ui(z,2,m) mpz_add_si(z,z,k) if mpz_prime(z) then return false end if end for return true end function integer k = 1, count = 0 while count<5 do if a(k) then printf(1,"%d ",k) count += 1 end if k += 2 end while printf(1,"\n") ?elapsed(time()-t0)
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.
#C.23
C#
using System; using System.Collections.Generic; using System.Linq;   class Program { struct Entry { public Entry(string name, double value) { Name = name; Value = value; } public string Name; public double Value; }   static void Main(string[] args) { var Elements = new List<Entry> { new Entry("Krypton", 83.798), new Entry("Beryllium", 9.012182), new Entry("Silicon", 28.0855), new Entry("Cobalt", 58.933195), new Entry("Selenium", 78.96), new Entry("Germanium", 72.64) };   var sortedElements = Elements.OrderBy(e => e.Name);   foreach (Entry e in sortedElements) Console.WriteLine("{0,-11}{1}", e.Name, e.Value); } }
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting 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 Counting 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) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Rust
Rust
fn counting_sort( mut data: Vec<usize>, min: usize, max: usize, ) -> Vec<usize> { // create and fill counting bucket with 0 let mut count: Vec<usize> = Vec::with_capacity(data.len()); count.resize(data.len(), 0);   for num in &data { count[num - min] = count[num - min] + 1; } let mut z: usize = 0; for i in min..max+1 { while count[i - min] > 0 { data[z] = i; z += 1; count[i - min] = count[i - min] - 1; } }   data }   fn main() { let arr1 = vec![1, 0, 2, 9, 3, 8, 4, 7, 5, 6]; println!("{:?}", counting_sort(arr1, 0, 9));   let arr2 = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; println!("{:?}", counting_sort(arr2, 0, 9));   let arr3 = vec![10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; println!("{:?}", counting_sort(arr3, 0, 10)); }
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting 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 Counting 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) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Scala
Scala
def countSort(input: List[Int], min: Int, max: Int): List[Int] = input.foldLeft(Array.fill(max - min + 1)(0)) { (arr, n) => arr(n - min) += 1 arr }.zipWithIndex.foldLeft(List[Int]()) { case (lst, (cnt, ndx)) => List.fill(cnt)(ndx + min) ::: lst }.reverse
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).
#Elixir
Elixir
# It solved if connected A and B, connected G and H (according to the video).   # require HLPsolver   adjacent = for i <- -2..2, j <- -2..2, not(i in -1..1 and j in -1..1), do: {i,j} layout = ~S""" A - B /|\ /|\ / | X | \ / |/ \| \ C - D - E - F \ |\ /| / \ | X | / \|/ \|/ G - H """ board = """ . 0 0 . 0 1 0 0 . 0 0 . """ HLPsolver.solve(board, adjacent, false) |> Enum.sort |> Enum.map(fn {_,cell} -> cell.value end) |> Enum.zip(~w[A B C D E F G H]) |> Enum.reduce(layout, fn {n,c},acc -> String.replace(acc, c, to_string(n)) end) |> IO.puts
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).
#Factor
Factor
USING: assocs interpolate io kernel math math.combinatorics math.ranges math.parser multiline pair-rocket sequences sequences.generalizations ;   STRING: diagram ${} ${} /|\ /|\ / | X | \ / |/ \| \ ${} - ${} - ${} - ${} \ |\ /| / \ | X | / \|/ \|/ ${} ${} ;   CONSTANT: adjacency H{ 0 => { 2 3 4 } 1 => { 3 4 5 } 2 => { 0 3 6 } 3 => { 0 1 2 4 6 7 } 4 => { 0 1 3 5 6 7 } 5 => { 1 4 7 } 6 => { 2 3 4 } 7 => { 3 4 5 } }   : any-consecutive? ( seq n -- ? ) [ - abs 1 = ] curry any? ;   : neighbors ( elt seq i -- seq elt ) adjacency at swap nths swap ;   : solution? ( permutation-seq -- ? ) dup [ neighbors any-consecutive? ] with find-index nip not ;   : find-solution ( -- seq ) 8 [1,b] [ solution? ] find-permutation ;   : display-solution ( seq -- ) [ number>string ] map 8 firstn diagram interpolate>string print ;   : main ( -- ) find-solution display-solution ;   MAIN: main
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Example 1 Problem. 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 Solution. 49 50 51 52 53 54 75 76 81 48 47 46 45 44 55 74 77 80 37 38 39 40 43 56 73 78 79 36 35 34 41 42 57 72 71 70 31 32 33 14 13 58 59 68 69 30 17 16 15 12 61 60 67 66 29 18 19 20 11 62 63 64 65 28 25 24 21 10 1 2 3 4 27 26 23 22 9 8 7 6 5 Example 2 Problem. 0 0 0 0 0 0 0 0 0 0 11 12 15 18 21 62 61 0 0 6 0 0 0 0 0 60 0 0 33 0 0 0 0 0 57 0 0 32 0 0 0 0 0 56 0 0 37 0 1 0 0 0 73 0 0 38 0 0 0 0 0 72 0 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0 Solution. 9 10 13 14 19 20 63 64 65 8 11 12 15 18 21 62 61 66 7 6 5 16 17 22 59 60 67 34 33 4 3 24 23 58 57 68 35 32 31 2 25 54 55 56 69 36 37 30 1 26 53 74 73 70 39 38 29 28 27 52 75 72 71 40 43 44 47 48 51 76 77 78 41 42 45 46 49 50 81 80 79 Task Write a program to solve puzzles of this ilk, demonstrating your program by solving the above examples. Extra credit for other interesting examples. 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 the no connection puzzle
#Phix
Phix
with javascript_semantics sequence board, knownx, knowny integer size, limit, nchars, tries string fmt, blank constant ROW = 1, COL = 2 constant moves = {{-1,0},{0,-1},{0,1},{1,0}} function onboard(integer row, integer col) return row>=1 and row<=size and col>=nchars and col<=nchars*size end function function solve(integer row, integer col, integer n) integer nrow, ncol tries+= 1 if n>limit then return 1 end if if knownx[n] then for move=1 to length(moves) do nrow = row+moves[move][ROW] ncol = col+moves[move][COL]*nchars if nrow = knownx[n] and ncol = knowny[n] then if solve(nrow,ncol,n+1) then return 1 end if exit end if end for return 0 end if sequence wmoves = {} 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 board[nrow][ncol-nchars+1..ncol] = sprintf(fmt,n) if solve(nrow,ncol,n+1) then return 1 end if board[nrow][ncol-nchars+1..ncol] = blank end if end for return 0 end function procedure Numbrix(sequence s) integer y, ch, ch2, k atom t0 = time() s = split(s,'\n') size = length(s) limit = size*size nchars = length(sprintf(" %d",limit)) fmt = sprintf(" %%%dd",nchars-1) blank = repeat('.',nchars) board = repeat(repeat(' ',size*nchars),size) knownx = repeat(0,limit) knowny = repeat(0,limit) for x=1 to size do for y=nchars to size*nchars by nchars do ch = s[x][y] if ch!='.' then k = ch-'0' ch2 = s[x][y-1] if ch2!=' ' then k += (ch2-'0')*10 board[x][y-1] = ch2 end if knownx[k] = x knowny[k] = y end if board[x][y] = ch end for end for tries = 0 if solve(knownx[1],knowny[1],2) then puts(1,join(board,"\n")) printf(1,"\nsolution found in %d tries (%3.2fs)\n",{tries,time()-t0}) else puts(1,"no solutions found\n") end if end procedure constant board1 = """ . . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17 . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .""" Numbrix(board1) constant board2 = """ . . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37 . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .""" Numbrix(board2)
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.
#COBOL
COBOL
PROGRAM-ID. sort-ints.   DATA DIVISION. WORKING-STORAGE SECTION. 01 array-area VALUE "54321". 03 array PIC 9 OCCURS 5 TIMES. 01 i PIC 9.   PROCEDURE DIVISION. main-line. PERFORM display-array SORT array ASCENDING array PERFORM display-array   GOBACK . display-array. PERFORM VARYING i FROM 1 BY 1 UNTIL 5 < i DISPLAY array (i) " " NO ADVANCING END-PERFORM DISPLAY SPACE .
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.
#Common_Lisp
Common Lisp
CL-USER> (sort #(9 -2 1 2 8 0 1 2) #'<) #(-2 0 1 1 2 2 8 9)
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
#jq
jq
def data: [ "1.3.6.1.4.1.11.2.17.19.3.4.0.10", "1.3.6.1.4.1.11.2.17.5.2.0.79", "1.3.6.1.4.1.11.2.17.19.3.4.0.4", "1.3.6.1.4.1.11150.3.4.0.1", "1.3.6.1.4.1.11.2.17.19.3.4.0.1", "1.3.6.1.4.1.11150.3.4.0" ];   data | map( split(".") | map(tonumber) ) | sort | map(join("."))
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
#Julia
Julia
oidlist = ["1.3.6.1.4.1.11.2.17.19.3.4.0.10", "1.3.6.1.4.1.11.2.17.5.2.0.79", "1.3.6.1.4.1.11.2.17.19.3.4.0.4", "1.3.6.1.4.1.11150.3.4.0.1", "1.3.6.1.4.1.11.2.17.19.3.4.0.1", "1.3.6.1.4.1.11150.3.4.0"]   sort!(oidlist; lt=lexless, by=x -> parse.(Int, String.(split(x, ".")))) println.(oidlist)
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
#Go
Go
package main   import ( "fmt" "sort" )   func main() { // givens values := []int{7, 6, 5, 4, 3, 2, 1, 0} indices := map[int]int{6: 0, 1: 0, 7: 0}   orderedValues := make([]int, len(indices)) orderedIndices := make([]int, len(indices)) i := 0 for j := range indices { // validate that indices are within list boundaries if j < 0 || j >= len(values) { fmt.Println("Invalid index: ", j) return } // extract elements to sort orderedValues[i] = values[j] orderedIndices[i] = j i++ } // sort sort.Ints(orderedValues) sort.Ints(orderedIndices)   fmt.Println("initial:", values) // replace sorted values for i, v := range orderedValues { values[orderedIndices[i]] = v } fmt.Println("sorted: ", values) }
http://rosettacode.org/wiki/Sort_stability
Sort stability
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 When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#REXX
REXX
/*REXX program sorts a (stemmed) array using a (stable) bubble─sort algorithm. */ call gen@ /*generate the array elements (strings)*/ call show 'before sort' /*show the before array elements. */ say copies('▒', 50) /*show a separator line between shows. */ call bubbleSort # /*invoke the bubble sort. */ call show ' after sort' /*show the after array elements. */ exit 0 /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ bubbleSort: procedure expose @.; parse arg n; m= n-1 /*N: number of array elements. */ do m=m for m by -1 until ok; ok= 1 /*keep sorting array until done.*/ do j=1 for m; k= j+1; if @.j<[email protected] then iterate /*Not out─of─order?*/ _= @.j; @.j= @.k; @.k= _ ok= 0 /*swap 2 elements; flag as ¬done*/ end /*j*/ end /*m*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ gen@: @.=; @.1 = 'UK London' @.2 = 'US New York' @.3 = 'US Birmingham' @.4 = 'UK Birmingham' do #=1 while @.#\=='' /*determine how many entries in list. */ end /*#*/; #= # - 1; return /*adjust for the DO loop index; return*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ show: do j=1 for #; say ' element' right(j,length(#)) arg(1)":" @.j; end; return
http://rosettacode.org/wiki/Sort_stability
Sort stability
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 When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#Ring
Ring
  aList = [["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]] see sort(aList,2)  
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.
#Phix
Phix
with javascript_semantics object {x,y,z} = {"lions, tigers, and","bears, oh my","(from the \"Wizard of OZ\")"} ?{x,y,z} {x,y,z} = sort({x,y,z}) ?{x,y,z} {x,y,z} = {77444,-12,0} ?{x,y,z} {x,y,z} = sort({x,y,z}) ?{x,y,z}
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.
#PHP
PHP
<?php //Sort strings $x = 'lions, tigers, and'; $y = 'bears, oh my!'; $z = '(from the "Wizard of OZ")'; $items = [$x, $y, $z]; sort($items);   list($x, $y, $z) = $items;   echo <<<EOT Case 1: x = $x y = $y z = $z   EOT;   //Sort numbers $x = 77444; $y = -12; $z = 0; $items = [$x, $y, $z]; sort($items);   list($x, $y, $z) = $items;   echo <<<EOT Case 2: x = $x y = $y z = $z   EOT;    
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.
#Kotlin
Kotlin
import java.util.Arrays   fun main(args: Array<String>) { val strings = arrayOf("Here", "are", "some", "sample", "strings", "to", "be", "sorted")   fun printArray(message: String, array: Array<String>) = with(array) { print("$message [") forEachIndexed { index, string -> print(if (index == lastIndex) string else "$string, ") } println("]") }   printArray("Unsorted:", strings)   Arrays.sort(strings) { first, second -> val lengthDifference = second.length - first.length if (lengthDifference == 0) first.lowercase().compareTo(second.lowercase(), true) else lengthDifference }   printArray("Sorted:", strings) }
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.
#Lua
Lua
test = { "Here", "we", "have", "some", "sample", "strings", "to", "be", "sorted" }   function stringSorter(a, b) if string.len(a) == string.len(b) then return string.lower(a) < string.lower(b) end return string.len(a) > string.len(b) end table.sort(test, stringSorter)   -- print sorted table for k,v in pairs(test) do print(v) end
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#TI-83_BASIC
TI-83 BASIC
:L1→L2 :dim(L2)→A :While A>5 and B=0 :int(A/1.3)→A :1→C :0→B :While (C+A)≥dim(L2) :If L2(C)>L2(C+A) :Then :L2(C)→D :L2(C+A)→L2(C) :D→L2(C+A) :1→B :End :C+1→C :End :DelVar A :DelVar B :DelVar C :DelVar D :L1→L3 :L2→L1 :prgmSORTINS :L3→L1 :DelVar L3 :Return
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.
#REXX
REXX
/*REXX program performs a type of bogo sort on numbers in an array. */ parse arg list /*obtain optional list from C.L. */ if list='' then list=-21 333 0 444.4 /*Not defined? Then use default.*/ #=words(list) /*the number of numbers in list. */ do i=1 for words(list); @.i=word(list,i); end /*create an array.*/ call tell 'before bogo sort'   do bogo=1   do j=1 for #-1; jp=j+1 /* [↓] compare a # with the next*/ if @.jp>[email protected] then iterate /*so far, so good; keep looking.*/ /*get 2 unique random #s for swap*/ do until a\==b; a=random(1, #); b=random(1, #); end   parse value @.a @.b with @.b @.a /*swap 2 random numbers in array.*/ iterate bogo /*go and try another bogo sort. */ end /*j*/   leave /*we're finished with bogo sort. */ end /*bogo*/ /* [↓] show the # of bogo sorts.*/   say 'number of bogo sorts performed =' bogo call tell ' after bogo sort' exit /*stick a fork in it, we're done.*/ /*──────────────────────────────────TELL subroutine─────────────────────*/ tell: say; say center(arg(1), 50, '─') do t=1 for # say arg(1) 'element'right(t, length(#))'='right(@.t, 18) end /*t*/ say return
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.
#Elena
Elena
import system'routines; import extensions;   extension op { bubbleSort() { var list := self.clone();   bool madeChanges := true; int itemCount := list.Length; while (madeChanges) { madeChanges := false; itemCount -= 1; for(int i := 0, i < itemCount, i += 1) { if (list[i] > list[i + 1]) { list.exchange(i,i+1); madeChanges := true } } };   ^ list } }   public program() { var list := new int[]{3, 7, 3, 2, 1, -4, 10, 12, 4}; console.printLine(list.bubbleSort().asEnumerable()) }
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.
#Nim
Nim
proc gnomeSort[T](a: var openarray[T]) = var n = a.len i = 1 j = 2 while i < n: if a[i-1] > a[i]: swap a[i-1], a[i] dec i if i > 0: continue i = j inc j   var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782] gnomeSort a echo a
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead 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 Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#VBA
VBA
Option Base 1   Private Function sq_add(arr As Variant, x As Double) As Variant Dim res() As Variant ReDim res(UBound(arr)) For i = 1 To UBound(arr) res(i) = arr(i) + x Next i sq_add = res End Function   Private Function beadsort(ByVal a As Variant) As Variant Dim poles() As Variant ReDim poles(WorksheetFunction.Max(a)) For i = 1 To UBound(a) For j = 1 To a(i) poles(j) = poles(j) + 1 Next j Next i For j = 1 To UBound(a) a(j) = 0 Next j For i = 1 To UBound(poles) For j = 1 To poles(i) a(j) = a(j) + 1 Next j Next i beadsort = a End Function   Public Sub main() Debug.Print Join(beadsort([{5, 3, 1, 7, 4, 1, 1, 20}]), ", ") End Sub
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead 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 Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#Wren
Wren
var beadSort = Fn.new { |a| var res = [] var max = a.reduce { |acc, i| (i > acc) ? i : acc } var trans = [0] * max for (i in a) { for (n in 0...i) trans[n] = trans[n] + 1 } for (i in a) { res.add(trans.count { |n| n > 0 }) for (n in 0...trans.count) trans[n] = trans[n] - 1 } return res[-1..0] // return in ascending order }   var as = [ [4, 65, 2, 31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ] for (a in as) { System.print("Before: %(a)") a = beadSort.call(a) System.print("After : %(a)") System.print() }
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
#Maple
Maple
arr := Array([17,3,72,0,36,2,3,8,40,0]): len := numelems(arr): swap := proc(arr, a, b) local temp := arr[a]: arr[a] := arr[b]: arr[b] := temp: end proc: while(true) do swapped := false: for i to len-1 do if arr[i] > arr[i+1] then: swap(arr, i, i+1): swapped := true: end if: end do: if (not swapped) then break: end if: swapped := false: for j from len-1 to 1 by -1 do if arr[j] > arr[j+1] then swap(arr,j,j+1): swapped := true: end if: end do: if (not swapped) then break: end if: end do: arr;
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.
#Befunge
Befunge
  589*+0g"0"-25**689*+0g"0"-+50p v # Sokoban - (c) Matthew Westcott 2000 # 03 83*>10p99*2->:00p10gg"x"-#v_v p01g<> ## # # # # # # # # # # # # # # # # # # # << ^ -1g01_^#!: -1g00< > v # # # # # # # # # # # # # # # # # # # # # |-"8"_v#-"2":_v#-"6":_v#-"4":~< <0 # > 1 0>$1+2 0>$2+3%\0>$1+3%40v $4<# v -"0"gp04:-1+g<v:-1+g00p03:p < $p # >#v_"X">30g40gv0>40g10g+1-g:"#"-!|0 # 0>"x" ^v1g00p<^1g04p03:_v#`\ "9"<0 # v:g-2++<>0gg"X"-#v_"0">00 g10gp30g^ # 4# ^g04g04g0<>" " ^v3< # >8*-#v_$"o" v ^1-1+g0< >00g30g30v # # >"0"-#v_v> ^v01-2++g< # ^>#$" " 0#<v>"@"50g1-50p^>g40g40gv # v_^#!-"@"g-1+g04g01:-1+g03g00p-2++< # >"0"50g1+50p>\10g40g+1-p30g02050g |# >,#-:#3_@#"a\rx#glg#lw$Zhoo#Grqh$"0<# ##################################### ######## # # # o@0o # # # # o# ### ### #0 x 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
#Elixir
Elixir
# require HLPsolver   adjacent = [{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}]   """ . . 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 """ |> HLPsolver.solve(adjacent)   """ _ _ _ _ _ 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 """ |> HLPsolver.solve(adjacent)
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
#Go
Go
package main   import "fmt"   var moves = [][2]int{ {-1, -2}, {1, -2}, {-1, 2}, {1, 2}, {-2, -1}, {-2, 1}, {2, -1}, {2, 1}, }   var board1 = " xxx " + " x xx " + " xxxxxxx" + "xxx x x" + "x x xxx" + "sxxxxxx " + " xx x " + " xxx "   var board2 = ".....s.x....." + ".....x.x....." + "....xxxxx...." + ".....xxx....." + "..x..x.x..x.." + "xxxxx...xxxxx" + "..xx.....xx.." + "xxxxx...xxxxx" + "..x..x.x..x.." + ".....xxx....." + "....xxxxx...." + ".....x.x....." + ".....x.x....."   func solve(pz [][]int, sz, sx, sy, idx, cnt int) bool { if idx > cnt { return true } for i := 0; i < len(moves); i++ { x := sx + moves[i][0] y := sy + moves[i][1] if (x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0 { pz[x][y] = idx if solve(pz, sz, x, y, idx+1, cnt) { return true } pz[x][y] = 0 } } return false }   func findSolution(b string, sz int) { pz := make([][]int, sz) for i := 0; i < sz; i++ { pz[i] = make([]int, sz) for j := 0; j < sz; j++ { pz[i][j] = -1 } } var x, y, idx, cnt int for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { switch b[idx] { case 'x': pz[i][j] = 0 cnt++ case 's': pz[i][j] = 1 cnt++ x, y = i, j } idx++ } }   if solve(pz, sz, x, y, 2, cnt) { for j := 0; j < sz; j++ { for i := 0; i < sz; i++ { if pz[i][j] != -1 { fmt.Printf("%02d ", pz[i][j]) } else { fmt.Print("-- ") } } fmt.Println() } } else { fmt.Println("Cannot solve this puzzle!") } }   func main() { findSolution(board1, 8) fmt.Println() findSolution(board2, 13) }
http://rosettacode.org/wiki/SOAP
SOAP
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
#F.23
F#
open Microsoft.FSharp.Data.TypeProviders   type Wsdl = WsdlService<"http://example.com/soap/wsdl"> let result = Wsdl.soapFunc("hello") let result2 = Wsdl.anotherSoapFunc(34234)
http://rosettacode.org/wiki/SOAP
SOAP
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
#Go
Go
package main   import ( "fmt" "github.com/tiaguinho/gosoap" "log" )   type CheckVatResponse struct { CountryCode string `xml:"countryCode"` VatNumber string `xml:"vatNumber"` RequestDate string `xml:"requestDate"` Valid string `xml:"valid"` Name string `xml:"name"` Address string `xml:"address"` }   var ( rv CheckVatResponse )   func check(err error) { if err != nil { log.Fatal(err) } }   func main() { // create SOAP client soap, err := gosoap.SoapClient("http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl")   // map parameter names to values params := gosoap.Params{ "vatNumber": "6388047V", "countryCode": "IE", }   // call 'checkVat' function err = soap.Call("checkVat", params) check(err)   // unmarshal response to 'rv' err = soap.Unmarshal(&rv) check(err)   // print response fmt.Println("Country Code  : ", rv.CountryCode) fmt.Println("Vat Number  : ", rv.VatNumber) fmt.Println("Request Date  : ", rv.RequestDate) fmt.Println("Valid  : ", rv.Valid) fmt.Println("Name  : ", rv.Name) fmt.Println("Address  : ", rv.Address) }
http://rosettacode.org/wiki/Solve_a_Hopido_puzzle
Solve a Hopido puzzle
Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following: "Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7×7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!" Knowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds. Example: . 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 . . . Extra credits are available for other interesting designs. 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 Numbrix puzzle Solve the no connection puzzle
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
puzz = ".00.00.\n0000000\n0000000\n.00000.\n..000..\n...0..."; puzz //= StringSplit[#, "\n"] & /* Map[Characters]; puzz //= Transpose /* Map[Reverse]; pos = Position[puzz, "0", {2}]; moves = Select[Select[Tuples[pos, 2], MatchQ[EuclideanDistance @@ #, 2 Sqrt[2] | 3] &], OrderedQ]; g = Graph[UndirectedEdge @@@ moves]; ord = Most[FindShortestTour[g][[2]]]; Graphics[MapThread[Text, {Range[Length[ord]], VertexList[g][[ord]]}]]
http://rosettacode.org/wiki/Solve_a_Hopido_puzzle
Solve a Hopido puzzle
Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following: "Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7×7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!" Knowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds. Example: . 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 . . . Extra credits are available for other interesting designs. 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 Numbrix puzzle Solve the no connection puzzle
#Nim
Nim
import algorithm, sequtils, strformat   const Moves = [(-3, 0), (0, 3), ( 3, 0), ( 0, -3), ( 2, 2), (2, -2), (-2, 2), (-2, -2)]   type   Hopido = object grid: seq[seq[int]] nRows, nCols: int totalToFill : Natural   Neighbor = (int, int, int)     proc initHopido(board: openArray[string]): Hopido = result.nRows = board.len + 6 result.nCols = board[0].len + 6 result.grid = newSeqWith(result.nRows, repeat(-1, result.nCols))   for row in 0..board.high: for col in 0..board[0].high: if board[row][col] == '0': result.grid[row + 3][col + 3] = 0 inc result.totalToFill     proc countNeighbors(hopido: Hopido; row, col: Natural): int = for (x, y) in Moves: if hopido.grid[row + y][col + x] == 0: inc result     proc neighbors(hopido: Hopido; row, col: Natural): seq[Neighbor] = for (x, y) in Moves: if hopido.grid[row + y][col + x] == 0: let num = hopido.countNeighbors(row + y, col + x) - 1 result.add (row + y, col + x, num)     proc solve(hopido: var Hopido; row, col, count: Natural): bool =   if count > hopido.totalTofill: return true   var nbrs = hopido.neighbors(row, col) if nbrs.len == 0 and count != hopido.totalToFill: return false   nbrs.sort(proc(a, b: Neighbor): int = cmp(a[2], b[2]))   for (row, col, _) in nbrs: hopido.grid[row][col] = count if hopido.solve(row, col, count + 1): return true hopido.grid[row][col] = 0     proc findSolution(hopido: var Hopido) = var pos = -1 var row, col: Natural   while true: while true: inc pos row = pos div hopido.nCols col = pos mod hopido.nCols if hopido.grid[row][col] != -1: break hopido.grid[row][col] = 1 if hopido.solve(row, col, 2): break hopido.grid[row][col] = 0 if pos >= hopido.nRows * hopido.nCols: break     proc print(hopido: Hopido) = for row in hopido.grid: for val in row: stdout.write if val == -1: " " else: &"{val:2} " echo()     when isMainModule:   const Board = [".00.00.", "0000000", "0000000", ".00000.", "..000..", "...0..."]   var hopido = initHopido(Board) hopido.findSolution() hopido.print()
http://rosettacode.org/wiki/Smallest_number_k_such_that_k%2B2%5Em_is_composite_for_all_m_less_than_k
Smallest number k such that k+2^m is composite for all m less than k
Generate the sequence of numbers a(k), where each k is the smallest positive integer such that k + 2m is composite for every positive integer m less than k. For example Suppose k == 7; test m == 1 through m == 6. If any are prime, the test fails. Is 7 + 21 (9) prime? False Is 7 + 22 (11) prime? True So 7 is not an element of this sequence. It is only necessary to test odd natural numbers k. An even number, plus any positive integer power of 2 is always composite. Task Find and display, here on this page, the first 5 elements of this sequence. See also OEIS:A033939 - Odd k for which k+2^m is composite for all m < k
#Raku
Raku
put (1..∞).hyper(:250batch).map(* × 2 + 1).grep( -> $k { !(1 ..^ $k).first: ($k + 1 +< *).is-prime } )[^5]
http://rosettacode.org/wiki/Smallest_number_k_such_that_k%2B2%5Em_is_composite_for_all_m_less_than_k
Smallest number k such that k+2^m is composite for all m less than k
Generate the sequence of numbers a(k), where each k is the smallest positive integer such that k + 2m is composite for every positive integer m less than k. For example Suppose k == 7; test m == 1 through m == 6. If any are prime, the test fails. Is 7 + 21 (9) prime? False Is 7 + 22 (11) prime? True So 7 is not an element of this sequence. It is only necessary to test odd natural numbers k. An even number, plus any positive integer power of 2 is always composite. Task Find and display, here on this page, the first 5 elements of this sequence. See also OEIS:A033939 - Odd k for which k+2^m is composite for all m < k
#Wren
Wren
import "./gmp" for Mpz   // returns true if k is a sequence member, false otherwise var a = Fn.new { |k| if (k == 1) return false for (m in 1...k) { var n = Mpz.one.lsh(m).add(k) if (n.probPrime(15) > 0) return false } return true }   var count = 0 var k = 1 while (count < 5) { if (a.call(k)) { System.write("%(k) ") count = count + 1 } k = k + 2 } System.print()
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.
#C.2B.2B
C++
g++ -std=c++11 sort.cpp
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.
#Clojure
Clojure
  ;; Gathered with Google Squared (def *langs* [["Clojure" 2007] ["Common Lisp" 1984] ["Java" 1995] ["Haskell" 1990] ["Lisp" 1958] ["Scheme" 1975]])   user> (sort-by second *langs*) ; using a keyfn   (["Lisp" 1958] ["Scheme" 1975] ["Common Lisp" 1984] ["Haskell" 1990] ["Java" 1995] ["Clojure" 2007])  
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting 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 Counting 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) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Sidef
Sidef
func counting_sort(a, min, max) { var cnt = ([0] * (max - min + 1)) a.each {|i| cnt[i-min]++ } cnt.map {|i| [min++] * i }.flat }   var a = 100.of { 100.irand } say counting_sort(a, 0, 100)
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting 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 Counting 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) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Slate
Slate
s@(Sequence traits) countingSort &min: min &max: max [| counts index | min `defaultsTo: (s reduce: #min: `er). max `defaultsTo: (s reduce: #max: `er). counts: ((0 to: max - min) project: [| :_ | 0]). s do: [| :value | counts at: value - min infect: [| :count | count + 1]]. index: 0. min to: max do: [| :value | [(counts at: value - min) isPositive] whileTrue: [s at: index put: value. index: index + 1. counts at: value - min infect: [| :val | val - 1]] ]. s ].
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).
#Fortran
Fortran
! This is free and unencumbered software released into the public domain, ! via the Unlicense. ! For more information, please refer to <http://unlicense.org/>   program no_connection_puzzle   implicit none   ! The names of the holes. integer, parameter :: a = 1 integer, parameter :: b = 2 integer, parameter :: c = 3 integer, parameter :: d = 4 integer, parameter :: e = 5 integer, parameter :: f = 6 integer, parameter :: g = 7 integer, parameter :: h = 8   integer :: holes(a:h)   call find_solutions (holes, a)   contains   recursive subroutine find_solutions (holes, current_hole_index) integer, intent(inout) :: holes(a:h) integer, intent(in) :: current_hole_index   integer :: peg_number   ! Recursively construct and print possible solutions, quitting ! any partial solution that does not satisfy constraints. do peg_number = 1, 8 holes(current_hole_index) = peg_number if (satisfies_the_constraints (holes, current_hole_index)) then if (current_hole_index == h) then call print_solution (holes) write (*, '()') else call find_solutions (holes, current_hole_index + 1) end if end if end do end subroutine find_solutions   function satisfies_the_constraints (holes, i) result (satisfies) integer, intent(inout) :: holes(a:h) integer, intent(in) :: i ! Where the new peg goes. logical :: satisfies   integer :: j   ! The most recently inserted peg must not be a duplicate of one ! already inserted. satisfies = all (holes(a : i - 1) /= holes(i))   if (satisfies) then ! ‘Fill’ the unfilled holes with fake pegs that cause ! differences with them always to be larger than 1. do j = i + 1, h holes(j) = 100 * j end do   ! Check that the differences are satisfactory. satisfies = 1 < abs (holes(a) - holes(c)) .and. & & 1 < abs (holes(a) - holes(d)) .and. & & 1 < abs (holes(a) - holes(e)) .and. & & 1 < abs (holes(c) - holes(g)) .and. & & 1 < abs (holes(d) - holes(g)) .and. & & 1 < abs (holes(e) - holes(g)) .and. & & 1 < abs (holes(b) - holes(d)) .and. & & 1 < abs (holes(b) - holes(e)) .and. & & 1 < abs (holes(b) - holes(f)) .and. & & 1 < abs (holes(d) - holes(h)) .and. & & 1 < abs (holes(e) - holes(h)) .and. & & 1 < abs (holes(f) - holes(h)) .and. & & 1 < abs (holes(c) - holes(d)) .and. & & 1 < abs (holes(d) - holes(e)) .and. & & 1 < abs (holes(e) - holes(f)) end if end function satisfies_the_constraints   subroutine print_solution (holes) integer, intent(in) :: holes(a:h)   write (*, '(I5, I4)') holes(a), holes(b) write (*, '(" /│\ /│\")') write (*, '(" / │ X │ \")') write (*, '(" / │/ \│ \")') write (*, '(3(I1, "───"), I1)') holes(c), holes(d), holes(e), holes(f) write (*, '(" \ │\ /│ /")') write (*, '(" \ │ X │ /")') write (*, '(" \│/ \│/")') write (*, '(I5, I4)') holes(g), holes(h) end subroutine print_solution   end program no_connection_puzzle
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Example 1 Problem. 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 Solution. 49 50 51 52 53 54 75 76 81 48 47 46 45 44 55 74 77 80 37 38 39 40 43 56 73 78 79 36 35 34 41 42 57 72 71 70 31 32 33 14 13 58 59 68 69 30 17 16 15 12 61 60 67 66 29 18 19 20 11 62 63 64 65 28 25 24 21 10 1 2 3 4 27 26 23 22 9 8 7 6 5 Example 2 Problem. 0 0 0 0 0 0 0 0 0 0 11 12 15 18 21 62 61 0 0 6 0 0 0 0 0 60 0 0 33 0 0 0 0 0 57 0 0 32 0 0 0 0 0 56 0 0 37 0 1 0 0 0 73 0 0 38 0 0 0 0 0 72 0 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0 Solution. 9 10 13 14 19 20 63 64 65 8 11 12 15 18 21 62 61 66 7 6 5 16 17 22 59 60 67 34 33 4 3 24 23 58 57 68 35 32 31 2 25 54 55 56 69 36 37 30 1 26 53 74 73 70 39 38 29 28 27 52 75 72 71 40 43 44 47 48 51 76 77 78 41 42 45 46 49 50 81 80 79 Task Write a program to solve puzzles of this ilk, demonstrating your program by solving the above examples. Extra credit for other interesting examples. 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 the no connection puzzle
#Prolog
Prolog
/* * Solver */ solve([A|T]) :- numlist(1,81,S), select(A,S,R), solve_([A|T],R).   solve_([_],[]). solve_([A,B|T],R) :- move(A,B), select(B,R,Rt), solve_([B|T],Rt).   move(A,B) :- lr(A,B) ; lr(B,A) ; ud(A,B) ; ud(B,A).   % create the left-right mapping rules at compile time term_expansion(lr(0,0),LrList) :- findall(LR, (between(1,81,N), M is N mod 9, dif(M,0), succ(N,N1), LR = lr(N,N1)), LrList). lr(0,0).   % create the up-down mapping rules at compile time term_expansion(ud(0,0),UdList) :- findall(UD, (between(1,72,N), N9 is N + 9, UD = ud(N,N9)), UdList). ud(0,0).     /* * Grid <-> Solvable List */ grid_solvable([],_,_). grid_solvable([A|T],N,S) :- (integer(A) -> nth1(A,S,N);true), succ(N,N1), grid_solvable(T,N1,S).   solvable_grid([],_,_). solvable_grid([A|T],N,G) :- nth1(A,G,N), succ(N,N1), solvable_grid(T,N1,G).     /* * Print Grid */ print_cell(C) :- C >= 10 -> format(' ~d', C) ; format(' ~d', C). print_grid([],_). print_grid([C|T],N) :- print_cell(C), (0 is N mod 9 -> nl ; true), succ(N,N1), print_grid(T,N1).     /* * Numbrix! */ numbrix(L) :- length(S, 81), grid_solvable(L,1,S), solve(S), solvable_grid(S,1,P), print_grid(P,1), !.   test1 :- numbrix([ _, _, _, _, _, _, _, _, _, _, _, 46, 45, _, 55, 74, _, _, _, 38, _, _, 43, _, _, 78, _, _, 35, _, _, _, _, _, 71, _, _, _, 33, _, _, _, 59, _, _, _, 17, _, _, _, _, _, 67, _, _, 18, _, _, 11, _, _, 64, _, _, _, 24, 21, _, 1, 2, _, _, _, _, _, _, _, _, _, _, _ ]).   test2 :- numbrix([ _, _, _, _, _, _, _, _, _, _, 11, 12, 15, 18, 21, 62, 61, _, _, 6, _, _, _, _, _, 60, _, _, 33, _, _, _, _, _, 57, _, _, 32, _, _, _, _, _, 56, _, _, 37, _, 1, _, _, _, 73, _, _, 38, _, _, _, _, _, 72, _, _, 43, 44, 47, 48, 51, 76, 77, _, _, _, _, _, _, _, _, _, _ ]).   test3 :- numbrix([ 17, _, _, _, 11, _, _, _, 59, _, 15, _, _, 6, _, _, 61, _, _, _, 3, _, _, _, 63, _, _, _, _, _, _, 66, _, _, _, _, 23, 24, _, 68, 67, 78, _, 54, 55, _, _, _, _, 72, _, _, _, _, _, _, 35, _, _, _, 49, _, _, _, 29, _, _, 40, _, _, 47, _, 31, _, _, _, 39, _, _, _, 45 ]).
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.
#Crystal
Crystal
  a = [5, 4, 3, 2, 1] puts a.sort # => [1, 2, 3, 4, 5]   puts a # => [5, 4, 3, 2, 1]   a.sort! puts a # => [1, 2, 3, 4, 5]  
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.
#D
D
import std.stdio, std.algorithm;   void main() { auto data = [2, 4, 3, 1, 2]; data.sort(); // in-place assert(data == [1, 2, 2, 3, 4]); }
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
#Kotlin
Kotlin
// version 1.0.6   class Oid(val id: String): Comparable<Oid> { override fun compareTo(other: Oid): Int { val splits1 = this.id.split('.') val splits2 = other.id.split('.') val minSize = if (splits1.size < splits2.size) splits1.size else splits2.size for (i in 0 until minSize) { if (splits1[i].toInt() < splits2[i].toInt()) return -1 else if (splits1[i].toInt() > splits2[i].toInt()) return 1 } return splits1.size.compareTo(splits2.size) }   override fun toString() = id }   fun main(args: Array<String>) { val oids = arrayOf( Oid("1.3.6.1.4.1.11.2.17.19.3.4.0.10"), Oid("1.3.6.1.4.1.11.2.17.5.2.0.79"), Oid("1.3.6.1.4.1.11.2.17.19.3.4.0.4"), Oid("1.3.6.1.4.1.11150.3.4.0.1"), Oid("1.3.6.1.4.1.11.2.17.19.3.4.0.1"), Oid("1.3.6.1.4.1.11150.3.4.0") ) println(oids.sorted().joinToString("\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
#Groovy
Groovy
def sparseSort = { a, indices = ([] + (0..<(a.size()))) -> indices.sort().unique() a[indices] = a[indices].sort() a }
http://rosettacode.org/wiki/Sort_stability
Sort stability
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 When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#Ruby
Ruby
ary = [["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"]] p ary.sort {|a,b| a[1] <=> b[1]} # MRI reverses the Birminghams: # => [["UK", "Birmingham"], ["US", "Birmingham"], ["UK", "London"], ["US", "New York"]]
http://rosettacode.org/wiki/Sort_stability
Sort stability
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 When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#Rust
Rust
fn main() { let country_city = [ ("UK", "London"), ("US", "New York"), ("US", "Birmingham"), ("UK", "Birmingham"), ];   let mut city_sorted = country_city.clone(); city_sorted.sort_by_key(|k| k.1);   let mut country_sorted = country_city.clone(); country_sorted.sort_by_key(|k| k.0);   println!("Original:"); for x in &country_city { println!("{} {}", x.0, x.1); }   println!("\nWhen sorted by city:"); for x in &city_sorted { println!("{} {}", x.0, x.1); }   println!("\nWhen sorted by county:"); for x in &country_sorted { println!("{} {}", x.0, x.1); } }
http://rosettacode.org/wiki/Sort_stability
Sort stability
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 When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#Scala
Scala
scala> val list = List((1, 'c'), (1, 'b'), (2, 'a')) list: List[(Int, Char)] = List((1,c), (1,b), (2,a))   scala> val srt1 = list.sortWith(_._2 < _._2) srt1: List[(Int, Char)] = List((2,a), (1,b), (1,c))   scala> val srt2 = srt1.sortBy(_._1) // Ordering[Int] is implicitly defined srt2: List[(Int, Char)] = List((1,b), (1,c), (2,a))   scala> val cities = """ | |UK London | |US New York | |US Birmingham | |UK Birmingham | |""".stripMargin.lines.filterNot(_ isEmpty).toSeq cities: Seq[String] = ArrayBuffer(UK London, US New York, US Birmingham, UK Birmingham)   scala> cities.sortBy(_ substring 4) res47: Seq[String] = ArrayBuffer(US Birmingham, UK Birmingham, UK London, US New York)
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.
#PicoLisp
PicoLisp
(let (X 77444 Y -12 Z 0) (println X Y Z) (mapc set '(X Y Z) (sort (list X Y Z))) (println X Y Z) )
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.
#Plain_English
Plain English
To run: Start up. Sort three numbers. Wait for the escape key. Shut down.   To sort three numbers: Put 77444 into an x number. Put -12 into a y number. Put 0 into a z number. Write "===Before sorting===" on the console. Write "x: " then the x on the console. Write "y: " then the y on the console. Write "z: " then the z on the console. Sort the x and the y and the z. Write "===After sorting===" on the console. Write "x: " then the x on the console. Write "y: " then the y on the console. Write "z: " then the z on the console.   To sort a first number and a second number and a third number: If the first number is greater than the second number, swap the first number with the second number. If the second number is greater than the third number, swap the second number with the third number. If the first number is greater than the second number, swap the first number with the second number.
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.
#M2000_Interpreter
M2000 Interpreter
  Module Checkit { Class Quick { Private: partition=lambda-> { Read &A(), p, r : i = p-1 : x=A(r) For j=p to r-1 {If .LE(A(j), x) Then i++:Swap A(i),A(j) } : Swap A(i+1), A(r) : Push i+2, i } Public: LE=Lambda->Number<=Number Module ForStrings { .partition<=lambda-> { Read &a$(), p, r : i = p-1 : x$=a$(r) For j=p to r-1 {If a$(j)<= x$ Then i++:Swap a$(i),a$(j) } : Swap a$(i+1), a$(r) : Push i+2, i } } Function quicksort { Read ref$ { loop : If Stackitem() >= Stackitem(2) Then Drop 2 : if empty then {Break} else continue over 2,2 : call .partition(ref$) :shift 3 } } } Quick=Quick()   ToSort$="this is a set of strings to sort This Is A Set Of Strings To Sort" Dim a$() a$()=Piece$(ToSort$, " ") \\ we can redim to any range Dim a$(100 to len(a$())+99) ' from 100 to 115 (16 items) Group Quick { Module ForStringsSpecial { .partition<=lambda-> { Read &a$(), p, r : i = p-1 : x$=a$(r) :lx$=lcase$(x$) : k=len(x$) For j=p to r-1 { m=len(a$(j)) select case compare(m, k) case 0 { aj$=lcase$(a$(j)) if aj$>lx$ then exit if aj$=lx$ then if a$(j)<=x$ then exit i++ Swap a$(i),a$(j) } case 1 { i++:Swap a$(i),a$(j) } End Select } : Swap a$(i+1), a$(r) : Push i+2, i } } } Document doc$={Unsorted List: } k=each(a$()) While k { doc$=" "+array$(k)+{ } } Quick.ForStringsSpecial \\ Dimension(a$(), 0, 1) is Lbound a$() first dimension \\ Dimension(a$(), 0, 1) is Ubound a$() first dimension Call Quick.quicksort(&a$(), Dimension(a$(), 0, 1), Dimension(a$(), 1,1)) k=each(a$()) Doc$={ Sorted List: } While k { doc$=" "+array$(k)+{ } } Report doc$ Clipboard doc$ } Checkit  
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.
#Maple
Maple
Compare_fn:= proc(s1, s2) local len1, len2; len1 := StringTools:-Length(s1); len2 := StringTools:-Length(s2); if (len1 > len2) then return true; elif (len1 < len2) then return false; else # ascending lexicographic order for strings of equal length / case insensitive StringTools:-CompareCI(s1, s2); end if; end proc:   L := ["Here", "are", "some", "sample", "strings", "to", "be", "sorted", "Tooo"]; sort(L, Compare_fn);
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#uBasic.2F4tH
uBasic/4tH
PRINT "Comb sort:" n = FUNC (_InitArray) PROC _ShowArray (n) PROC _Combsort (n) PROC _ShowArray (n) PRINT   END     _Combsort PARAM (1) ' Combsort subroutine LOCAL(4) b@ = a@ c@ = 1   DO WHILE (b@ > 1) + c@   b@ = (b@ * 10) / 13   IF (b@ = 9) + (b@ = 10) THEN b@ = 11 IF b@ < 1 THEN b@ = 1   c@ = 0 d@ = 0 e@ = b@   DO WHILE e@ < a@ IF @(d@) > @(e@) THEN PROC _Swap (d@, e@) : c@ = 1 d@ = d@ + 1 e@ = e@ + 1 LOOP LOOP RETURN     _Swap PARAM(2) ' Swap two array elements PUSH @(a@) @(a@) = @(b@) @(b@) = POP() RETURN     _InitArray ' Init example array PUSH 4, 65, 2, -31, 0, 99, 2, 83, 782, 1   FOR i = 0 TO 9 @(i) = POP() NEXT   RETURN (i)     _ShowArray PARAM (1) ' Show array subroutine FOR i = 0 TO a@-1 PRINT @(i), NEXT   PRINT RETURN
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.
#Ring
Ring
  # Project : Sorting algorithms/Bogosort   test = [4, 65, 2, 31, 0, 99, 2, 83, 782, 1] shuffles = 0 while ! sorted(test) shuffles = shuffles + 1 shuffle(test) end see "" + shuffles + " shuffles required to sort " + len(test) + " items:" + nl showarray(test)   func shuffle(d) for i = len(d) to 2 step -1 item = random(i) + 1 if item <= len(d) temp = d[i-1] d[i-1] = d[item] d[item] = temp else i = i -1 ok next   func sorted(d) for j = 2 to len(d) if d[j] < d[j-1] return false ok next return true   func showarray(vect) see "[" svect = "" for n = 1 to len(vect) svect = svect + vect[n] + ", " next svect = left(svect, len(svect) - 2) see svect see "]" + nl  
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.
#Ruby
Ruby
def shuffle(l) l.sort_by { rand } end   def bogosort(l) l = shuffle(l) until in_order(l) l end   def in_order(l) (0..l.length-2).all? {|i| l[i] <= l[i+1] } end
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.
#Elixir
Elixir
defmodule Sort do def bsort(list) when is_list(list) do t = bsort_iter(list)   if t == list, do: t, else: bsort(t) end   def bsort_iter([x, y | t]) when x > y, do: [y | bsort_iter([x | t])] def bsort_iter([x, y | t]), do: [x | bsort_iter([y | t])] def bsort_iter(list), do: list 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.
#Objeck
Objeck
  function : GnomeSort(a : Int[]) { i := 1; j := 2;   while(i < a->Size()) { if (a[i-1] <= a[i]) { i := j; j += 1; } else { tmp := a[i-1]; a[i-1] := a[i]; a[i] := tmp; i -= 1; if(i = 0) { i := j; j += 1; }; }; }; }  
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead 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 Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#XPL0
XPL0
include c:\cxpl\codes;   proc BeadSort(Array, Length); \Sort Array into increasing order int Array, Length; \Array contents range 0..31; number of items int Row, I, J, T, C; [Row:= Reserve(Length*4); \each Row has room for 32 beads for I:= 0 to Length-1 do \each Row gets Array(I) number of beads Row(I):= ~-1<<Array(I); \(beware for 80186..Pentium <<32 doesn't shift) for J:= 1 to Length-1 do for I:= Length-1 downto J do [T:= Row(I-1) & ~Row(I); \up to 31 beads fall in a single pass Row(I-1):= Row(I-1) | T; \(|=xor, !=or) Row(I):= Row(I) | T; ]; for I:= 0 to Length-1 do \count beads in each Row [C:= 0; T:= Row(I); while T do [if T&1 then C:= C+1; T:= T>>1]; Array(I):= C; \count provides sorted order ]; ];   int A, I; [A:= [3, 1, 4, 1, 25, 9, 2, 6, 5, 0]; BeadSort(A, 10); for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )]; ]
http://rosettacode.org/wiki/Sorting_algorithms/Bead_sort
Sorting algorithms/Bead 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 Task Sort an array of positive integers using the Bead Sort Algorithm. A   bead sort   is also known as a   gravity sort. Algorithm has   O(S),   where   S   is the sum of the integers in the input set:   Each bead is moved individually. This is the case when bead sort is implemented without a mechanism to assist in finding empty spaces below the beads, such as in software implementations.
#zkl
zkl
fcn columns(m){ // m is list of lists of zeros/beads, # beads is n, eg (0,0,0)==3 m .apply("len") // (0,0,0)-->3 .reduce("max") // largest bead stack .walker() // [0..max] .apply('wrap(i){ m.filter('wrap(s){ s.len() > i }).len().pump(List,0) }); }   fcn beadSort(data){ data.apply("pump",List,0):columns(_):columns(_).apply("len"); }
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
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
cocktailSort[A_List] := Module[ { swapped = True }, While[ swapped == True, swapped=False; For[ i = 1, i< Length[A]-1,i++, If[ A[[i]] > A[[i+1]], A[[i;;i+1]] = A[[i+1;;i;;-1]]; swapped=True;] ]; If[swapped == False, Break[]]; swapped=False; For [ i= Length[A]-1, i > 0, i--, If[ A[[i]] > A[[i+1]], A[[i;;i+1]] = A[[i+1;;i;;-1]]; swapped = True;] ]]]
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.
#Ada
Ada
with GNAT.Sockets; use GNAT.Sockets;   procedure Socket_Send is Client : Socket_Type; begin Initialize; Create_Socket (Socket => Client); Connect_Socket (Socket => Client, Server => (Family => Family_Inet, Addr => Inet_Addr ("127.0.0.1"), Port => 256)); String'Write (Stream (Client), "hello socket world"); Close_Socket (Client); end Socket_Send;
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
#11l
11l
F divisors(n) V divs = [1] L(ii) 2 .< Int(n ^ 0.5) + 3 I n % ii == 0 divs.append(ii) divs.append(Int(n / ii)) divs.append(n) R Array(Set(divs))   F is_prime(n) R divisors(n).len == 2   F digit_check(n) I String(n).len < 2 R 1B E L(digit) String(n) I !is_prime(Int(digit)) R 0B R 1B   F sequence(max_n) V ii = 0 V n = 0 [Int] r L ii++ I is_prime(ii) I n > max_n L.break I digit_check(ii) n++ r.append(ii) R r   V seq = sequence(100) print(‘First 25 SPDS primes:’) L(item) seq[0.<25] print(item, end' ‘ ’) print() print(‘Hundredth SPDS prime: ’seq[99])
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.
#C
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <stdint.h> #include <assert.h> #include <stdbool.h>   int w, h, n_boxes; uint8_t *board, *goals, *live;   typedef uint16_t cidx_t; typedef uint32_t hash_t;   /* board configuration is represented by an array of cell indices of player and boxes */ typedef struct state_t state_t;   struct state_t { // variable length hash_t h; state_t *prev, *next, *qnext; cidx_t c[]; };   size_t state_size, block_size = 32; state_t *block_root, *block_head;   inline state_t* newstate(state_t *parent) { inline state_t* next_of(state_t *s) { return (void*)((uint8_t*)s + state_size); }   state_t *ptr; if (!block_head) { block_size *= 2; state_t *p = malloc(block_size * state_size); assert(p); p->next = block_root; block_root = p; ptr = (void*)((uint8_t*)p + state_size * block_size); p = block_head = next_of(p); state_t *q; for (q = next_of(p); q < ptr; p = q, q = next_of(q)) p->next = q; p->next = NULL; }   ptr = block_head; block_head = block_head->next;   ptr->prev = parent; ptr->h = 0; return ptr; }   inline void unnewstate(state_t *p) { p->next = block_head; block_head = p; }   enum { space, wall, player, box };   #define E "\033[" const char * const glyph1[] = { " ", "#", E"31m@"E"m", E"33m$"E"m"}; const char * const glyph2[] = { E"32m."E"m", "#", E"32m@"E"m", E"32m$"E"m"}; #undef E   // mark up positions where a box definitely should not be void mark_live(const int c) { const int y = c / w, x = c % w; if (live[c]) return;   live[c] = 1; if (y > 1 && board[c - w] != wall && board[c - w * 2] != wall) mark_live(c - w); if (y < h - 2 && board[c + w] != wall && board[c + w * 2] != wall) mark_live(c + w); if (x > 1 && board[c - 1] != wall && board[c - 2] != wall) mark_live(c - 1); if (x < w - 2 && board[c + 1] != wall && board[c + 2] != wall) mark_live(c + 1); }   state_t *parse_board(const int y, const int x, const char *s) { w = x, h = y; board = calloc(w * h, sizeof(uint8_t)); assert(board); goals = calloc(w * h, sizeof(uint8_t)); assert(goals); live = calloc(w * h, sizeof(uint8_t)); assert(live);   n_boxes = 0; for (int i = 0; s[i]; i++) { switch(s[i]) { case '#': board[i] = wall; continue;   case '.': // fallthrough case '+': goals[i] = 1; // fallthrough case '@': continue;   case '*': goals[i] = 1; // fallthrough case '$': n_boxes++; continue; default: continue; } }   const int is = sizeof(int); state_size = (sizeof(state_t) + (1 + n_boxes) * sizeof(cidx_t) + is - 1) / is * is;   state_t *state = newstate(NULL);   for (int i = 0, j = 0; i < w * h; i++) { if (goals[i]) mark_live(i); if (s[i] == '$' || s[i] == '*') state->c[++j] = i; else if (s[i] == '@' || s[i] == '+') state->c[0] = i; }   return state; }   void show_board(const state_t *s) { unsigned char b[w * h]; memcpy(b, board, w * h);   b[ s->c[0] ] = player; for (int i = 1; i <= n_boxes; i++) b[ s->c[i] ] = box;   for (int i = 0; i < w * h; i++) { printf((goals[i] ? glyph2 : glyph1)[ b[i] ]); if (! ((1 + i) % w)) putchar('\n'); } }   // K&R hash function inline void hash(state_t *s) { if (!s->h) { register hash_t ha = 0; cidx_t *p = s->c; for (int i = 0; i <= n_boxes; i++) ha = p[i] + 31 * ha; s->h = ha; } }   state_t **buckets; hash_t hash_size, fill_limit, filled;   void extend_table() { int old_size = hash_size;   if (!old_size) { hash_size = 1024; filled = 0; fill_limit = hash_size * 3 / 4; // 0.75 load factor } else { hash_size *= 2; fill_limit *= 2; }   buckets = realloc(buckets, sizeof(state_t*) * hash_size); assert(buckets);   // rehash memset(buckets + old_size, 0, sizeof(state_t*) * (hash_size - old_size));   const hash_t bits = hash_size - 1; for (int i = 0; i < old_size; i++) { state_t *head = buckets[i]; buckets[i] = NULL; while (head) { state_t *next = head->next; const int j = head->h & bits; head->next = buckets[j]; buckets[j] = head; head = next; } } }   state_t *lookup(state_t *s) { hash(s); state_t *f = buckets[s->h & (hash_size - 1)]; for (; f; f = f->next) { if (//(f->h == s->h) && !memcmp(s->c, f->c, sizeof(cidx_t) * (1 + n_boxes))) break; }   return f; }   bool add_to_table(state_t *s) { if (lookup(s)) { unnewstate(s); return false; }   if (filled++ >= fill_limit) extend_table();   hash_t i = s->h & (hash_size - 1);   s->next = buckets[i]; buckets[i] = s; return true; }   bool success(const state_t *s) { for (int i = 1; i <= n_boxes; i++) if (!goals[s->c[i]]) return false; return true; }   state_t *move_me(state_t *s, const int dy, const int dx) { const int y = s->c[0] / w; const int x = s->c[0] % w; const int y1 = y + dy; const int x1 = x + dx; const int c1 = y1 * w + x1;   if (y1 < 0 || y1 > h || x1 < 0 || x1 > w || board[c1] == wall) return NULL;   int at_box = 0; for (int i = 1; i <= n_boxes; i++) { if (s->c[i] == c1) { at_box = i; break; } }   int c2; if (at_box) { c2 = c1 + dy * w + dx; if (board[c2] == wall || !live[c2]) return NULL; for (int i = 1; i <= n_boxes; i++) if (s->c[i] == c2) return NULL; }   state_t *n = newstate(s); memcpy(n->c + 1, s->c + 1, sizeof(cidx_t) * n_boxes);   cidx_t *p = n->c; p[0] = c1;   if (at_box) p[at_box] = c2;   // leet bubble sort for (int i = n_boxes; --i; ) { cidx_t t = 0; for (int j = 1; j < i; j++) { if (p[j] > p[j + 1]) t = p[j], p[j] = p[j+1], p[j+1] = t; } if (!t) break; }   return n; }   state_t *next_level, *done;   bool queue_move(state_t *s) { if (!s || !add_to_table(s)) return false;   if (success(s)) { puts("\nSuccess!"); done = s; return true; }   s->qnext = next_level; next_level = s; return false; }   bool do_move(state_t *s) { return queue_move(move_me(s, 1, 0)) || queue_move(move_me(s, -1, 0)) || queue_move(move_me(s, 0, 1)) || queue_move(move_me(s, 0, -1)); }   void show_moves(const state_t *s) { if (s->prev) show_moves(s->prev); usleep(200000); printf("\033[H"); show_board(s); }   int main() { state_t *s = parse_board(   #define BIG 0   #if BIG == 0 8, 7, "#######" "# #" "# #" "#. # #" "#. $$ #" "#.$$ #" "#.# @#" "#######"   #elif BIG == 1 5, 13, "#############" "# # #" "# $$$$$$$ @#" "#....... #" "#############"   #elif BIG == 2 5, 13, "#############" "#... # #" "#.$$$$$$$ @#" "#... #" "#############"   #else 11, 19, " ##### " " # # " " # # " " ### #$## " " # # " "### #$## # ######" "# # ## ##### .#" "# $ $ ..#" "##### ### #@## .#" " # #########" " ####### " #endif );   show_board(s); extend_table(); queue_move(s); for (int i = 0; !done; i++) { printf("depth %d\r", i); fflush(stdout);   state_t *head = next_level; for (next_level = NULL; head && !done; head = head->qnext) do_move(head);   if (!next_level) { puts("no solution?"); return 1; } }   printf("press any key to see moves\n"); getchar(), puts("\033[H\033[J"); show_moves(done);   #if 0 free(buckets); free(board); free(goals); free(live);   while (block_root) { void *tmp = block_root->next; free(block_root); block_root = tmp; } #endif   return 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
#Haskell
Haskell
import Data.Array (Array, (//), (!), assocs, elems, bounds, listArray) import Data.Foldable (forM_) import Data.List (intercalate, transpose) import Data.Maybe   type Position = (Int, Int)   type KnightBoard = Array Position (Maybe Int)   toSlot :: Char -> Maybe Int toSlot '0' = Just 0 toSlot '1' = Just 1 toSlot _ = Nothing   toString :: Maybe Int -> String toString Nothing = replicate 3 ' ' toString (Just n) = replicate (3 - length nn) ' ' ++ nn where nn = show n   chunksOf :: Int -> [a] -> [[a]] chunksOf _ [] = [] chunksOf n xs = let (chunk, rest) = splitAt n xs in chunk : chunksOf n rest   showBoard :: KnightBoard -> String showBoard board = intercalate "\n" . map concat . transpose . chunksOf (height + 1) . map toString $ elems board where (_, (_, height)) = bounds board   toBoard :: [String] -> KnightBoard toBoard strs = board where height = length strs width = minimum (length <$> strs) board = listArray ((0, 0), (width - 1, height - 1)) . map toSlot . concat . transpose $ take width <$> strs   add :: Num a => (a, a) -> (a, a) -> (a, a) add (a, b) (x, y) = (a + x, b + y)   within :: Ord a => ((a, a), (a, a)) -> (a, a) -> Bool within ((a, b), (c, d)) (x, y) = a <= x && x <= c && b <= y && y <= d   -- Enumerate valid moves given a board and a knight's position. validMoves :: KnightBoard -> Position -> [Position] validMoves board position = filter isValid plausible where bound = bounds board plausible = add position <$> [(1, 2), (2, 1), (2, -1), (-1, 2), (-2, 1), (1, -2), (-1, -2), (-2, -1)] isValid pos = within bound pos && maybe False (== 0) (board ! pos)   isSolved :: KnightBoard -> Bool isSolved = all (maybe True (0 /=))   -- Solve the knight's tour with a simple Depth First Search. solveKnightTour :: KnightBoard -> Maybe KnightBoard solveKnightTour board = solve board 1 initPosition where initPosition = fst $ head $ filter ((== Just 1) . snd) $ assocs board solve boardA depth position = let boardB = boardA // [(position, Just depth)] in if isSolved boardB then Just boardB else listToMaybe $ mapMaybe (solve boardB $ depth + 1) $ validMoves boardB position   tourExA :: [String] tourExA = [ " 000 " , " 0 00 " , " 0000000" , "000 0 0" , "0 0 000" , "1000000 " , " 00 0 " , " 000 " ]   tourExB :: [String] tourExB = [ "-----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-----" ]   main :: IO () main = forM_ [tourExA, tourExB] (\board -> case solveKnightTour $ toBoard board of Nothing -> putStrLn "No solution.\n" Just solution -> putStrLn $ showBoard solution ++ "\n")
http://rosettacode.org/wiki/SOAP
SOAP
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
#Icon_and_Unicon
Icon and Unicon
import soap   procedure main(A) soap := SoapClient(A[1] | "http://example.com/soap/wsdl") # Allow override of default write("soapFunc: ",soap.call("soapFunc")) write("anotherSoapFunc: ",soap.call("anotherSoapFunc")) end
http://rosettacode.org/wiki/SOAP
SOAP
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
#Julia
Julia
using LibCURL   function callSOAP(url, infilename, outfilename) rfp = open(infilename, "r") wfp = open(outfilename, "w+")   header = curl_slist_append(header, "Content-Type:text/xml") header = curl_slist_append(header, "SOAPAction: rsc"); header = curl_slist_append(header, "Transfer-Encoding: chunked") header = curl_slist_append(header, "Expect:")   curl = curl_easy_init(); curl_easy_setopt(curl, CURLOPT_URL, URL) curl_easy_setopt(curl, CURLOPT_POST, 1L) curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_data) curl_easy_setopt(curl, CURLOPT_READDATA, rfp) curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data) curl_easy_setopt(curl, CURLOPT_WRITEDATA, wfp) curl_easy_setopt(curl, CURLOPT_HTTPHEADER, header) curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, (curl_off_t)-1) curl_easy_setopt(curl, CURLOPT_VERBOSE,1L) curl_easy_perform(curl)   curl_easy_cleanup(curl) end   try callSOAP(ARGS[1], ARGS[2], ARGS[3]) catch y println("Usage : $(@__FILE__) <URL of WSDL> <Input file path> <Output File Path>") end  
http://rosettacode.org/wiki/SOAP
SOAP
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
#Kotlin
Kotlin
// libcurl.def headers = /usr/include/curl/curl.h linkerOpts.linux = -L/usr/lib/x86_64-linux-gnu -lcurl
http://rosettacode.org/wiki/SOAP
SOAP
In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ). This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
InstallService["http://example.com/soap/wsdl"]; soapFunc["Hello"]; anotherSoapFunc[12345];
http://rosettacode.org/wiki/Solve_a_Hopido_puzzle
Solve a Hopido puzzle
Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following: "Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7×7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!" Knowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds. Example: . 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 . . . Extra credits are available for other interesting designs. 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 Numbrix puzzle Solve the no connection puzzle
#Perl
Perl
#!/usr/bin/perl   use strict; # http://www.rosettacode.org/wiki/Solve_a_Hopido_puzzle use warnings;   $_ = do { local $/; <DATA> }; s/./$&$&/g; # double chars my $w = /\n/ && $-[0]; my $wd = 3 * $w + 1; # vertical gap my $wr = 2 * $w + 8; # down right gap my $wl = 2 * $w - 8; # down left gap place($_, '00'); die "No solution\n";   sub place { (local $_, my $last) = @_; (my $new = $last)++; /$last.{10}(?=00)/g and place( s/\G00/$new/r, $new ); # right /(?=00.{10}$last)/g and place( s/\G00/$new/r, $new ); # left /$last.{$wd}(?=00)/gs and place( s/\G00/$new/r, $new ); # down /(?=00.{$wd}$last)/gs and place( s/\G00/$new/r, $new ); # up /$last.{$wr}(?=00)/gs and place( s/\G00/$new/r, $new ); # down right /(?=00.{$wr}$last)/gs and place( s/\G00/$new/r, $new ); # up left /$last.{$wl}(?=00)/gs and place( s/\G00/$new/r, $new ); # down left /(?=00.{$wl}$last)/gs and place( s/\G00/$new/r, $new ); # up right /00/ and return; print "Solution\n\n", s/ / /gr =~ s/0\B/ /gr; exit; }   __DATA__ . 0 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 0 0 0 0 . 0 0 0 0 0 . . . 0 0 0 . . . . . 0 . . .
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.
#Common_Lisp
Common Lisp
CL-USER> (defparameter *test-scores* '(("texas" 68.9) ("ohio" 87.8) ("california" 76.2) ("new york" 88.2)) ) *TEST-SCORES*
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.
#D
D
import std.stdio, std.algorithm;   struct Pair { string name, value; }   void main() { Pair[] pairs = [{"Joe", "5531"}, {"Adam", "2341"}, {"Bernie", "122"}, {"Walter", "1234"}, {"David", "19"}];   pairs.schwartzSort!q{ a.name }.writeln; }
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort
Sorting algorithms/Counting 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 Counting 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) Task Implement the Counting sort.   This is a way of sorting integers when the minimum and maximum value are known. Pseudocode function countingSort(array, min, max): count: array of (max - min + 1) elements initialize count with 0 for each number in array do count[number - min] := count[number - min] + 1 done z := 0 for i from min to max do while ( count[i - min] > 0 ) do array[z] := i z := z+1 count[i - min] := count[i - min] - 1 done done The min and max can be computed apart, or be known a priori. Note:   we know that, given an array of integers,   its maximum and minimum values can be always found;   but if we imagine the worst case for an array that can hold up to 32 bit integers,   we see that in order to hold the counts,   an array of up to 232 elements may be needed.   I.E.:   we need to hold a count value up to 232-1,   which is a little over 4.2 Gbytes.   So the counting sort is more practical when the range is (very) limited,   and minimum and maximum values are known   a priori.     (However, as a counterexample,   the use of   sparse arrays   minimizes the impact of the memory usage,   as well as removing the need of having to know the minimum and maximum values   a priori.)
#Smalltalk
Smalltalk
OrderedCollection extend [ countingSortWithMin: min andMax: max [ |oc z| oc := OrderedCollection new. 1 to: (max - min + 1) do: [ :n| oc add: 0 ]. self do: [ :v | oc at: (v - min + 1) put: ( (oc at: (v - min + 1)) + 1) ]. z := 1. min to: max do: [ :i | 1 to: (oc at: (i - min + 1)) do: [ :k | self at: z put: i. z := z + 1. ] ] ] ].
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).
#Go
Go
package main   import ( "fmt" "strings" )   func main() { p, tests, swaps := Solution() fmt.Println(p) fmt.Println("Tested", tests, "positions and did", swaps, "swaps.") }   // Holes A=0, B=1, …, H=7 // With connections: const conn = ` A B /|\ /|\ / | X | \ / |/ \| \ C - D - E - F \ |\ /| / \ | X | / \|/ \|/ G H`   var connections = []struct{ a, b int }{ {0, 2}, {0, 3}, {0, 4}, // A to C,D,E {1, 3}, {1, 4}, {1, 5}, // B to D,E,F {6, 2}, {6, 3}, {6, 4}, // G to C,D,E {7, 3}, {7, 4}, {7, 5}, // H to D,E,F {2, 3}, {3, 4}, {4, 5}, // C-D, D-E, E-F }   type pegs [8]int   // Valid checks if the pegs are a valid solution. // If the absolute difference between any pair of connected pegs is // greater than one it is a valid solution. func (p *pegs) Valid() bool { for _, c := range connections { if absdiff(p[c.a], p[c.b]) <= 1 { return false } } return true }   // Solution is a simple recursive brute force solver, // it stops at the first found solution. // It returns the solution, the number of positions tested, // and the number of pegs swapped. func Solution() (p *pegs, tests, swaps int) { var recurse func(int) bool recurse = func(i int) bool { if i >= len(p)-1 { tests++ return p.Valid() } // Try each remain peg from p[i:] in p[i] for j := i; j < len(p); j++ { swaps++ p[i], p[j] = p[j], p[i] if recurse(i + 1) { return true } p[i], p[j] = p[j], p[i] } return false } p = &pegs{1, 2, 3, 4, 5, 6, 7, 8} recurse(0) return }   func (p *pegs) String() string { return strings.Map(func(r rune) rune { if 'A' <= r && r <= 'H' { return rune(p[r-'A'] + '0') } return r }, conn) }   func absdiff(a, b int) int { if a > b { return a - b } return b - a }
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle
Solve a Numbrix puzzle
Numbrix puzzles are similar to Hidato. The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood). Published puzzles also tend not to have holes in the grid and may not always indicate the end node. Two examples follow: Example 1 Problem. 0 0 0 0 0 0 0 0 0 0 0 46 45 0 55 74 0 0 0 38 0 0 43 0 0 78 0 0 35 0 0 0 0 0 71 0 0 0 33 0 0 0 59 0 0 0 17 0 0 0 0 0 67 0 0 18 0 0 11 0 0 64 0 0 0 24 21 0 1 2 0 0 0 0 0 0 0 0 0 0 0 Solution. 49 50 51 52 53 54 75 76 81 48 47 46 45 44 55 74 77 80 37 38 39 40 43 56 73 78 79 36 35 34 41 42 57 72 71 70 31 32 33 14 13 58 59 68 69 30 17 16 15 12 61 60 67 66 29 18 19 20 11 62 63 64 65 28 25 24 21 10 1 2 3 4 27 26 23 22 9 8 7 6 5 Example 2 Problem. 0 0 0 0 0 0 0 0 0 0 11 12 15 18 21 62 61 0 0 6 0 0 0 0 0 60 0 0 33 0 0 0 0 0 57 0 0 32 0 0 0 0 0 56 0 0 37 0 1 0 0 0 73 0 0 38 0 0 0 0 0 72 0 0 43 44 47 48 51 76 77 0 0 0 0 0 0 0 0 0 0 Solution. 9 10 13 14 19 20 63 64 65 8 11 12 15 18 21 62 61 66 7 6 5 16 17 22 59 60 67 34 33 4 3 24 23 58 57 68 35 32 31 2 25 54 55 56 69 36 37 30 1 26 53 74 73 70 39 38 29 28 27 52 75 72 71 40 43 44 47 48 51 76 77 78 41 42 45 46 49 50 81 80 79 Task Write a program to solve puzzles of this ilk, demonstrating your program by solving the above examples. Extra credit for other interesting examples. 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 the no connection puzzle
#Python
Python
  from sys import stdout neighbours = [[-1, 0], [0, -1], [1, 0], [0, 1]] exists = [] lastNumber = 0 wid = 0 hei = 0     def find_next(pa, x, y, z): for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == z: return a, b   return -1, -1     def find_solution(pa, x, y, z): if z > lastNumber: return 1 if exists[z] == 1: s = find_next(pa, x, y, z) if s[0] < 0: return 0 return find_solution(pa, s[0], s[1], z + 1)   for i in range(4): a = x + neighbours[i][0] b = y + neighbours[i][1] if wid > a > -1 and hei > b > -1: if pa[a][b] == 0: pa[a][b] = z r = find_solution(pa, a, b, z + 1) if r == 1: return 1 pa[a][b] = 0   return 0     def solve(pz, w, h): global lastNumber, wid, hei, exists   lastNumber = w * h wid = w hei = h exists = [0 for j in range(lastNumber + 1)]   pa = [[0 for j in range(h)] for i in range(w)] st = pz.split() idx = 0 for j in range(h): for i in range(w): if st[idx] == ".": idx += 1 else: pa[i][j] = int(st[idx]) exists[pa[i][j]] = 1 idx += 1   x = 0 y = 0 t = w * h + 1 for j in range(h): for i in range(w): if pa[i][j] != 0 and pa[i][j] < t: t = pa[i][j] x = i y = j   return find_solution(pa, x, y, t + 1), pa     def show_result(r): if r[0] == 1: for j in range(hei): for i in range(wid): stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No Solution!\n")   print()     r = solve(". . . . . . . . . . . 46 45 . 55 74 . . . 38 . . 43 . . 78 . . 35 . . . . . 71 . . . 33 . . . 59 . . . 17" " . . . . . 67 . . 18 . . 11 . . 64 . . . 24 21 . 1 2 . . . . . . . . . . .", 9, 9) show_result(r)   r = solve(". . . . . . . . . . 11 12 15 18 21 62 61 . . 6 . . . . . 60 . . 33 . . . . . 57 . . 32 . . . . . 56 . . 37" " . 1 . . . 73 . . 38 . . . . . 72 . . 43 44 47 48 51 76 77 . . . . . . . . . .", 9, 9) show_result(r)   r = solve("17 . . . 11 . . . 59 . 15 . . 6 . . 61 . . . 3 . . . 63 . . . . . . 66 . . . . 23 24 . 68 67 78 . 54 55" " . . . . 72 . . . . . . 35 . . . 49 . . . 29 . . 40 . . 47 . 31 . . . 39 . . . 45", 9, 9) show_result(r)  
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.
#Delphi
Delphi
uses Types, Generics.Collections;   var a: TIntegerDynArray; begin a := TIntegerDynArray.Create(5, 4, 3, 2, 1); TArray.Sort<Integer>(a); end;
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.
#DWScript
DWScript
var a : array of Integer := [5, 4, 3, 2, 1]; a.Sort; // ascending natural sort PrintLn(a.Map(IntToStr).Join(',')); // 1,2,3,4,5
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
#Lua
Lua
local OIDs = { "1.3.6.1.4.1.11.2.17.19.3.4.0.10", "1.3.6.1.4.1.11.2.17.5.2.0.79", "1.3.6.1.4.1.11.2.17.19.3.4.0.4", "1.3.6.1.4.1.11150.3.4.0.1", "1.3.6.1.4.1.11.2.17.19.3.4.0.1", "1.3.6.1.4.1.11150.3.4.0" }   function compare (a, b) local aList, bList, Na, Nb = {}, {} for num in a:gmatch("%d+") do table.insert(aList, num) end for num in b:gmatch("%d+") do table.insert(bList, num) end for i = 1, math.max(#aList, #bList) do Na, Nb = tonumber(aList[i]) or 0, tonumber(bList[i]) or 0 if Na ~= Nb then return Na < Nb end end end   table.sort(OIDs, compare) for _, oid in pairs(OIDs) do print(oid) end
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
#Haskell
Haskell
import Control.Monad import qualified Data.Array as A import Data.Array.IArray import Data.Array.ST import Data.List import Data.List.Utils   -- Partition 'xs' according to whether their element indices are in 'is'. Sort -- the sublist corresponding to 'is', merging the result with the remainder of -- the list. disSort1 :: (Ord a, Num a, Enum a, Ord b) => [b] -> [a] -> [b] disSort1 xs is = let is_ = sort is (sub, rest) = partition ((`elem` is_) . fst) $ zip [0 ..] xs in map snd . merge rest . zip is_ . sort $ map snd sub   -- Convert the list to an array. Extract the sublist corresponding to the -- indices 'is'. Sort the sublist, replacing those elments in the array. disSort2 :: (Ord a) => [a] -> [Int] -> [a] disSort2 xs is = let as = A.listArray (0, length xs - 1) xs sub = zip (sort is) . sort $ map (as !) is in elems $ as // sub   -- Similar to disSort2, but using mutable arrays. The sublist is updated -- "in place", rather than creating a new array. However, this is not visible -- to a caller. disSort3 :: [Int] -> [Int] -> [Int] disSort3 xs is = elems . runSTUArray $ do as <- newListArray (0, length xs - 1) xs sub <- (zip (sort is) . sort) Control.Applicative.<$> mapM (readArray as) is mapM_ (uncurry (writeArray as)) sub return as   main :: IO () main = do let xs = [7, 6, 5, 4, 3, 2, 1, 0] is = [6, 1, 7] print $ disSort1 xs is print $ disSort2 xs is print $ disSort3 xs is
http://rosettacode.org/wiki/Sort_stability
Sort stability
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 When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#Sidef
Sidef
var table = [ <UK London>, <US New\ York>, <US Birmingham>, <UK Birmingham>, ];   table.sort {|a,b| a[0] <=> b[0]}.each { |col| say "#{col[0]} #{col[1]}" }
http://rosettacode.org/wiki/Sort_stability
Sort stability
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 When sorting records in a table by a particular column or field, a stable sort will always retain the relative order of records that have the same key. Example In this table of countries and cities, a stable sort on the second column, the cities, would keep the   US Birmingham   above the   UK Birmingham. (Although an unstable sort might, in this case, place the   US Birmingham   above the   UK Birmingham,   a stable sort routine would guarantee it). UK London US New York US Birmingham UK Birmingham Similarly, stable sorting on just the first column would generate UK London as the first item and US Birmingham as the last item   (since the order of the elements having the same first word –   UK or US   – would be maintained). Task   Examine the documentation on any in-built sort routines supplied by a language.   Indicate if an in-built routine is supplied   If supplied, indicate whether or not the in-built routine is stable. (This Wikipedia table shows the stability of some common sort routines).
#Stata
Stata
import "/sort" for Cmp, Sort   var data = [ ["UK", "London"], ["US", "New York"], ["US", "Birmingham"], ["UK", "Birmingham"] ]   // for sorting by country var cmp = Fn.new { |p1, p2| Cmp.string.call(p1[0], p2[0]) }   // for sorting by city var cmp2 = Fn.new { |p1, p2| Cmp.string.call(p1[1], p2[1]) }   System.print("Initial data:") System.print(" " + data.join("\n "))   System.print("\nSorted by country:") var data2 = data.toList Sort.insertion(data2, cmp) System.print(" " + data2.join("\n "))   System.print("\nSorted by city:") var data3 = data.toList Sort.insertion(data3, cmp2) System.print(" " + data3.join("\n "))
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.
#PureBasic
PureBasic
;sort three variables: x, y, z   ;Macro handles any of the native types, including integers, floating point, and strings ;because the variable types are not declared but substituted during each instance of the macro. ;The sorting is in ascending order, i.e. x < y < z. Macro sort3vars(x, y, z) If x > y: Swap x, y: EndIf If x > z: Swap x, z: EndIf If y > z: Swap y, z: EndIf EndMacro   ;Macro to perform the sorting test for each variable type, again by substitution. Macro test_sort(x, y, z) PrintN("Variables before sorting: " + #CRLF$ + x + #CRLF$ + y + #CRLF$ + z + #CRLF$) sort3vars(x, y, z)   PrintN("Variables after sorting: " + #CRLF$ + x + #CRLF$ + y + #CRLF$ + z + #CRLF$) EndMacro     ;Define three sets of variables each with a different type for testing Define.s x, y, z ;string x = "lions, tigers, and" y = "bears, oh my!" z = ~"(from the \"Wizard of OZ\")" ;uses an escaped string as one way to include quotation marks   Define x1 = 77444, y1 = -12, z1 = 0 ;integer   Define.f x2= 5.2, y2 = -1133.9, z2 = 0 ;floating point If OpenConsole() PrintN("Sort three variables" + #CRLF$) test_sort(x, y, z) ;strings   test_sort(x1, y1, z1) ;integers   test_sort(x2, y2, z2) ;floating point   Print(#CRLF$ + "Press ENTER to exit"): Input() CloseConsole() EndIf
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
StringOrderQ[x_String, y_String] := If[StringLength[x] == StringLength[y], OrderedQ[{x, y}], StringLength[x] >StringLength[y] ] words={"on","sunday","sander","sifted","and","sorted","sambaa","for","a","second"}; Sort[words,StringOrderQ]
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.
#Maxima
Maxima
strangeorderp(a, b) := slength(a) > slength(b) or (slength(a) = slength(b) and orderlessp(a, b))$ s: tokens("Lorem ipsum dolor sit amet consectetur adipiscing elit Sed non risus Suspendisse\ lectus tortor dignissim sit amet adipiscing nec ultricies sed dolor")$   sort(s, strangeorderp); ["Suspendisse", "consectetur", "adipiscing", "adipiscing", "dignissim", "ultricies", "lectus", "tortor", "Lorem", "dolor", "dolor", "ipsum", "risus", "amet", "amet", "elit", "Sed", "nec", "non", "sed", "sit", "sit"]
http://rosettacode.org/wiki/Sorting_algorithms/Comb_sort
Sorting algorithms/Comb sort
Sorting algorithms/Comb sort You are encouraged to solve this task according to the task description, using any language you may know. 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 Implement a   comb sort. The Comb Sort is a variant of the Bubble Sort. Like the Shell sort, the Comb Sort increases the gap used in comparisons and exchanges. Dividing the gap by   ( 1 − e − φ ) − 1 ≈ 1.247330950103979 {\displaystyle (1-e^{-\varphi })^{-1}\approx 1.247330950103979}   works best, but   1.3   may be more practical. Some implementations use the insertion sort once the gap is less than a certain amount. Also see   the Wikipedia article:   Comb sort. Variants: Combsort11 makes sure the gap ends in (11, 8, 6, 4, 3, 2, 1), which is significantly faster than the other two possible endings. Combsort with different endings changes to a more efficient sort when the data is almost sorted (when the gap is small).   Comb sort with a low gap isn't much better than the Bubble Sort. Pseudocode: function combsort(array input) gap := input.size //initialize gap size loop until gap = 1 and swaps = 0 //update the gap value for a next comb. Below is an example gap := int(gap / 1.25) if gap < 1 //minimum gap is 1 gap := 1 end if i := 0 swaps := 0 //see Bubble Sort for an explanation //a single "comb" over the input list loop until i + gap >= input.size //see Shell sort for similar idea if input[i] > input[i+gap] swap(input[i], input[i+gap]) swaps := 1 // Flag a swap has occurred, so the // list is not guaranteed sorted end if i := i + 1 end loop end loop end function
#VBA
VBA
Function comb_sort(ByVal s As Variant) As Variant Dim gap As Integer: gap = UBound(s) Dim swapped As Integer Do While True gap = WorksheetFunction.Max(WorksheetFunction.Floor_Precise(gap / 1.3), 1) swapped = False For i = 0 To UBound(s) - gap si = Val(s(i)) If si > Val(s(i + gap)) Then s(i) = s(i + gap) s(i + gap) = CStr(si) swapped = True End If Next i If gap = 1 And Not swapped Then Exit Do Loop comb_sort = s End Function   Public Sub main() Dim s(9) As Variant For i = 0 To 9 s(i) = CStr(Int(1000 * Rnd)) Next i Debug.Print Join(s, ", ") Debug.Print Join(comb_sort(s), ", ") End Sub
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.
#Rust
Rust
extern crate rand; use rand::Rng;   fn bogosort_by<T,F>(order: F, coll: &mut [T]) where F: Fn(&T, &T) -> bool { let mut rng = rand::thread_rng(); while !is_sorted_by(&order, coll) { rng.shuffle(coll); } }   #[inline] fn is_sorted_by<T,F>(order: F, coll: &[T]) -> bool where F: Fn(&T,&T) -> bool, { coll[..].iter().zip(&coll[1..]).all(|(x,y)| order(x,y)) }     fn main() { let mut testlist = [1,55,88,24,990876,312,67,0,854,13,4,7]; bogosort_by(|x,y| x < y, &mut testlist); println!("{:?}", testlist); bogosort_by(|x,y| x > y, &mut testlist); println!("{:?}", testlist); }  
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.
#Scala
Scala
def isSorted(l: List[Int]) = l.iterator sliding 2 forall (s => s.head <= s.last) def bogosort(l: List[Int]): List[Int] = if (isSorted(l)) l else bogosort(scala.util.Random.shuffle(l))
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.
#Erlang
Erlang
  -module( bubble_sort ).   -export( [list/1, task/0] ).   list( To_be_sorted ) -> sort( To_be_sorted, [], true ).   task() -> List = "asdqwe123", Sorted = list( List ), io:fwrite( "List ~p is sorted ~p~n", [List, Sorted] ).     sort( [], Acc, true ) -> lists:reverse( Acc ); sort( [], Acc, false ) -> sort( lists:reverse(Acc), [], true ); sort( [X, Y | T], Acc, _Done ) when X > Y -> sort( [X | T], [Y | Acc], false ); sort( [X | T], Acc, Done ) -> sort( T, [X | Acc], Done ).  
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.
#OCaml
OCaml
# let gnome_sort a = let i = ref 1 and j = ref 2 in while !i < Array.length a do if a.(!i-1) <= a.(!i) then begin i := !j; j := !j + 1; end else begin swap a (!i-1) (!i); i := !i - 1; if !i = 0 then begin i := !j; j := !j + 1; end; end; done; ;; val gnome_sort : 'a array -> unit = <fun>   # let a = [| 7; 9; 4; 2; 1; 3; 6; 5; 0; 8; |] ;; val a : int array = [|7; 9; 4; 2; 1; 3; 6; 5; 0; 8|]   # gnome_sort a ;; - : unit = ()   # a ;; - : int array = [|0; 1; 2; 3; 4; 5; 6; 7; 8; 9|]