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/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
#MATLAB_.2F_Octave
MATLAB / Octave
function list = cocktailSort(list)   %We have to do this because the do...while loop doesn't exist in MATLAB swapped = true;   while swapped   %Bubble sort down the list swapped = false; for i = (1:numel(list)-1) if( list(i) > list(i+1) ) list([i i+1]) = list([i+1 i]); %swap swapped = true; end end   if ~swapped break end   %Bubble sort up the list swapped = false; for i = (numel(list)-1:-1:1) if( list(i) > list(i+1) ) list([i i+1]) = list([i+1 i]); %swap swapped = true; end %if end %for end %while end %cocktail sort
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.
#Aime
Aime
file i, o; tcpip_connect(i, o, "127.0.0.1", 256, 0); i.text("hello socket world");
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#AutoHotkey
AutoHotkey
Network_Port = 256 Network_Address = 127.0.0.1 NewData := false DataReceived = GoSub, Connection_Init SendData(socket,"hello socket world") return   Connection_Init: OnExit, ExitSub   socket := ConnectToAddress(Network_Address, Network_Port) if socket = -1 ExitApp   Process, Exist DetectHiddenWindows On ScriptMainWindowId := WinExist("ahk_class AutoHotkey ahk_pid " . ErrorLevel) DetectHiddenWindows Off   NotificationMsg = 0x5556 OnMessage(NotificationMsg, "ReceiveData")   FD_READ = 1 FD_CLOSE = 32 if DllCall("Ws2_32\WSAAsyncSelect", "UInt", socket, "UInt", ScriptMainWindowId, "UInt", NotificationMsg, "Int", FD_READ|FD_CLOSE) { MsgBox % "WSAAsyncSelect() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError") ExitApp }   return     ConnectToAddress(IPAddress, Port) { VarSetCapacity(wsaData, 32) result := DllCall("Ws2_32\WSAStartup", "UShort", 0x0002, "UInt", &wsaData) if ErrorLevel { MsgBox WSAStartup() could not be called due to error %ErrorLevel%. Winsock 2.0 or higher is required. return -1 } if result { MsgBox % "WSAStartup() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError") return -1 } AF_INET = 2 SOCK_STREAM = 1 IPPROTO_TCP = 6 socket := DllCall("Ws2_32\socket", "Int", AF_INET, "Int", SOCK_STREAM, "Int", IPPROTO_TCP) if socket = -1 { MsgBox % "socket() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError") return -1 } SizeOfSocketAddress = 16 VarSetCapacity(SocketAddress, SizeOfSocketAddress) InsertInteger(2, SocketAddress, 0, AF_INET) InsertInteger(DllCall("Ws2_32\htons", "UShort", Port), SocketAddress, 2, 2) InsertInteger(DllCall("Ws2_32\inet_addr", "Str", IPAddress), SocketAddress, 4, 4) if DllCall("Ws2_32\connect", "UInt", socket, "UInt", &SocketAddress, "Int", SizeOfSocketAddress) { MsgBox % "connect() indicated Winsock error " . DllCall("Ws2_32\WSAGetLastError") . "?" return -1 } return socket }   ReceiveData(wParam, lParam) { global DataReceived global NewData socket := wParam ReceivedDataSize = 4096 Loop { VarSetCapacity(ReceivedData, ReceivedDataSize, 0) ReceivedDataLength := DllCall("Ws2_32\recv", "UInt", socket, "Str", ReceivedData, "Int", ReceivedDataSize, "Int", 0) if ReceivedDataLength = 0 ExitApp if ReceivedDataLength = -1 { WinsockError := DllCall("Ws2_32\WSAGetLastError") if WinsockError = 10035 { DataReceived = %TempDataReceived% NewData := true return 1 } if WinsockError <> 10054 MsgBox % "recv() indicated Winsock error " . WinsockError ExitApp } if (A_Index = 1) TempDataReceived = TempDataReceived = %TempDataReceived%%ReceivedData% } return 1 }   SendData(wParam,SendData) { socket := wParam SendDataSize := VarSetCapacity(SendData) SendDataSize += 1 sendret := DllCall("Ws2_32\send", "UInt", socket, "Str", SendData, "Int", SendDatasize, "Int", 0) }   InsertInteger(pInteger, ByRef pDest, pOffset = 0, pSize = 4) { Loop %pSize% DllCall("RtlFillMemory", "UInt", &pDest + pOffset + A_Index-1, "UInt", 1, "UChar", pInteger >> 8*(A_Index-1) & 0xFF) }   ReceiveProcedure: if NewData GuiControl, , ReceivedText, %DataReceived% NewData := false Return   ExitSub: DllCall("Ws2_32\WSACleanup") ExitApp
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
#Action.21
Action!
INCLUDE "D2:REAL.ACT" ;from the Action! Tool Kit   BYTE FUNC IsZero(REAL POINTER a) CHAR ARRAY s(10)   StrR(a,s) IF s(0)=1 AND s(1)='0 THEN RETURN (1) FI RETURN (0)   CARD FUNC MyMod(CARD a,b) REAL ar,br,dr CARD d,m   IF a>32767 THEN  ;Built-in DIV and MOD  ;do not work properly  ;for numbers greater than 32767 IntToReal(a,ar) IntToReal(b,br) RealDiv(ar,br,dr) d=RealToInt(dr) m=a-d*b ELSE m=a MOD b FI RETURN (m)   BYTE FUNC IsPrime(CARD a) CARD i   IF a<=1 THEN RETURN (0) FI   i=2 WHILE i*i<=a DO IF MyMod(a,i)=0 THEN RETURN (0) FI i==+1 OD RETURN (1)   BYTE FUNC AllDigitsArePrime(CARD a) BYTE i CHAR ARRAY s CHAR c   StrC(a,s) FOR i=1 TO s(0) DO c=s(i) IF c#'2 AND c#'3 AND c#'5 AND c#'7 THEN RETURN (0) FI OD RETURN (1)   PROC Main() BYTE count CARD a   Put(125) PutE() ;clear screen PrintE("Sequence from 1st to 25th:") count=0 a=1 DO IF AllDigitsArePrime(a)=1 AND IsPrime(a)=1 THEN count==+1 IF count<=25 THEN PrintC(a) Put(32) ELSEIF count=100 THEN PrintF("%E%E100th: %U%E",a) EXIT FI FI a==+1 OD RETURN
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
#ALGOL_68
ALGOL 68
# find elements of the Smarandache prime-digital sequence - primes whose # # digits are all primes # # Uses the observations that the final digit of 2 or more digit Smarandache # # primes must be 3 or 7 and the only prime digits are 2, 3, 5 and 7 # # Needs --heap 256m for Algol 68G # BEGIN # construct a sieve of primes up to 10 000 000 # INT prime max = 10 000 000; [ prime max ]BOOL prime; FOR i TO UPB prime DO prime[ i ] := TRUE OD; FOR s FROM 2 TO ENTIER sqrt( prime max ) DO IF prime[ s ] THEN FOR p FROM s * s BY s TO prime max DO prime[ p ] := FALSE OD FI OD; # consruct the Smarandache primes up to 10 000 000 # [ prime max ]BOOL smarandache; FOR i TO UPB prime DO smarandache[ i ] := FALSE OD; [ ]INT prime digits = ( 2, 3, 5, 7 ); [ 7 ]INT digits := ( 0, 0, 0, 0, 0, 0, 0 ); # tests whether the current digits form a Smarandache prime # PROC try smarandache = VOID: BEGIN INT possible prime := 0; FOR i TO UPB digits DO possible prime *:= 10 +:= digits[ i ] OD; smarandache[ possible prime ] := prime[ possible prime ] END # try smarandache # ; # tests whether the current digits plus 3 or 7 form a Smarandache prime # PROC try smarandache 3 or 7 = VOID: BEGIN digits[ UPB digits ] := 3; try smarandache; digits[ UPB digits ] := 7; try smarandache END # try smarandache 3 or 7 # ; # the 1 digit primes are all Smarandache primes # FOR d7 TO UPB prime digits DO smarandache[ prime digits[ d7 ] ] := TRUE OD; # try the possible 2, 3, etc. digit numbers composed of prime digits # FOR d6 TO UPB prime digits DO digits[ 6 ] := prime digits[ d6 ]; try smarandache 3 or 7; FOR d5 TO UPB prime digits DO digits[ 5 ] := prime digits[ d5 ]; try smarandache 3 or 7; FOR d4 TO UPB prime digits DO digits[ 4 ] := prime digits[ d4 ]; try smarandache 3 or 7; FOR d3 TO UPB prime digits DO digits[ 3 ] := prime digits[ d3 ]; try smarandache 3 or 7; FOR d2 TO UPB prime digits DO digits[ 2 ] := prime digits[ d2 ]; try smarandache 3 or 7; FOR d1 TO UPB prime digits DO digits[ 1 ] := prime digits[ d1 ]; try smarandache 3 or 7 OD; digits[ 1 ] := 0 OD; digits[ 2 ] := 0 OD; digits[ 3 ] := 0 OD; digits[ 4 ] := 0 OD; digits[ 5 ] := 0 OD; # print some Smarandache primes # INT count := 0; INT s100 := 0; INT s1000 := 0; INT s last := 0; INT p last := 0; print( ( "First 25 Smarandache primes:", newline ) ); FOR i TO UPB smarandache DO IF smarandache[ i ] THEN count +:= 1; s last := i; p last := count; IF count <= 25 THEN print( ( " ", whole( i, 0 ) ) ) ELIF count = 100 THEN s100 := i ELIF count = 1000 THEN s1000 := i FI FI OD; print( ( newline ) ); print( ( "100th Smarandache prime: ", whole( s100, 0 ), newline ) ); print( ( "1000th Smarandache prime: ", whole( s1000, 0 ), newline ) ); print( ( "Largest Smarandache prime under " , whole( prime max, 0 ) , ": " , whole( s last, 0 ) , " (Smarandache prime " , whole( p last, 0 ) , ")" , newline ) ) END
http://rosettacode.org/wiki/Sokoban
Sokoban
Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character array where space is an empty square # is a wall @ is the player $ is a box . is a goal + is the player on a goal * is a box on a goal ####### # # # # #. # # #. $$ # #.$$ # #.# @# ####### Sokoban solutions are usually stored in the LURD format, where lowercase l, u, r and d represent a move in that (left, up, right, down) direction and capital LURD represents a push. Please state if you use some other format for either the input or output, and why. For more information, see the Sokoban wiki.
#C.23
C#
using System.Collections.Generic; using System.Linq; using System.Text;   namespace SokobanSolver { public class SokobanSolver { private class Board { public string Cur { get; internal set; } public string Sol { get; internal set; } public int X { get; internal set; } public int Y { get; internal set; }   public Board(string cur, string sol, int x, int y) { Cur = cur; Sol = sol; X = x; Y = y; } }   private string destBoard, currBoard; private int playerX, playerY, nCols;   SokobanSolver(string[] board) { nCols = board[0].Length; StringBuilder destBuf = new StringBuilder(); StringBuilder currBuf = new StringBuilder();   for (int r = 0; r < board.Length; r++) { for (int c = 0; c < nCols; c++) {   char ch = board[r][c];   destBuf.Append(ch != '$' && ch != '@' ? ch : ' '); currBuf.Append(ch != '.' ? ch : ' ');   if (ch == '@') { this.playerX = c; this.playerY = r; } } } destBoard = destBuf.ToString(); currBoard = currBuf.ToString(); }   private string Move(int x, int y, int dx, int dy, string trialBoard) {   int newPlayerPos = (y + dy) * nCols + x + dx;   if (trialBoard[newPlayerPos] != ' ') return null;   char[] trial = trialBoard.ToCharArray(); trial[y * nCols + x] = ' '; trial[newPlayerPos] = '@';   return new string(trial); }   private string Push(int x, int y, int dx, int dy, string trialBoard) {   int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;   if (trialBoard[newBoxPos] != ' ') return null;   char[] trial = trialBoard.ToCharArray(); trial[y * nCols + x] = ' '; trial[(y + dy) * nCols + x + dx] = '@'; trial[newBoxPos] = '$';   return new string(trial); }   private bool IsSolved(string trialBoard) { for (int i = 0; i < trialBoard.Length; i++) if ((destBoard[i] == '.') != (trialBoard[i] == '$')) return false; return true; }   private string Solve() { char[,] dirLabels = { { 'u', 'U' }, { 'r', 'R' }, { 'd', 'D' }, { 'l', 'L' } }; int[,] dirs = { { 0, -1 }, { 1, 0 }, { 0, 1 }, { -1, 0 } }; ISet<string> history = new HashSet<string>(); LinkedList<Board> open = new LinkedList<Board>();   history.Add(currBoard); open.AddLast(new Board(currBoard, string.Empty, playerX, playerY));   while (!open.Count.Equals(0)) { Board item = open.First(); open.RemoveFirst(); string cur = item.Cur; string sol = item.Sol; int x = item.X; int y = item.Y;   for (int i = 0; i < dirs.GetLength(0); i++) { string trial = cur; int dx = dirs[i, 0]; int dy = dirs[i, 1];   // are we standing next to a box ? if (trial[(y + dy) * nCols + x + dx] == '$') { // can we push it ? if ((trial = Push(x, y, dx, dy, trial)) != null) { // or did we already try this one ? if (!history.Contains(trial)) {   string newSol = sol + dirLabels[i, 1];   if (IsSolved(trial)) return newSol;   open.AddLast(new Board(trial, newSol, x + dx, y + dy)); history.Add(trial); } } // otherwise try changing position } else if ((trial = Move(x, y, dx, dy, trial)) != null) { if (!history.Contains(trial)) { string newSol = sol + dirLabels[i, 0]; open.AddLast(new Board(trial, newSol, x + dx, y + dy)); history.Add(trial); } } } } return "No solution"; }   public static void Main(string[] a) { string level = "#######," + "# #," + "# #," + "#. # #," + "#. $$ #," + "#.$$ #," + "#.# @#," + "#######"; System.Console.WriteLine("Level:\n"); foreach (string line in level.Split(',')) { System.Console.WriteLine(line); } System.Console.WriteLine("\nSolution:\n"); System.Console.WriteLine(new SokobanSolver(level.Split(',')).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
#Icon_and_Unicon
Icon and Unicon
global nCells, cMap, best record Pos(r,c)   procedure main(A) puzzle := showPuzzle("Input",readPuzzle()) QMouse(puzzle,findStart(puzzle),&null,0) showPuzzle("Output", solvePuzzle(puzzle)) | write("No solution!") end   procedure readPuzzle() # Start with a reduced puzzle space p := [[-1],[-1]] nCells := maxCols := 0 every line := !&input do { put(p,[: -1 | -1 | gencells(line) | -1 | -1 :]) maxCols <:= *p[-1] } every put(p, [-1]|[-1]) # Now normalize all rows to the same length every i := 1 to *p do p[i] := [: !p[i] | (|-1\(maxCols - *p[i])) :] return p end   procedure gencells(s) static WS, NWS initial { NWS := ~(WS := " \t") cMap := table() # Map to/from internal model cMap["#"] := -1; cMap["_"] := 0 cMap[-1] := " "; cMap[0] := "_" }   s ? while not pos(0) do { w := (tab(many(WS))|"", tab(many(NWS))) | break w := numeric(\cMap[w]|w) if -1 ~= w then nCells +:= 1 suspend w } end   procedure showPuzzle(label, p) write(label," with ",nCells," cells:") every r := !p do { every c := !r do writes(right((\cMap[c]|c),*nCells+1)) write() } return p end   procedure findStart(p) if \p[r := !*p][c := !*p[r]] = 1 then return Pos(r,c) end   procedure solvePuzzle(puzzle) if path := \best then { repeat { loc := path.getLoc() puzzle[loc.r][loc.c] := path.getVal() path := \path.getParent() | break } return puzzle } end   class QMouse(puzzle, loc, parent, val)   method getVal(); return val; end method getLoc(); return loc; end method getParent(); return parent; end method atEnd(); return nCells = val; end   method visit(r,c) if /best & validPos(r,c) then return Pos(r,c) end   method validPos(r,c) v := val+1 xv := (0 <= puzzle[r][c]) | fail if xv = (v|0) then { # make sure this path hasn't already gone there ancestor := self while xl := (ancestor := \ancestor.getParent()).getLoc() do if (xl.r = r) & (xl.c = c) then fail return } end   initially val := val+1 if atEnd() then return best := self QMouse(puzzle, visit(loc.r-2,loc.c-1), self, val) QMouse(puzzle, visit(loc.r-2,loc.c+1), self, val) QMouse(puzzle, visit(loc.r-1,loc.c+2), self, val) QMouse(puzzle, visit(loc.r+1,loc.c+2), self, val) QMouse(puzzle, visit(loc.r+2,loc.c+1), self, val) QMouse(puzzle, visit(loc.r+2,loc.c-1), self, val) QMouse(puzzle, visit(loc.r+1,loc.c-2), self, val) QMouse(puzzle, visit(loc.r-1,loc.c-2), self, val) 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.
#Perl
Perl
use SOAP::Lite;   print SOAP::Lite -> service('http://example.com/soap/wsdl') -> soapFunc("hello"); print SOAP::Lite -> service('http://example.com/soap/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.
#Phix
Phix
-- -- demo\rosetta\SOAP.exw -- ===================== -- -- translated from https://gist.github.com/p120ph37/8281362ae9da042f3043 -- without js -- (libcurl) include builtins\libcurl.e include builtins\xml.e -- xml_encode() function write_callback(atom pData, integer size, nmemb, atom /*pUserdata*/) integer bytes_written = size*nmemb puts(1,peek({pData,bytes_written})) return bytes_written end function constant write_cb = call_back({'+',write_callback}) function compose_soap_frobnicate(string foo, bar, baz) return sprintf(""" <?xml version="1.0" encoding="utf-8"?> <soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> <soap:Body> <frobnicate xmlns="http://example.com/frobnicate"> <foo>%s</foo> <bar>%s</bar> <baz>%s</baz> </frobnicate> </soap:Body> </soap:Envelope>""",{xml_encode(foo),xml_encode(bar),xml_encode(baz)}) end function curl_global_init() atom curl = curl_easy_init() curl_easy_setopt(curl, CURLOPT_URL, "https://ameriwether.com/cgi-bin/info.pl") string soap = compose_soap_frobnicate("'Ein'", ">Zwei<", "\"Drei\"") curl_easy_setopt(curl, CURLOPT_POSTFIELDS, soap) curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC) curl_easy_setopt(curl, CURLOPT_USERNAME, "user") curl_easy_setopt(curl, CURLOPT_PASSWORD, "password") curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_cb) atom headers = NULL headers = curl_slist_append(headers, "Content-Type: text/xml; charset=utf-8") headers = curl_slist_append(headers, "SOAPAction: \"https://ameriwether.com/cgi-bin/info.pl/frobnicate\"") headers = curl_slist_append(headers, "Accept: text/plain") -- Example output easier to read as plain text. curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers) -- Make the example URL work even if your CA bundle is missing. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false) CURLcode res = curl_easy_perform(curl) if res!=CURLE_OK then printf(2, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res)) end if curl_slist_free_all(headers) curl_easy_cleanup(curl) curl_global_cleanup()
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
#Phix
Phix
with javascript_semantics sequence board integer limit, tries constant ROW = 1, COL = 2 constant moves = {{-2,-2},{-2,2},{2,-2},{2,2},{-3,0},{3,0},{0,-3},{0,3}} function solve(integer row, integer col, integer n) integer nrow, ncol tries+= 1 if n>limit then return 1 end if for move=1 to length(moves) do nrow = row+moves[move][ROW] ncol = col+moves[move][COL]*3 if nrow>=1 and nrow<=length(board) and ncol>=1 and ncol<=length(board[row]) and board[nrow][ncol]=' ' then board[nrow][ncol-1..ncol] = sprintf("%2d",n) if solve(nrow,ncol,n+1) then return 1 end if board[nrow][ncol-1..ncol] = " " end if end for return 0 end function procedure Hopido(sequence s, integer w, integer h) integer rx, ry atom t0 = time() board = split(s,'\n') limit = 0 for x=1 to h do for y=3 to w*3 by 3 do if board[x][y]='0' then board[x][y] = ' ' limit += 1 end if end for end for while 1 do rx = rand(h) ry = rand(w)*3 if board[rx][ry]=' ' then exit end if end while board[rx][ry] = '1' tries = 0 if solve(rx,ry,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 = """ . 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 . . .""" Hopido(board1,7,6)
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.
#Delphi
Delphi
program SortCompositeStructures;   {$APPTYPE CONSOLE}   uses SysUtils, Generics.Collections, Generics.Defaults;   type TStructurePair = record name: string; value: string; constructor Create(const aName, aValue: string); end;   constructor TStructurePair.Create(const aName, aValue: string); begin name := aName; value := aValue; end;   var lArray: array of TStructurePair; begin SetLength(lArray, 3); lArray[0] := TStructurePair.Create('dog', 'rex'); lArray[1] := TStructurePair.Create('cat', 'simba'); lArray[2] := TStructurePair.Create('horse', 'trigger');   TArray.Sort<TStructurePair>(lArray , TDelegatedComparer<TStructurePair>.Construct( function(const Left, Right: TStructurePair): Integer begin Result := CompareText(Left.Name, Right.Name); end)); end.
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.)
#Tcl
Tcl
proc countingsort {a {min ""} {max ""}} { # If either of min or max weren't given, compute them now if {$min eq ""} { set min [::tcl::mathfunc::min $a] } if {$max eq ""} { set max [::tcl::mathfunc::max $a] }   # Make the "array" of counters set count [lrepeat [expr {$max - $min + 1}] 0]   # Count the values in the input list foreach n $a { set idx [expr {$n - $min}] lincr count $idx }   # Build the output list set z 0 for {set i $min} {$i <= $max} {incr i} { set idx [expr {$i - $min}] while {[lindex $count $idx] > 0} { lset a $z $i incr z lincr count $idx -1 } } return $a }   # Helper that will increment an existing element of a list proc lincr {listname idx {value 1}} { upvar 1 $listname list lset list $idx [expr {[lindex $list $idx] + $value}] }   # Demo code for {set i 0} {$i < 50} {incr i} {lappend a [expr {1+ int(rand()*10)}]} puts $a puts [countingsort $a]
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).
#Groovy
Groovy
import java.util.stream.Collectors import java.util.stream.IntStream   class NoConnection { // adopted from Go static int[][] links = [ [2, 3, 4], // A to C,D,E [3, 4, 5], // B to D,E,F [2, 4], // D to C, E [5], // E to F [2, 3, 4], // G to C,D,E [3, 4, 5], // H to D,E,F ]   static int[] pegs = new int[8]   static void main(String[] args) { List<Integer> vals = IntStream.range(1, 9) .mapToObj({ it }) .collect(Collectors.toList())   while (true) { Collections.shuffle(vals) for (int i = 0; i < pegs.length; i++) { pegs[i] = vals.get(i) } if (solved()) { break } }   printResult() }   static boolean solved() { for (int i = 0; i < links.length; i++) { for (int peg : links[i]) { if (Math.abs(pegs[i] - peg) == 1) { return false } } } return true }   static void printResult() { println(" ${pegs[0]} ${pegs[1]}") println("${pegs[2]} ${pegs[3]} ${pegs[4]} ${pegs[5]}") println(" ${pegs[6]} ${pegs[7]}") } }
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
#Racket
Racket
#lang racket ;;; Used in my solutions of: ;;; "Solve a Hidato Puzzle" ;;; "Solve a Holy Knights Tour" ;;; "Solve a Numbrix Puzzle" ;;; "Solve a Hopido Puzzle"   ;;; As well as the solver being common, the solution renderer and input formats are common (provide  ;; Input: list of neighbour offsets  ;; Output: a solver function:  ;; Input: a puzzle  ;; Output: either the solved puzzle or #f if impossible solve-hidato-family  ;; Input: puzzle  ;; optional minimum cell width  ;; Output: a pretty string that can be printed puzzle->string)   ;; Cell values are: ;; zero? - unvisited ;; positive? - nth visitied ;; else - unvisitable. In the puzzle layout, it's a _. In the hash it's a -1, so we can care less ;; about number type checking. ;; A puzzle is a sequence of sequences of cell values ;; We work with a puzzle as a hash keyed on (cons row-num col-num)   ;; Take a puzzle and get a working hash of it (define (puzzle->hash p) (for*/hash (((r row-num) (in-parallel p (in-naturals))) ((v col-num) (in-parallel r (in-naturals))) #:when (integer? v)) (values (cons row-num col-num) v)))   ;; Takes a hash and recreates a vector of vectors puzzle (define (hash->puzzle h# (blank '_)) (define keys (hash-keys h#)) (define n-rows (add1 (car (argmax car keys)))) (define n-cols (add1 (cdr (argmax cdr keys)))) (for/vector #:length n-rows ((r n-rows)) (for/vector #:length n-cols ((c n-cols)) (hash-ref h# (cons r c) blank))))   ;; See "provide" section for description (define (puzzle->string p (w #f)) (match p [#f "unsolved"] [(? sequence? s) (define (max-n-digits p) (and p (add1 (order-of-magnitude (* (vector-length p) (vector-length (vector-ref p 0))))))) (define min-width (or w (max-n-digits p))) (string-join (for/list ((r s)) (string-join (for/list ((c r)) (~a c #:align 'right #:min-width min-width)) " ")) "\n")]))   (define ((solve-hidato-family neighbour-offsets) board) (define board# (puzzle->hash board))  ;; reverse mapping, will only take note of positive values (define targets# (for/hash ([(k v) (in-hash board#)] #:when (positive? v)) (values v k)))   (define (neighbours r.c) (for/list ((r+.c+ neighbour-offsets)) (match-define (list r+ c+) r+.c+) (match-define (cons r c ) r.c) (cons (+ r r+) (+ c c+))))    ;; Count the moves, rather than check for "no more zeros" in puzzle (define last-move (length (filter number? (hash-values board#))))    ;; Depth first solution of the puzzle (we have to go deep, it's where the solutions are! (define (inr-solve-pzl b# move r.c) (cond [(= move last-move) b#] ; no moves needed, so solved [else (define m++ (add1 move)) (for*/or ; check each neighbour as an option ((r.c+ (in-list (neighbours r.c))) #:when (equal? (hash-ref targets# move r.c) r.c) ; we're where we should be! #:when (match (hash-ref b# r.c+ -1) (0 #t) ((== m++) #t) (_ #f))) (inr-solve-pzl (hash-set b# r.c+ m++) m++ r.c+))]))   (define (solution-starting-at n) (define start-r.c (for/first (((k v) (in-hash board#)) #:when (= n v)) k)) (and start-r.c (inr-solve-pzl board# n start-r.c)))   (define sltn (cond [(solution-starting-at 1) => values]  ;; next clause starts from 0 for hopido [(solution-starting-at 0) => values]))   (and sltn (hash->puzzle sltn)))
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
#Raku
Raku
my @adjacent = [-1, 0], [ 0, -1], [ 0, 1], [ 1, 0]; put "\n" xx 60;   solveboard q:to/END/; __ __ __ __ __ __ __ __ __ __ __ 46 45 __ 55 74 __ __ __ 38 __ __ 43 __ __ 78 __ __ 35 __ __ __ __ __ 71 __ __ __ 33 __ __ __ 59 __ __ __ 17 __ __ __ __ __ 67 __ __ 18 __ __ 11 __ __ 64 __ __ __ 24 21 __ 1 2 __ __ __ __ __ __ __ __ __ __ __ END   # And put "\n" xx 60;   solveboard q:to/END/; 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 END     sub solveboard($board) { my $max = +$board.comb(/\w+/); my $width = $max.chars;   my @grid; my @known; my @neigh; my @degree;   @grid = $board.lines.map: -> $line { [ $line.words.map: { /^_/ ?? 0 !! /^\./ ?? Rat !! $_ } ] }   sub neighbors($y,$x --> List) { eager gather for @adjacent { my $y1 = $y + .[0]; my $x1 = $x + .[1]; take [$y1,$x1] if defined @grid[$y1][$x1]; } }   for ^@grid -> $y { for ^@grid[$y] -> $x { if @grid[$y][$x] -> $v { @known[$v] = [$y,$x]; } if @grid[$y][$x].defined { @neigh[$y][$x] = neighbors($y,$x); @degree[$y][$x] = +@neigh[$y][$x]; } } } print "\e[0H\e[0J";   my $tries = 0;   try_fill 1, @known[1];   sub try_fill($v, $coord [$y,$x] --> Bool) { return True if $v > $max; $tries++;   my $old = @grid[$y][$x];   return False if +$old and $old != $v; return False if @known[$v] and @known[$v] !eqv $coord;   @grid[$y][$x] = $v; # conjecture grid value   print "\e[0H"; # show conjectured board for @grid -> $r { say do for @$r { when Rat { ' ' x $width } when 0 { '_' x $width } default { .fmt("%{$width}d") } } }     my @neighbors = @neigh[$y][$x][];   my @degrees; for @neighbors -> \n [$yy,$xx] { my $d = --@degree[$yy][$xx]; # conjecture new degrees push @degrees[$d], n; # and categorize by degree }   for @degrees.grep(*.defined) -> @ties { for @ties.reverse { # reverse works better for this hidato anyway return True if try_fill $v + 1, $_; } }   for @neighbors -> [$yy,$xx] { ++@degree[$yy][$xx]; # undo degree conjectures }   @grid[$y][$x] = $old; # undo grid value conjecture return False; }   say "$tries tries"; }  
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#D.C3.A9j.C3.A0_Vu
Déjà Vu
!. sort [ 5 4 3 2 1 ]
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#E
E
[2,4,3,1,2].sort()
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Object identifiers (OID) Task Show how to sort a list of OIDs, in their natural sort order. Details An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number. Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields. Test case Input (list of strings) Output (list of strings) 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11150.3.4.0.1 Related tasks Natural sorting Sort using a custom comparator
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Flush ' empty stack of values Data "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.1", "1.3.6.1.4.1.11150.3.4.0.1" 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.11150.3.4.0" \\ Inventories of type queue can get same keys, and have sort where numbers (float type) as part of key count as numbers Inventory queue OID \\ prepare keys (replace dot to #) While not empty { Append OID, Replace$(".","#", letter$) } Sort Ascending OID n=Each(OID) a$="" While n { \\ replace # to dot a$+=Replace$("#",".", Eval$(n))+{ } } Clipboard a$ Report a$ } Checkit  
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
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
in = {"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"}; in = StringSplit[#, "."] & /@ in; in = Map[ToExpression, in, {2}]; Column[StringRiffle[ToString /@ #, "."] & /@ LexicographicSort[in]]
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
#Icon_and_Unicon
Icon and Unicon
  link sort # get the 'isort' procedure for sorting a list   procedure sortDisjoint (items, indices) indices := isort (indices) # sort indices into a list result := copy (items) values := [] every put (values, result[!indices]) values := isort (values) every result[!indices] := pop (values) return result end   procedure main () # set up and do the sort items := [7, 6, 5, 4, 3, 2, 1, 0] indices := set(7, 2, 8) # note, Icon lists 1-based result := sortDisjoint (items, indices) # display result every writes (!items || " ") write () every writes (!indices || " ") write () every writes (!result || " ") write () end  
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).
#Tcl
Tcl
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_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).
#TXR
TXR
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.
#Python
Python
  #python2 Code for Sorting 3 values a= raw_input("Enter values one by one ..\n1.").strip() b=raw_input("2.").strip() c=raw_input("3.").strip() if a>b : a,b = b,a if a>c: a,c = c,a if b>c: b,c = c,b print(str(a)+" "+str(b)+" "+str(c))  
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.
#Quackery
Quackery
[ stack ] is x [ stack ] is y [ stack ] is z   $ 'lions, tigers, and' x put $ 'bears, oh my!' y put $ '(from the "Wizard of OZ")' z put   x take y take z take 3 pack sortwith $> unpack z put y put x put   say " x = " x take echo$ cr say " y = " y take echo$ cr say " z = " z take echo$ cr   cr   77444 x put -12 y put 0 z put   x take y take z take 3 pack sortwith > unpack z put y put x put   say " x = " x take echo cr say " y = " y take echo cr say " z = " z take echo cr
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.
#MAXScript
MAXScript
fn myCmp str1 str2 = ( case of ( (str1.count < str2.count): 1 (str1.count > str2.count): -1 default:( -- String compare is case sensitive, name compare isn't. Hence... str1 = str1 as name str2 = str2 as name case of ( (str1 > str2): 1 (str1 < str2): -1 default: 0 ) ) ) )   strList = #("Here", "are", "some", "sample", "strings", "to", "be", "sorted") qSort strList myCmp print strList
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.
#min
min
("Here" "are" "some" "sample" "strings" "to" "be" "sorted") (((length) (length)) spread <) sort print
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
#Vlang
Vlang
fn main() { mut a := [170, 45, 75, -90, -802, 24, 2, 66] println("before: $a") comb_sort(mut a) println("after: $a") }   fn comb_sort(mut a []int) { if a.len < 2 { return } for gap := a.len; ; { if gap > 1 { gap = gap * 4 / 5 } mut swapped := false for i := 0; ; { if a[i] > a[i+gap] { a[i], a[i+gap] = a[i+gap], a[i] swapped = true } i++ if i+gap >= a.len { break } } if gap == 1 && !swapped { break } } }
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.
#Sidef
Sidef
func in_order(a) { return true if (a.len <= 1); var first = a[0]; a.ft(1).all { |elem| first <= elem  ? do { first = elem; true } : false } }   func bogosort(a) { a.shuffle! while !in_order(a); return a; }   var arr = 5.of{ 100.rand.int }; say "Before: #{arr}"; say "After: #{bogosort(arr)}";
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.
#ERRE
ERRE
  PROGRAM BUBBLE_SORT   DIM FLIPS%,N,J   DIM A%[100]   BEGIN   ! init random number generator RANDOMIZE(TIMER) ! fills array A% with random data FOR N=1 TO UBOUND(A%,1) DO A%[N]=RND(1)*256 END FOR ! sort array FLIPS%=TRUE WHILE FLIPS% DO FLIPS%=FALSE FOR N=1 TO UBOUND(A%,1)-1 DO IF A%[N]>A%[N+1] THEN SWAP(A%[N],A%[N+1]) FLIPS%=TRUE END IF END FOR END WHILE ! print sorted array FOR N=1 TO UBOUND(A%,1) DO PRINT(A%[N];) END FOR PRINT END PROGRAM  
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.
#Octave
Octave
function s = gnomesort(v) i = 2; j = 3; while ( i <= length(v) ) if ( v(i-1) <= v(i) ) i = j; j++; else t = v(i-1); v(i-1) = v(i); v(i) = t; i--; if ( i == 1 ) i = j; j++; endif endif endwhile s = v; endfunction
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
#MAXScript
MAXScript
fn cocktailSort arr = ( local swapped = true while swapped do ( swapped = false for i in 1 to (arr.count-1) do ( if arr[i] > arr[i+1] then ( swap arr[i] arr[i+1] swapped = true ) ) if not swapped then exit for i in (arr.count-1) to 1 by -1 do ( if arr[i] > arr[i+1] then ( swap arr[i] arr[i+1] swapped = true ) ) ) return arr )
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.
#AutoIt
AutoIt
Func _HelloWorldSocket() TCPStartup() $Socket = TCPConnect("127.0.0.1", 256) TCPSend($Socket, "Hello World") TCPCloseSocket($Socket) TCPShutdown() EndFunc
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.
#AWK
AWK
BEGIN { s="/inet/tcp/256/0/0" print strftime() |& s close(s) }  
http://rosettacode.org/wiki/Sleeping_Beauty_problem
Sleeping Beauty problem
Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss. If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to estimate the probability that the coin toss was heads. Her estimate is recorded and she is then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied. If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to estimate the probability the coin toss was heads, but is then given a drug which makes her forget that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday. Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always estimate the probability of heads as 1/2, since she does not have any additional information. Others have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate should be 1/3 heads. Task Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty is asked the question.
#11l
11l
F sleeping_beauty_experiment(repetitions) ‘ Run the Sleeping Beauty Problem experiment `repetitions` times, checking to see how often we had heads on waking Sleeping Beauty. ’ V gotheadsonwaking = 0 V wakenings = 0 L 0 .< repetitions V coin_result = random:choice([‘heads’, ‘tails’])   // On Monday, we check if we got heads. wakenings++ I coin_result == ‘heads’ gotheadsonwaking++   // If tails, we do this again, but of course we will not add as if it was heads.. I coin_result == ‘tails’ wakenings++ I coin_result == ‘heads’ gotheadsonwaking++ // never done   print(‘Wakenings over ’repetitions‘ experiments: ’wakenings)   R Float(gotheadsonwaking) / wakenings   V CREDENCE = sleeping_beauty_experiment(1'000'000) print(‘Results of experiment: Sleeping Beauty should estimate a credence of: ’CREDENCE)
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
#AWK
AWK
  # syntax: GAWK -f SMARANDACHE_PRIME-DIGITAL_SEQUENCE.AWK BEGIN { limit = 25 printf("1-%d:",limit) while (1) { if (is_prime(++n)) { if (all_digits_prime(n) == 1) { if (++count <= limit) { printf(" %d",n) } if (count == 100) { printf("\n%d: %d\n",count,n) break } } } } exit(0) } function all_digits_prime(n, i) { for (i=1; i<=length(n); i++) { if (!is_prime(substr(n,i,1))) { return(0) } } return(1) } function is_prime(x, i) { if (x <= 1) { return(0) } for (i=2; i<=int(sqrt(x)); i++) { if (x % i == 0) { return(0) } } return(1) }  
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
#BASIC256
BASIC256
arraybase 1 dim smar(100) smar[1] = 2   cont = 1 i = 1   print 1, 2 while cont < 100 i += 2 if not isPrime(i) then continue while for j = 1 to length(string(i)) digit = int(mid(string(i),j,1)) if not isPrime(digit) then continue while next j cont += 1 smar[cont] = i if cont = 100 or cont <= 25 then print cont, smar[cont] end while end   function isPrime(v) if v < 2 then return False if v mod 2 = 0 then return v = 2 if v mod 3 = 0 then return v = 3 d = 5 while d * d <= v if v mod d = 0 then return False else d += 2 end while return True end function
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.2B.2B
C++
#include <iostream> #include <string> #include <vector> #include <queue> #include <regex> #include <tuple> #include <set> #include <array> using namespace std;   class Board { public: vector<vector<char>> sData, dData; int px, py;   Board(string b) { regex pattern("([^\\n]+)\\n?"); sregex_iterator end, iter(b.begin(), b.end(), pattern);   int w = 0; vector<string> data; for(; iter != end; ++iter){ data.push_back((*iter)[1]); w = max(w, (*iter)[1].length()); }   for(int v = 0; v < data.size(); ++v){ vector<char> sTemp, dTemp; for(int u = 0; u < w; ++u){ if(u > data[v].size()){ sTemp.push_back(' '); dTemp.push_back(' '); }else{ char s = ' ', d = ' ', c = data[v][u];   if(c == '#') s = '#'; else if(c == '.' || c == '*' || c == '+') s = '.';   if(c == '@' || c == '+'){ d = '@'; px = u; py = v; }else if(c == '$' || c == '*') d = '*';   sTemp.push_back(s); dTemp.push_back(d); } }   sData.push_back(sTemp); dData.push_back(dTemp); } }   bool move(int x, int y, int dx, int dy, vector<vector<char>> &data) { if(sData[y+dy][x+dx] == '#' || data[y+dy][x+dx] != ' ') return false;   data[y][x] = ' '; data[y+dy][x+dx] = '@';   return true; }   bool push(int x, int y, int dx, int dy, vector<vector<char>> &data) { if(sData[y+2*dy][x+2*dx] == '#' || data[y+2*dy][x+2*dx] != ' ') return false;   data[y][x] = ' '; data[y+dy][x+dx] = '@'; data[y+2*dy][x+2*dx] = '*';   return true; }   bool isSolved(const vector<vector<char>> &data) { for(int v = 0; v < data.size(); ++v) for(int u = 0; u < data[v].size(); ++u) if((sData[v][u] == '.') ^ (data[v][u] == '*')) return false; return true; }   string solve() { set<vector<vector<char>>> visited; queue<tuple<vector<vector<char>>, string, int, int>> open;   open.push(make_tuple(dData, "", px, py)); visited.insert(dData);   array<tuple<int, int, char, char>, 4> dirs; dirs[0] = make_tuple(0, -1, 'u', 'U'); dirs[1] = make_tuple(1, 0, 'r', 'R'); dirs[2] = make_tuple(0, 1, 'd', 'D'); dirs[3] = make_tuple(-1, 0, 'l', 'L');   while(open.size() > 0){ vector<vector<char>> temp, cur = get<0>(open.front()); string cSol = get<1>(open.front()); int x = get<2>(open.front()); int y = get<3>(open.front()); open.pop();   for(int i = 0; i < 4; ++i){ temp = cur; int dx = get<0>(dirs[i]); int dy = get<1>(dirs[i]);   if(temp[y+dy][x+dx] == '*'){ if(push(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){ if(isSolved(temp)) return cSol + get<3>(dirs[i]); open.push(make_tuple(temp, cSol + get<3>(dirs[i]), x+dx, y+dy)); visited.insert(temp); } }else if(move(x, y, dx, dy, temp) && (visited.find(temp) == visited.end())){ if(isSolved(temp)) return cSol + get<2>(dirs[i]); open.push(make_tuple(temp, cSol + get<2>(dirs[i]), x+dx, y+dy)); visited.insert(temp); } } }   return "No solution"; } };   int main() { string level = "#######\n" "# #\n" "# #\n" "#. # #\n" "#. $$ #\n" "#.$$ #\n" "#.# @#\n" "#######";   Board b(level);   cout << level << endl << endl << b.solve() << endl; 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
#J
J
9!:21]2^34   unpack=:verb define mask=. +./' '~:y board=. (255 0 1{a.) {~ {.@:>:@:"."0 mask#"1 y )   ex1=:unpack ];._2]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 1 0 0 0 0 0 0 0 0 0 0 0 0 )   solve=:verb define board=.,:y for_move.1+i.+/({.a.)=,y do. board=. ;move <@knight"2 board end. )   kmoves=: ,/(2 1,:1 2)*"1/_1^#:i.4   knight=:dyad define pos=. ($y)#:(,y)i.x{a. moves=. <"1(#~ 0&<: */"1@:* ($y)&>"1)pos+"1 kmoves moves=. (#~ (0{a.)={&y) moves moves y adverb def (':';'y x} m')"0 (x+1){a. )
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.
#PHP
PHP
<?php //load the wsdl file $client = new SoapClient("http://example.com/soap/definition.wsdl"); //functions are now available to be called $result = $client->soapFunc("hello"); $result = $client->anotherSoapFunc(34234);   //SOAP Information $client = new SoapClient("http://example.com/soap/definition.wsdl"); //list of SOAP types print_r($client->__getTypes()); //list if SOAP Functions print_r($client->__getFunctions()); ?>
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.
#PureBasic
PureBasic
  XIncludeFile "COMatePLUS.pbi" Define.COMateObject soapObject = COMate_CreateObject("MSSOAP.SoapClient") soapObject\Invoke("MSSoapInit('http://example.com/soap/wsdl')") result = soapObject\Invoke("soapFunc('hello')") result2 = soapObject\Invoke("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.
#Python
Python
from SOAPpy import WSDL proxy = WSDL.Proxy("http://example.com/soap/wsdl") result = proxy.soapFunc("hello") result = proxy.anotherSoapFunc(34234)
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
#Picat
Picat
  import sat. main => Grid = {{0,1,1,0,1,1,0}, {1,1,1,1,1,1,1}, {1,1,1,1,1,1,1}, {0,1,1,1,1,1,0}, {0,0,1,1,1,0,0}, {0,0,0,1,0,0,0}}, NR = len(Grid), NC = len(Grid[1]), Es = [{(R,C), (R1,C1), _} : R in 1..NR, C in 1..NC, R1 in 1..NR, C1 in 1..NC, % Edges ((R1 = R, abs(C1 - C) = 3); (C1 = C, abs(R1 - R) = 3); % horizontal hop (abs(R1 - R) = 2, abs(C1 - C) = 2)),  % diagonal hop Grid[R,C] = 1, Grid[R1,C1] = 1], hcp_grid(Grid, Es), % find a Hamiltion cylce on the vertices in Grid through the edges in Es solve(vars(Es)),  % Write the solution as a matrix, starting at the base tile 6|4: M = {{0: _ in 1..NC} : _ in 1..NR}, R1 = 6, C1 = 4, I = 0, do I := I + 1, M[R1,C1] := I, Stop = 0, foreach({(R1,C1), (R2,C2), 1} in Es, break(Stop == 1)) R1 := R2, C1 := C2, Stop := 1 end while ((R1,C1) != (6,4)), foreach(R in 1..NR, C in 1..NC) if M[R,C] = 0 then print(" ") else printf("%2d ", M[R,C]) end, if C = NC then nl end end.  
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
#Prolog
Prolog
hopido(Grid,[C|Solved],Xs,Ys) :- select(C,Grid,RGrid), solve(RGrid,C,Solved,Xs,Ys).   solve([],_,[],_,_). solve(Grid,p(X,Y),[p(X1,Y1)|R],Xs,Ys) :- valid_move(X,Y,Xs,Ys,X1,Y1), select(p(X1,Y1),Grid,NextGrid), solve(NextGrid,p(X1,Y1),R,Xs,Ys).   valid_move(X,Y,Xs,_,X1,Y) :- j3(X,X1,Xs). % right (3,0) valid_move(X,Y,Xs,_,X1,Y) :- j3(X1,X,Xs). % left (-3,0) valid_move(X,Y,_,Ys,X,Y1) :- j3(Y,Y1,Ys). % up (0,3). valid_move(X,Y,_,Ys,X,Y1) :- j3(Y1,Y,Ys). % down (0,-3). valid_move(X,Y,Xs,Ys,X1,Y1) :- j2(X,X1,Xs), j2(Y,Y1,Ys). % up-right (2,2). valid_move(X,Y,Xs,Ys,X1,Y1) :- j2(X1,X,Xs), j2(Y,Y1,Ys). % up-left (-2,2). valid_move(X,Y,Xs,Ys,X1,Y1) :- j2(X1,X,Xs), j2(Y1,Y,Ys). % down-left (-2,-2). valid_move(X,Y,Xs,Ys,X1,Y1) :- j2(X,X1,Xs), j2(Y1,Y,Ys). % down-right (2,-2).   j2(O,N,[O,_,N|_]). j2(O,N,[_|T]) :- j2(O,N,T).   j3(O,N,[O,_,_,N|_]). j3(O,N,[_|T]) :- j3(O,N,T).
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.
#E
E
def compareBy(keyfn) { # This ought to be in the standard library return def comparer(a, b) { return keyfn(a).op__cmp(keyfn(b)) } }   def x := [ ["Joe",3], ["Bill",4], ["Alice",20], ["Harry",3], ]   println(x.sort(compareBy(fn [name,_] { name })))
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.)
#VBA
VBA
Option Base 1 Private Function countingSort(array_ As Variant, mina As Long, maxa As Long) As Variant Dim count() As Integer ReDim count(maxa - mina + 1) For i = 1 To UBound(array_) count(array_(i) - mina + 1) = count(array_(i) - mina + 1) + 1 Next i Dim z As Integer: z = 1 For i = mina To maxa For j = 1 To count(i - mina + 1) array_(z) = i z = z + 1 Next j Next i countingSort = array_ End Function   Public Sub main() s = [{5, 3, 1, 7, 4, 1, 1, 20}] Debug.Print Join(countingSort(s, WorksheetFunction.Min(s), WorksheetFunction.Max(s)), ", ") End Sub
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).
#Haskell
Haskell
import Data.List (permutations)   solution :: [Int] solution@(a : b : c : d : e : f : g : h : _) = head $ filter isSolution (permutations [1 .. 8]) where isSolution :: [Int] -> Bool isSolution (a : b : c : d : e : f : g : h : _) = all ((> 1) . abs) $ zipWith (-) [a, c, g, e, a, c, g, e, b, d, h, f, b, d, h, f] [d, d, d, d, c, g, e, a, e, e, e, e, d, h, f, b]   main :: IO () main = (putStrLn . unlines) $ unlines ( zipWith (\x y -> x : (" = " <> show y)) ['A' .. 'H'] solution ) : ( rightShift . unwords . fmap show <$> [[], [a, b], [c, d, e, f], [g, h]] ) where rightShift s | length s > 3 = s | otherwise = " " <> s
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
#REXX
REXX
/*REXX program solves a Numbrix (R) puzzle, it also displays the puzzle and solution. */ maxR= 0; maxC= 0; maxX= 0; /*define maxR, maxC, and maxX. */ minR= 9e9; minC= 9e9; minX= 9e9; /* " minR, minC, " minX. */ cells= 0 /*the number of cells (so far). */ parse arg xxx /*get the cell definitions from the CL.*/ xxx=translate(xxx, ',,,,,' , "/\;:_") /*also allow other characters as comma.*/ @.= do while xxx\=''; parse var xxx r c marks ',' xxx do while marks\=''; [email protected] parse var marks x marks if datatype(x, 'N') then x= abs(x) / 1 /*normalize │x│ */ minR= min(minR, r); minC= min(minC, c) /*find min R and C*/ maxR= max(maxR, r); maxC= max(maxC, c) /* " max " " "*/ if x==1 then do;  !r= r;  !c= c /*the START cell. */ end if _\=='' then call err "cell at" r c 'is already occupied with:' _ @.r.c= x; c= c +1; cells= cells + 1 /*assign a mark. */ if x==. then iterate /*is a hole? Skip*/ if \datatype(x,'W') then call err 'illegal marker specified:' x minX= min(minX, x); maxX= max(maxX, x) /*min & max X.*/ end /*while marks\='' */ end /*while xxx \='' */ call show /* [↓] is used for making fast moves. */ Nr = '0 1 0 -1 -1 1 1 -1' /*possible row for the next move. */ Nc = '1 0 -1 0 1 -1 1 -1' /* " column " " " " */ pMoves= words(Nr) - 4 /*is this to be a Numbrix puzzle ? */   do i=1 for pMoves; Nr.i= word(Nr, i); Nc.i= word(Nc, i) /*for fast moves. */ end /*i*/ say if \next(2, !r, !c) then call err 'No solution possible for this Numbrix puzzle.' say 'A solution for the Numbrix puzzle exists.'; say; call show exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ err: say; say '***error*** (from Numbrix puzzle): ' arg(1); say; exit 13 /*──────────────────────────────────────────────────────────────────────────────────────*/ next: procedure expose @. Nr. Nc. cells pMoves; parse arg #,r,c; ##= # + 1 do t=1 for pMoves /* [↓] try some moves. */ parse value r+Nr.t c+Nc.t with nr nc /*next move coördinates.*/ if @.nr.nc==. then do; @.nr.nc= # /*let's try this move. */ if #==cells then return 1 /*is this the last move?*/ if next(##, nr, nc) then return 1 @.nr.nc=. /*undo the above move. */ iterate /*go & try another move.*/ end if @.nr.nc==# then do /*this a fill─in move ? */ if #==cells then return 1 /*this is the last move.*/ if next(##, nr, nc) then return 1 /*a fill─in move. */ end end /*t*/ return 0 /*this ain't working. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ show: if maxR<1 | maxC<1 then call err 'no legal cell was specified.' if minX<1 then call err 'no 1 was specified for the puzzle start' w= max(2, length(cells) ); do r=maxR to minR by -1; _= do c=minC to maxC; _= _ right(@.r.c, w) end /*c*/ say _ end /*r*/ say; return
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.
#EGL
EGL
program SortExample   function main() test1 int[] = [1,-1,8,-8,2,-2,7,-7,3,-3,6,-6,9,-9,4,-4,5,-5,0]; test1.sort(sortFunction);   for(i int from 1 to test1.getSize()) SysLib.writeStdout(test1[i]); end end   function sortFunction(a any in, b any in) returns (int) return (a as int) - (b as int); end   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.
#Elena
Elena
import system'routines; import extensions;   public program() { var unsorted := new int[]{6, 2, 7, 8, 3, 1, 10, 5, 4, 9};   console.printLine(unsorted.clone().sort(ifOrdered).asEnumerable()) }
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
#Nim
Nim
import algorithm, sequtils, strutils   type OID = distinct string   # Borrow the `$` procedure from the base string type. proc `$`(oid: OID): string {.borrow.}     template toSeqInt(oid: OID): seq[int] = ## Convert an OID into a sequence of integers. oid.string.split('.').map(parseInt)     proc oidCmp(a, b: OID): int = ## Compare two OIDs. Return 0 if OIDs are equal, -1 if the first is ## less than the second, +1 is the first is greater than the second. let aseq = a.toSeqInt let bseq = b.toSeqInt for i in 0..<min(aseq.len, bseq.len): result = cmp(aseq[i], bseq[i]) if result != 0: return result = cmp(aseq.len, bseq.len)     when isMainModule:   const OIDS = [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"]   for oid in OIDS.sorted(oidCmp): echo oid
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
#Perl
Perl
my @OIDs = qw( 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 );   my @sorted = map { $_->[0] } sort { $a->[1] cmp $b->[1] } map { [$_, join '', map { sprintf "%8d", $_ } split /\./, $_] } @OIDs;   print "$_\n" for @sorted;
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
#Io
Io
List disjointSort := method(indices, sortedIndices := indices unique sortInPlace sortedValues := sortedIndices map(idx,at(idx)) sortInPlace sortedValues foreach(i,v,atPut(sortedIndices at(i),v)) self )   list(7,6,5,4,3,2,1,0) disjointSort(list(6,1,7)) println
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).
#Wren
Wren
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.
#R
R
  #lang R   assignVec <- Vectorize("assign", c("x", "value")) `%<<-%` <- function(x, value) invisible(assignVec(x, value, envir = .GlobalEnv)) # define multiple global assignments operator  
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.
#Racket
Racket
#lang racket   (define-syntax-rule (sort-3! x y z <?) (begin (define-syntax-rule (swap! x y) (let ((tmp x)) (set! x y) (set! y tmp))) (define-syntax-rule (sort-2! x y) (when (<? y x) (swap! x y))) (sort-2! x y) (sort-2! x z) (sort-2! y z)))   (module+ test (require rackunit data/order)   (define (test-permutations l <?) (test-case (format "test-permutations ~a" (object-name <?)) (for ((p (in-permutations l))) (match-define (list a b c) p) (sort-3! a b c <?) (check-equal? (list a b c) l))))   (test-permutations '(1 2 3) <)    ;; string sorting (let ((x "lions, tigers, and") (y "bears, oh my!") (z "(from the \"Wizard of OZ\")")) (sort-3! x y z string<?) (for-each displayln (list x y z)))   (newline)    ;; general data sorting (define datum<? (order-<? datum-order)) (let ((x "lions, tigers, and") (y "bears, oh my!") (z '(from the "Wizard of OZ"))) (sort-3! x y z datum<?) (for-each displayln (list x y z))))
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length. Use a sorting facility provided by the language/library, combined with your own callback comparison function. Note:   Lexicographic order is case-insensitive.
#Nemerle
Nemerle
using System.Console;   module CustomSort { Main() : void { def strings1 = ["these", "are", "strings", "of", "different", "length"]; def strings2 = ["apple", "House", "chewy", "Salty", "rises", "Later"];   WriteLine(strings1.Sort((x, y) => y.Length.CompareTo(x.Length))); WriteLine(strings2.Sort((x, y) => x.CompareTo(y))) } }
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.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   -- ============================================================================= class RSortCustomComparator public   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static sample = [String 'Here', 'are', 'some', 'sample', 'strings', 'to', 'be', 'sorted'] say displayArray(sample) Arrays.sort(sample, LengthComparator()) say displayArray(sample) return   method displayArray(harry = String[]) constant disp = '' loop elmt over harry disp = disp','elmt end elmt return '['disp.substr(2)']' -- trim leading comma   -- ============================================================================= class RSortCustomComparator.LengthComparator implements Comparator   method compare(lft = Object, rgt = Object) public binary returns int cRes = int if lft <= String, rgt <= String then do cRes = (String rgt).length - (String lft).length if cRes == 0 then cRes = (String lft).compareToIgnoreCase(String rgt) end else signal IllegalArgumentException('Arguments must be Strings') return cRes  
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
#Wren
Wren
var combSort = Fn.new { |a| var gap = a.count while (true) { gap = (gap/1.25).floor if (gap < 1) gap = 1 var i = 0 var swaps = false while (true) { if (a[i] > a[i+gap]) { var t = a[i] a[i] = a[i+gap] a[i+gap] = t swaps = true } i = i + 1 if (i + gap >= a.count) break } if (gap == 1 && !swaps) return } }   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)") combSort.call(a) System.print("After : %(a)") System.print() }
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.
#Scheme
Scheme
(import (rnrs base (6)) (srfi :27 random-bits))   (define (shuffle lst) (define (swap! vec i j) (let ((tmp (vector-ref vec i))) (vector-set! vec i (vector-ref vec j)) (vector-set! vec j tmp))) (define vec (list->vector lst)) (let loop ((i (sub1 (vector-length vec)))) (unless (zero? i) (swap! vec i (random-integer (add1 i))) (loop (sub1 i)))) (vector->list vec))   (define (sorted? lst pred?) (cond ((null? (cdr lst)) #t) ((pred? (car lst) (cadr lst)) (sorted? (cdr lst) pred?)) (else #f)))   (define (bogosort lst) (if (sorted? lst <) lst (bogosort (shuffle lst))))     (let ((input '(5 4 3 2 1))) (display "Input: ") (display input) (newline) (display "Output: ") (display (bogosort input)) (newline))
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.
#Euphoria
Euphoria
function bubble_sort(sequence s) object tmp integer changed for j = length(s) to 1 by -1 do changed = 0 for i = 1 to j-1 do if compare(s[i], s[i+1]) > 0 then tmp = s[i] s[i] = s[i+1] s[i+1] = tmp changed = 1 end if end for if not changed then exit end if end for return s end function   include misc.e constant s = {4, 15, "delta", 2, -31, 0, "alfa", 19, "gamma", 2, 13, "beta", 782, 1}   puts(1,"Before: ") pretty_print(1,s,{2}) puts(1,"\nAfter: ") pretty_print(1,bubble_sort(s),{2})
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.
#ooRexx
ooRexx
/* Rexx */   call demo return exit   -- ----------------------------------------------------------------------------- -- Gnome sort implementation -- ----------------------------------------------------------------------------- ::routine gnomeSort use arg ra, sAsc = '' if sAsc = '' then sAsc = isTrue()   sDsc = \sAsc -- Ascending/descending switches i_ = 1 j_ = 2 loop label i_ while i_ < ra~items() ctx = (ra~get(i_ - 1))~compareTo(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   -- ----------------------------------------------------------------------------- -- Demonstrate the implementation -- ----------------------------------------------------------------------------- ::routine demo placesList = .nlist~of( - "UK London", "US New York", "US Boston", "US Washington" - , "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" - )   lists = .nlist~of( - placesList - , gnomeSort(placesList~copy()) - )   loop ln = 0 to lists~items() - 1 cl = lists[ln] loop ct = 0 to cl~items() - 1 say right(ct + 1, 3)':' cl[ct] end ct say end ln   i_.0 = 3 i_.1 = .nlist~of(3, 3, 1, 2, 4, 3, 5, 6) i_.2 = gnomeSort(i_.1~copy(), isTrue()) i_.3 = gnomeSort(i_.1~copy(), isFalse()) loop s_ = 1 to i_.0 ss = '' loop x_ = 0 to i_.s_~items() - 1 ss ||= right(i_.s_~get(x_), 3)' ' end x_ say strip(ss, 'T') end s_   return   -- ----------------------------------------------------------------------------- ::routine isTrue return 1 == 1   -- ----------------------------------------------------------------------------- ::routine isFalse return \isTrue()   -- ----------------------------------------------------------------------------- -- Helper class. Map get and set methods for easier conversion from java.util.List -- ----------------------------------------------------------------------------- ::class NList mixinclass List public   -- Map get() to at() ::method get use arg ix return self~at(ix)   -- Map set() to put() ::method set use arg ix, item self~put(item, ix) return  
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
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols binary   placesList = [String - "UK London", "US New York" - , "US Boston", "US Washington" - , "UK Washington", "US Birmingham" - , "UK Birmingham", "UK Boston" - ] sortedList = cocktailSort(String[] Arrays.copyOf(placesList, placesList.length))   lists = [placesList, sortedList] loop ln = 0 to lists.length - 1 cl = lists[ln] loop ct = 0 to cl.length - 1 say cl[ct] end ct say end ln   return   method cocktailSort(A = String[]) public constant binary returns String[]   Alength = A.length swapped = isFalse loop label swapped until \swapped swapped = isFalse loop i_ = 0 to Alength - 2 if A[i_].compareTo(A[i_ + 1]) > 0 then do swap = A[i_ + 1] A[i_ + 1] = A[i_] A[i_] = swap swapped = isTrue end end i_ if \swapped then do leave swapped end swapped = isFalse loop i_ = Alength - 2 to 0 by -1 if A[i_].compareTo(A[i_ + 1]) > 0 then do swap = A[i_ + 1] A[i_ + 1] = A[i_] A[i_] = swap swapped = isTrue end end i_ end swapped   return A   method isTrue public constant binary returns boolean return 1 == 1   method isFalse public constant binary returns boolean return \isTrue
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.
#BBC_BASIC
BBC BASIC
INSTALL @lib$+"SOCKLIB" PROC_initsockets   socket% = FN_tcpconnect("localhost", "256") IF socket% <=0 ERROR 100, "Failed to open socket"   REM Don't use FN_writesocket since an error is expected msg$ = "hello socket world" SYS `send`, socket%, !^msg$, LEN(msg$), 0 TO result%   PROC_closesocket(socket%) PROC_exitsockets
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.
#C
C
#include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h>   const char *msg = "hello socket world";   int main() { int i, sock, len, slen;   struct addrinfo hints, *addrs; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM;   if (0 == getaddrinfo("localhost", "256", &hints, &addrs)) { sock = socket(addrs->ai_family, addrs->ai_socktype, addrs->ai_protocol); if ( sock >= 0 ) { if ( connect(sock, addrs->ai_addr, addrs->ai_addrlen) >= 0 ) { const char *pm = msg; do { len = strlen(pm); slen = send(sock, pm, len, 0); pm += slen; } while ((0 <= slen) && (slen < len)); } close(sock); } freeaddrinfo(addrs); } }
http://rosettacode.org/wiki/Sleeping_Beauty_problem
Sleeping Beauty problem
Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss. If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to estimate the probability that the coin toss was heads. Her estimate is recorded and she is then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied. If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to estimate the probability the coin toss was heads, but is then given a drug which makes her forget that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday. Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always estimate the probability of heads as 1/2, since she does not have any additional information. Others have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate should be 1/3 heads. Task Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty is asked the question.
#Arturo
Arturo
sleepingBeauty: function [reps][ wakings: 0 heads: 0 do.times: reps [ coin: random 0 1 wakings: wakings + 1 if? coin = 0 -> heads: heads + 1 else -> wakings: wakings + 1 ] print ["Wakings over" reps "repetitions =" wakings] return 100.0 * heads//wakings ]   pc: sleepingBeauty 100000 print ["Percentage probability of heads on waking =" pc "%"]
http://rosettacode.org/wiki/Sleeping_Beauty_problem
Sleeping Beauty problem
Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss. If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to estimate the probability that the coin toss was heads. Her estimate is recorded and she is then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied. If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to estimate the probability the coin toss was heads, but is then given a drug which makes her forget that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday. Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always estimate the probability of heads as 1/2, since she does not have any additional information. Others have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate should be 1/3 heads. Task Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty is asked the question.
#BASIC
BASIC
  iteraciones = 1000000 cara = 0 dormir = 0   for i = 1 to iteraciones lanza_moneda = int(rand * 2) dormir = dormir + 1 if lanza_moneda = 1 then cara = cara + 1 else dormir = dormir + 1 end if next i   print "Wakings over "; iteraciones; " repetitions = "; dormir print "Percentage probability of heads on waking = "; (cara/dormir*100); "%" end  
http://rosettacode.org/wiki/Sleeping_Beauty_problem
Sleeping Beauty problem
Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss. If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to estimate the probability that the coin toss was heads. Her estimate is recorded and she is then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied. If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to estimate the probability the coin toss was heads, but is then given a drug which makes her forget that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday. Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always estimate the probability of heads as 1/2, since she does not have any additional information. Others have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate should be 1/3 heads. Task Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty is asked the question.
#C.2B.2B
C++
#include <iostream> #include <random>   int main() { std::cout.imbue(std::locale("")); const int experiments = 1000000; std::random_device dev; std::default_random_engine engine(dev()); std::uniform_int_distribution<int> distribution(0, 1); int heads = 0, wakenings = 0; for (int i = 0; i < experiments; ++i) { ++wakenings; switch (distribution(engine)) { case 0: // heads ++heads; break; case 1: // tails ++wakenings; break; } } std::cout << "Wakenings over " << experiments << " experiments: " << wakenings << '\n'; std::cout << "Sleeping Beauty should estimate a credence of: " << double(heads) / wakenings << '\n'; }
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also OEIS A019546: Primes whose digits are primes. https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
#C
C
#include <locale.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h>   typedef uint32_t integer;   integer next_prime_digit_number(integer n) { if (n == 0) return 2; switch (n % 10) { case 2: return n + 1; case 3: case 5: return n + 2; default: return 2 + next_prime_digit_number(n/10) * 10; } }   bool is_prime(integer n) { if (n < 2) return false; if (n % 2 == 0) return n == 2; if (n % 3 == 0) return n == 3; if (n % 5 == 0) return n == 5; static const integer wheel[] = { 4,2,4,2,4,6,2,6 }; integer p = 7; for (;;) { for (int i = 0; i < 8; ++i) { if (p * p > n) return true; if (n % p == 0) return false; p += wheel[i]; } } }   int main() { setlocale(LC_ALL, ""); const integer limit = 1000000000; integer n = 0, max = 0; printf("First 25 SPDS primes:\n"); for (int i = 0; n < limit; ) { n = next_prime_digit_number(n); if (!is_prime(n)) continue; if (i < 25) { if (i > 0) printf(" "); printf("%'u", n); } else if (i == 25) printf("\n"); ++i; if (i == 100) printf("Hundredth SPDS prime: %'u\n", n); else if (i == 1000) printf("Thousandth SPDS prime: %'u\n", n); else if (i == 10000) printf("Ten thousandth SPDS prime: %'u\n", n); max = n; } printf("Largest SPDS prime less than %'u: %'u\n", limit, max); return 0; }
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle
Solve a Hidato puzzle
The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always connected. The number “1” is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique. It may be assumed that the difference between numbers present on the grid is not greater than lucky 13. The aim is to place a natural number in each blank square so that in the sequence of numbered squares from “1” upwards, each square is in the wp:Moore neighborhood of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints). Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order. A square may only contain one number. In a proper Hidato puzzle, the solution is unique. For example the following problem has the following solution, with path marked on it: Related tasks A* search algorithm N-queens problem Solve a Holy Knight's tour Solve a Knight's tour Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle;
#11l
11l
[[Int]] board [Int] given V start = (-1, -1)   F setup(s) V lines = s.split("\n") V ncols = lines[0].split(‘ ’, group_delimiters' 1B).len V nrows = lines.len  :board = (0 .< nrows + 2).map(_ -> [-1] * (@ncols + 2))   L(row) lines V r = L.index L(cell) row.split(‘ ’, group_delimiters' 1B) V c = L.index I cell == ‘__’  :board[r + 1][c + 1] = 0 L.continue E I cell == ‘.’ L.continue E V val = Int(cell)  :board[r + 1][c + 1] = val  :given.append(val) I val == 1  :start = (r + 1, c + 1)  :given.sort()   F solve(r, c, n, =next = 0) I n > :given.last R 1B I :board[r][c] & :board[r][c] != n R 0B I :board[r][c] == 0 & :given[next] == n R 0B V back = 0 I :board[r][c] == n next++ back = n  :board[r][c] = n L(i) -1 .< 2 L(j) -1 .< 2 I solve(r + i, c + j, n + 1, next) R 1B  :board[r][c] = back R 0B   F print_board() V d = [-1 = ‘ ’, 0 = ‘__’] V bmax = max(:board.map(r -> max(r))) V lbmax = String(bmax).len + 1 L(r) :board[1 .< (len)-1] print(r[1 .< (len)-1].map(c -> @d.get(c, String(c)).rjust(@lbmax)).join(‘’))   V hi = |‘__ 33 35 __ __ . . . __ __ 24 22 __ . . . __ __ __ 21 __ __ . . __ 26 __ 13 40 11 . . 27 __ __ __ 9 __ 1 . . . __ __ 18 __ __ . . . . . __ 7 __ __ . . . . . . 5 __’   setup(hi) print_board() solve(start[0], start[1], 1) print() print_board()
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.
#D
D
import std.string, std.typecons, std.exception, std.algorithm; import queue_usage2; // No queue in Phobos 2.064.   const struct Board { private enum El { floor = ' ', wall = '#', goal = '.', box = '$', player = '@', boxOnGoal='*' } private alias CTable = string; private immutable size_t ncols; private immutable CTable sData, dData; private immutable int playerx, playery;   this(in string[] board) immutable pure nothrow @safe in { foreach (const row; board) { assert(row.length == board[0].length, "Unequal board rows."); foreach (immutable c; row) assert(c.inPattern(" #.$@*"), "Not valid input"); } } body { /*static*/ immutable sMap = [' ':' ', '.':'.', '@':' ', '#':'#', '$':' ']; /*static*/ immutable dMap = [' ':' ', '.':' ', '@':'@', '#':' ', '$':'*']; ncols = board[0].length;   int plx = 0, ply = 0; CTable sDataBuild, dDataBuild;   foreach (immutable r, const row; board) foreach (immutable c, const ch; row) { sDataBuild ~= sMap[ch]; dDataBuild ~= dMap[ch]; if (ch == El.player) { plx = c; ply = r; } }   this.sData = sDataBuild; this.dData = dDataBuild; this.playerx = plx; this.playery = ply; }   private bool move(in int x, in int y, in int dx, in int dy, ref CTable data) const pure nothrow /*@safe*/ { if (sData[(y + dy) * ncols + x + dx] == El.wall || data[(y + dy) * ncols + x + dx] != El.floor) return false;   auto data2 = data.dup; data2[y * ncols + x] = El.floor; data2[(y + dy) * ncols + x + dx] = El.player; data = data2.assumeUnique; // Not enforced. return true; }   private bool push(in int x, in int y, in int dx, in int dy, ref CTable data) const pure nothrow /*@safe*/ { if (sData[(y + 2 * dy) * ncols + x + 2 * dx] == El.wall || data[(y + 2 * dy) * ncols + x + 2 * dx] != El.floor) return false;   auto data2 = data.dup; data2[y * ncols + x] = El.floor; data2[(y + dy) * ncols + x + dx] = El.player; data2[(y + 2 * dy) * ncols + x + 2*dx] = El.boxOnGoal; data = data2.assumeUnique; // Not enforced. return true; }   private bool isSolved(in CTable data) const pure nothrow @safe @nogc { foreach (immutable i, immutable d; data) if ((sData[i] == El.goal) != (d == El.boxOnGoal)) return false; return true; }   string solve() pure nothrow /*@safe*/ { bool[immutable CTable] visitedSet = [dData: true];   alias Four = Tuple!(CTable, string, int, int); GrowableCircularQueue!Four open; open.push(Four(dData, "", playerx, playery));   static immutable dirs = [tuple( 0, -1, 'u', 'U'), tuple( 1, 0, 'r', 'R'), tuple( 0, 1, 'd', 'D'), tuple(-1, 0, 'l', 'L')];   while (!open.empty) { //immutable (cur, cSol, x, y) = open.pop; immutable item = open.pop; immutable cur = item[0]; immutable cSol = item[1]; immutable x = item[2]; immutable y = item[3];   foreach (immutable di; dirs) { CTable temp = cur; //immutable (dx, dy) = di[0 .. 2]; immutable dx = di[0]; immutable dy = di[1];   if (temp[(y + dy) * ncols + x + dx] == El.boxOnGoal) { if (push(x, y, dx, dy, temp) && temp !in visitedSet) { if (isSolved(temp)) return cSol ~ di[3]; open.push(Four(temp, cSol ~ di[3], x + dx, y + dy)); visitedSet[temp] = true; } } else if (move(x, y, dx, dy, temp) && temp !in visitedSet) { if (isSolved(temp)) return cSol ~ di[2]; open.push(Four(temp, cSol ~ di[2], x + dx, y + dy)); visitedSet[temp] = true; } } }   return "No solution"; } }   void main() { import std.stdio, core.memory; GC.disable; // Uses about twice the memory.   immutable level = "####### # # # # #. # # #. $$ # #.$$ # #.# @# #######";   immutable b = immutable(Board)(level.splitLines); writeln(level, "\n\n", b.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
#Java
Java
import java.util.*;   public class HolyKnightsTour {   final static String[] board = { " xxx ", " x xx ", " xxxxxxx", "xxx x x", "x x xxx", "1xxxxxx ", " xx x ", " xxx "};   private final static int base = 12; private final static int[][] moves = {{1, -2}, {2, -1}, {2, 1}, {1, 2}, {-1, 2}, {-2, 1}, {-2, -1}, {-1, -2}}; private static int[][] grid; private static int total = 2;   public static void main(String[] args) { int row = 0, col = 0;   grid = new int[base][base];   for (int r = 0; r < base; r++) { Arrays.fill(grid[r], -1); for (int c = 2; c < base - 2; c++) { if (r >= 2 && r < base - 2) { if (board[r - 2].charAt(c - 2) == 'x') { grid[r][c] = 0; total++; } if (board[r - 2].charAt(c - 2) == '1') { row = r; col = c; } } } }   grid[row][col] = 1;   if (solve(row, col, 2)) printResult(); }   private static boolean solve(int r, int c, int count) { if (count == total) return true;   List<int[]> nbrs = neighbors(r, c);   if (nbrs.isEmpty() && count != total) return false;   Collections.sort(nbrs, (a, b) -> a[2] - b[2]);   for (int[] nb : nbrs) { r = nb[0]; c = nb[1]; grid[r][c] = count; if (solve(r, c, count + 1)) return true; grid[r][c] = 0; }   return false; }   private static List<int[]> neighbors(int r, int c) { List<int[]> nbrs = new ArrayList<>();   for (int[] m : moves) { int x = m[0]; int y = m[1]; if (grid[r + y][c + x] == 0) { int num = countNeighbors(r + y, c + x) - 1; nbrs.add(new int[]{r + y, c + x, num}); } } return nbrs; }   private static int countNeighbors(int r, int c) { int num = 0; for (int[] m : moves) if (grid[r + m[1]][c + m[0]] == 0) num++; return num; }   private static void printResult() { for (int[] row : grid) { for (int i : row) { if (i == -1) System.out.printf("%2s ", ' '); else System.out.printf("%2d ", i); } System.out.println(); } } }
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.
#Raku
Raku
# Reference: # https://github.com/retupmoca/P6-SOAP # http://wiki.dreamfactory.com/DreamFactory/Tutorials/Temp_Conversion_SOAP_API   use v6; use SOAP::Client;   my $request = SOAP::Client.new('http://www.w3schools.com/xml/tempconvert.asmx?WSDL') or die;   say $request.call('CelsiusToFahrenheit', Celsius => 100 ) or die;   say $request.call('FahrenheitToCelsius', Fahrenheit => 212 ) or die;
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.
#Ruby
Ruby
require 'soap/wsdlDriver'   wsdl = SOAP::WSDLDriverFactory.new("http://example.com/soap/wsdl") soap = wsdl.create_rpc_driver   response1 = soap.soapFunc(:elementName => "value") puts response1.soapFuncReturn   response2 = soap.anotherSoapFunc(:aNumber => 42) puts response2.anotherSoapFuncReturn
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.
#Smalltalk
Smalltalk
| service client response1 response2 |   service := SprayWSDLService onUrl: 'http://example.com/soap/wsdl'.   client := service createClient. response1 := client send: 'soapFunc' withArguments:{ 'hello' }. response2 := client send: 'anotherSoapFunc' withArguments:{ 34234 }.
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
#Python
Python
  from sys import stdout   neighbours = [[2, 2], [-2, 2], [2, -2], [-2, -2], [3, 0], [0, 3], [-3, 0], [0, -3]] cnt = 0 pWid = 0 pHei = 0     def is_valid(a, b): return -1 < a < pWid and -1 < b < pHei     def iterate(pa, x, y, v): if v > cnt: return 1   for i in range(len(neighbours)): a = x + neighbours[i][0] b = y + neighbours[i][1] if is_valid(a, b) and pa[a][b] == 0: pa[a][b] = v r = iterate(pa, a, b, v + 1) if r == 1: return r pa[a][b] = 0 return 0     def solve(pz, w, h): global cnt, pWid, pHei   pa = [[-1 for j in range(h)] for i in range(w)] f = 0 pWid = w pHei = h for j in range(h): for i in range(w): if pz[f] == "1": pa[i][j] = 0 cnt += 1 f += 1   for y in range(h): for x in range(w): if pa[x][y] == 0: pa[x][y] = 1 if 1 == iterate(pa, x, y, 2): return 1, pa pa[x][y] = 0   return 0, pa   r = solve("011011011111111111111011111000111000001000", 7, 6) if r[0] == 1: for j in range(6): for i in range(7): if r[1][i][j] == -1: stdout.write(" ") else: stdout.write(" {:0{}d}".format(r[1][i][j], 2)) print() else: stdout.write("No solution!")  
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.
#EchoLisp
EchoLisp
  ;; sorting (name value) by name - Ignoring case (define (name a) (first a)) (define( sort-proc a b) (string-ci<? (name a) (name b)))   (define people '(("😎" -42) ("albert" 33) ("Simone" 44) ("Antoinette" 42) ("elvis" 666) ("😃" 1000)))   (list-sort sort-proc people) → (("albert" 33) ("Antoinette" 42) ("elvis" 666) ("Simone" 44) ("😃" 1000) ("😎" -42))    
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.)
#VBScript
VBScript
function findMax( a ) dim num dim max max = 0 for each num in a if num > max then max = num next findMax = max end function   function findMin( a ) dim num dim min min = 0 for each num in a if num < min then min = num next findMin = min end function   'the function returns the sorted array, but the fact is that VBScript passes the array by reference anyway function countingSort( a ) dim count() dim min, max min = findMin(a) max = findMax(a) redim count( max - min + 1 ) dim i dim z for i = 0 to ubound( a ) count( a(i) - min ) = count( a( i ) - min ) + 1 next z = 0 for i = min to max while count( i - min) > 0 a(z) = i z = z + 1 count( i - min ) = count( i - min ) - 1 wend next countingSort = a end function
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).
#J
J
holes=:;:'A B C D E F G H'   connections=:".;._2]0 :0 holes e.;:'C D E' NB. A holes e.;:'D E F' NB. B holes e.;:'A D G' NB. C holes e.;:'A B C E G H' NB. D holes e.;:'A B D F G H' NB. E holes e.;:'B E H' NB. F holes e.;:'C D E' NB. G holes e.;:'D E F' NB. H ) assert (-:|:) connections NB. catch typos   pegs=: 1+(A.&i.~ !)8   attempt=: [: <./@(-.&0)@,@:| connections * -/~     box=:0 :0 A B /|\ /|\ / | X | \ / |/ \| \ C - D - E - F \ |\ /| / \ | X | / \|/ \|/ G H )   disp=:verb define rplc&(,holes;&":&>y) box )
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
#Ruby
Ruby
require 'HLPsolver'   ADJACENT = [[-1, 0], [0, -1], [0, 1], [1, 0]]   board1 = <<EOS 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 EOS HLPsolver.new(board1).solve   board2 = <<EOS 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 EOS HLPsolver.new(board2).solve
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
#SystemVerilog
SystemVerilog
    ////////////////////////////////////////////////////////////////////////////// /// NumbrixSolver /// /// Solve the puzzle, by using system verilog randomization engine /// ////////////////////////////////////////////////////////////////////////////// class NumbrixSolver; rand int solvedBoard[][]; int fixedBoard[][]; int numCells; //////////////////////////////////////////////////////////////////////////// /// Dynamically resize the board accordingly to the size of the reference/// /// board /// //////////////////////////////////////////////////////////////////////////// constraint height { solvedBoard.size == fixedBoard.size; } constraint width { foreach(solvedBoard[i]) solvedBoard[i].size == fixedBoard[i].size; }   //////////////////////////////////////////////////////////////////////////// /// Fix the positions defined in the input board /// //////////////////////////////////////////////////////////////////////////// constraint fixed { foreach(solvedBoard[i]) foreach(solvedBoard[i][j]) if(fixedBoard[i][j] != 0)solvedBoard[i][j] == fixedBoard[i][j]; } //////////////////////////////////////////////////////////////////////////// /// Ensures that the whole board is filled from the number with numbers /// /// 1,2,3,...,numCells /// //////////////////////////////////////////////////////////////////////////// constraint range { foreach(solvedBoard[i])foreach(solvedBoard[i][j]) solvedBoard[i][j] inside {[1:numCells]}; } //////////////////////////////////////////////////////////////////////////// /// Ensures that there is no repeated number, consequently every number /// /// is present on the board /// //////////////////////////////////////////////////////////////////////////// constraint uniqueness { foreach(solvedBoard[i1]) foreach(solvedBoard[i1][j1]) foreach(solvedBoard[i2]) foreach(solvedBoard[i2][j2]) if((i1 != i2) || (j1 != j2)) solvedBoard[i1][j1] != solvedBoard[i2][j2]; }   //////////////////////////////////////////////////////////////////////////// /// Ensures that exists one direction connecting the numbers in /// /// increasing order /// //////////////////////////////////////////////////////////////////////////// constraint f_seq { foreach(solvedBoard[i])foreach(solvedBoard[i][j]) (solvedBoard[i][j] == (numCells)) || (solvedBoard[(i < solvedBoard.size-1) ? (i+1): i][j] == solvedBoard[i][j]+1) || (solvedBoard[i][(j < solvedBoard[i].size - 1) ? j+1: j] == solvedBoard[i][j]+1) || (solvedBoard[(i > 0) ? i-1: i][j] == solvedBoard[i][j]+1) || (solvedBoard[i][(j > 0)? j-1:j] == solvedBoard[i][j]+1); }     function void pre_randomize(); // the multiplication is not supported in the constraints numCells = fixedBoard.size * fixedBoard[0].size; endfunction function void printSolvedBoard(); foreach(solvedBoard[i]) begin foreach(solvedBoard[j]) begin $write("%4d", solvedBoard[i][j]); end $display(""); end endfunction endclass     ////////////////////////////////////////////////////////////////////////////// /// SolveNumBrix: A program demonstrating how to use NumbrixSolver class /// //////////////////////////////////////////////////////////////////////////////   program SolveNumbrix; NumbrixSolver board; initial begin board = new; board.fixedBoard = '{ '{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}}; if(board.randomize()) begin $display("Solution for the Example 1"); board.printSolvedBoard(); end else begin $display("Failed to solve Example 1"); end   board.fixedBoard = '{ {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}};   if(board.randomize()) begin $display("Solution for the Example 2"); board.printSolvedBoard(); end else begin $display("Failed to solve Example 2"); end $finish; end endprogram  
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.
#Elixir
Elixir
list = [2, 4, 3, 1, 2] IO.inspect Enum.sort(list) IO.inspect Enum.sort(list, &(&1>&2))
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#Erlang
Erlang
List = [2, 4, 3, 1, 2]. SortedList = lists:sort(List).
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Object identifiers (OID) Task Show how to sort a list of OIDs, in their natural sort order. Details An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number. Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields. Test case Input (list of strings) Output (list of strings) 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11150.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11.2.17.5.2.0.79 1.3.6.1.4.1.11.2.17.19.3.4.0.1 1.3.6.1.4.1.11.2.17.19.3.4.0.4 1.3.6.1.4.1.11.2.17.19.3.4.0.10 1.3.6.1.4.1.11150.3.4.0 1.3.6.1.4.1.11150.3.4.0.1 Related tasks Natural sorting Sort using a custom comparator
#Phix
Phix
sequence 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"} constant len = length(strings) sequence sortable = repeat(0,len) for i=1 to len do sequence si = split(strings[i],'.') for j=1 to length(si) do si[j] = to_number(si[j]) end for sortable[i] = {si,i} end for sortable = sort(sortable) for i=1 to len do ?strings[sortable[i][2]] end for
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
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   ( "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" )   len for var i i get "." " " subst split len for var j j get tonum j set endfor i set endfor   sort   len for var i i get "" var string len for get tostr "." chain string swap chain var string endfor drop string 0 del i set endfor   len for get print nl endfor  
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
#J
J
7 6 5 4 3 2 1 0 (/:~@:{`[`]}~ /:~@~.) 6 1 7 7 0 5 4 3 2 1 6
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
#Java
Java
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List;   public class Disjoint { public static <T extends Comparable<? super T>> void sortDisjoint( List<T> array, int[] idxs) { Arrays.sort(idxs); List<T> disjoint = new ArrayList<T>(); for (int idx : idxs) { disjoint.add(array.get(idx)); } Collections.sort(disjoint); int i = 0; for (int idx : idxs) { array.set(idx, disjoint.get(i++)); } }   public static void main(String[] args) { List<Integer> list = Arrays.asList(7, 6, 5, 4, 3, 2, 1, 0); int[] indices = {6, 1, 7}; System.out.println(list); sortDisjoint(list, indices); System.out.println(list); } }
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).
#zkl
zkl
fcn sortByColumn(list,col) { list.sort('wrap(city1,city2){ city1[col]<city2[col] }) }
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.
#Raku
Raku
# Sorting strings. Added a vertical bar between strings to make them discernable my ($a, $b, $c) = 'lions, tigers, and', 'bears, oh my!', '(from "The Wizard of Oz")'; say "sorting: {($a, $b, $c).join('|')}"; say ($a, $b, $c).sort.join('|'), ' - standard lexical string sort';   # Sorting numeric things my ($x, $y, $z) = 7.7444e4, -12, 18/2; say "\nsorting: $x $y $z"; say ($x, $y, $z).sort, ' - standard numeric sort, low to high';   # Or, with a modified comparitor: for -*, ' - numeric sort high to low', ~*, ' - lexical "string" sort', *.chars, ' - sort by string length short to long', -*.chars, ' - or long to short' -> $comparitor, $type { my ($x, $y, $z) = 7.7444e4, -12, 18/2; say ($x, $y, $z).sort( &$comparitor ), $type; } say '';   # sort ALL THE THINGS # sorts by lexical order with numeric values by magnitude. .say for ($a, $b, $c, $x, $y, $z).sort;
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.
#Nial
Nial
sort fork [=[tally first,tally last],up, >= [tally first,tally last]] ['Here', 'are', 'some', 'sample', 'strings', 'to', 'be', 'sorted'] =+-------+------+------+----+----+---+--+--+ =|strings|sample|sorted|Here|some|are|be|to| =+-------+------+------+----+----+---+--+--+
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.
#Nim
Nim
import strutils, algorithm   var strings = "here are Some sample strings to be sorted".split(' ')   strings.sort(proc (x, y: string): int = result = cmp(y.len, x.len) if result == 0: result = cmpIgnoreCase(x, y) )   echo strings
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
#zkl
zkl
fcn combSort(list){ len,gap,swaps:=list.len(),len,True; while(gap>1 or swaps){ gap,swaps=(1).max(gap.toFloat()/1.2473), False; foreach i in (len - gap){ if(list[i]>list[i + gap]){ list.swap(i,i + gap); swaps=True; } } } list }
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.
#Smalltalk
Smalltalk
Smalltalk at: #isItSorted put: [ :c | |isit| isit := false. (2 to: (c size)) detect: [ :i | ( (c at: ( i - 1 )) > (c at: i) ) ] ifNone: [ isit := true ]. isit ]. Smalltalk at: #bogosort put: [ :c | [ isItSorted value: c ] whileFalse: [ 1 to: (c size) do: [ :i | |r t| r := (Random between: 1 and: (c size)). t := (c at: i). c at: i put: (c at: r). c at: r put: t ] ] ].   |tobesorted| tobesorted := { 2 . 7 . 5 . 3 . 4 . 8 . 6 . 1 }. bogosort value: tobesorted. tobesorted displayNl.
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.
#Ezhil
Ezhil
    ## இந்த நிரல் ஒரு பட்டியலில் உள்ள எண்களை Bubble Sort என்ற முறைப்படி ஏறுவரிசையிலும் பின்னர் அதையே இறங்குவரிசையிலும் அடுக்கித் தரும்   ## மாதிரிக்கு நாம் ஏழு எண்களை எடுத்துக்கொள்வோம்   எண்கள் = [5, 1, 10, 8, 1, 21, 4, 2] எண்கள்பிரதி = எண்கள்   பதிப்பி "ஆரம்பப் பட்டியல்:" பதிப்பி எண்கள்   நீளம் = len(எண்கள்) குறைநீளம் = நீளம் - 1   @(குறைநீளம் != -1) வரை மாற்றம் = -1 @(எண் = 0, எண் < குறைநீளம், எண் = எண் + 1) ஆக முதலெண் = எடு(எண்கள், எண்) இரண்டாமெண் = எடு(எண்கள், எண் + 1) @(முதலெண் > இரண்டாமெண்) ஆனால்   ## பெரிய எண்களை ஒவ்வொன்றாகப் பின்னே நகர்த்துகிறோம்   வெளியேஎடு(எண்கள், எண்) நுழைக்க(எண்கள், எண், இரண்டாமெண்) வெளியேஎடு(எண்கள், எண் + 1) நுழைக்க(எண்கள், எண் + 1, முதலெண்) மாற்றம் = எண் முடி முடி குறைநீளம் = மாற்றம் முடி   பதிப்பி "ஏறு வரிசையில் அமைக்கப்பட்ட பட்டியல்:" பதிப்பி எண்கள்   ## இதனை இறங்குவரிசைக்கு மாற்றுவதற்கு எளிய வழி   தலைகீழ்(எண்கள்)   ## இப்போது, நாம் ஏற்கெனவே எடுத்துவைத்த எண்களின் பிரதியை Bubble Sort முறைப்படி இறங்குவரிசைக்கு மாற்றுவோம்   நீளம் = len(எண்கள்பிரதி) குறைநீளம் = நீளம் - 1   @(குறைநீளம் != -1) வரை மாற்றம் = -1 @(எண் = 0, எண் < குறைநீளம், எண் = எண் + 1) ஆக முதலெண் = எடு(எண்கள்பிரதி, எண்) இரண்டாமெண் = எடு(எண்கள்பிரதி, எண் + 1) @(முதலெண் < இரண்டாமெண்) ஆனால்   ## சிறிய எண்களை ஒவ்வொன்றாகப் பின்னே நகர்த்துகிறோம்   வெளியேஎடு(எண்கள்பிரதி, எண்) நுழைக்க(எண்கள்பிரதி, எண், இரண்டாமெண்) வெளியேஎடு(எண்கள்பிரதி, எண் + 1) நுழைக்க(எண்கள்பிரதி, எண் + 1, முதலெண்) மாற்றம் = எண் முடி முடி குறைநீளம் = மாற்றம் முடி   பதிப்பி "இறங்கு வரிசையில் அமைக்கப்பட்ட பட்டியல்:" பதிப்பி எண்கள்பிரதி    
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.
#Oz
Oz
declare fun {GnomeSort Xs} case Xs of nil then nil [] X|Xr then {Loop [X] Xr} end end   fun {Loop Vs Ws} case [Vs Ws] of [V|_ W|Wr] andthen V =< W then {Loop W|Vs Wr} [] [V|Vr W|Wr] then {Loop Vr W|V|Wr} [] [nil W|Wr] then {Loop [W] Wr} [] [Vs nil ] then {Reverse Vs} end end in {Show {GnomeSort [3 1 4 1 5 9 2 6 5]}}
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
#Nim
Nim
template trySwap(): untyped = if a[i] < a[i-1]: swap a[i], a[i-1] t = false   proc cocktailSort[T](a: var openarray[T]) = var t = false var l = a.len while not t: t = true for i in 1 ..< l: trySwap if t: break for i in countdown(l-1, 1): trySwap   var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782] cocktailSort a echo a
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.
#C.23
C#
using System; using System.IO; using System.Net.Sockets;   class Program { static void Main(string[] args) { TcpClient tcp = new TcpClient("localhost", 256); StreamWriter writer = new StreamWriter(tcp.GetStream());   writer.Write("hello socket world"); writer.Flush();   tcp.Close(); } }
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#C.2B.2B
C++
//compile with g++ main.cpp -lboost_system -pthread   #include <boost/asio.hpp>   int main() { boost::asio::io_context io_context; boost::asio::ip::tcp::socket sock(io_context); boost::asio::ip::tcp::resolver resolver(io_context); boost::asio::ip::tcp::resolver::query query("localhost", "4321");   boost::asio::connect(sock, resolver.resolve(query)); boost::asio::write(sock, boost::asio::buffer("Hello world socket\r\n"));   return 0; }
http://rosettacode.org/wiki/Sleeping_Beauty_problem
Sleeping Beauty problem
Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss. If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to estimate the probability that the coin toss was heads. Her estimate is recorded and she is then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied. If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to estimate the probability the coin toss was heads, but is then given a drug which makes her forget that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday. Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always estimate the probability of heads as 1/2, since she does not have any additional information. Others have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate should be 1/3 heads. Task Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty is asked the question.
#CLU
CLU
% This program needs to be merged with PCLU's "misc" library % to use the random number generator.   experiment = cluster is run rep = null   own awake: int := 0 own awake_heads: int := 0    % Returns true if heads, false if tails coin_toss = proc () returns (bool) return(random$next(2)=1) end coin_toss    % Do the experiment once do_experiment = proc () heads: bool := coin_toss()    % monday - wake up awake := awake + 1 if heads then awake_heads := awake_heads + 1 return end    % tuesday - wake up if tails awake := awake + 1 end do_experiment    % Run the experiment N times run = proc (n: int) returns (real) awake := 0 awake_heads := 0   for i: int in int$from_to(1,n) do do_experiment() end   return(real$i2r(awake_heads) / real$i2r(awake)) end run end experiment   start_up = proc () N = 1000000   po: stream := stream$primary_output() stream$puts(po, "Chance of waking up with heads: ")   chance: real := experiment$run(N) stream$putl(po, f_form(chance, 1, 6)) end start_up
http://rosettacode.org/wiki/Sleeping_Beauty_problem
Sleeping Beauty problem
Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss. If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to estimate the probability that the coin toss was heads. Her estimate is recorded and she is then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied. If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to estimate the probability the coin toss was heads, but is then given a drug which makes her forget that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday. Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always estimate the probability of heads as 1/2, since she does not have any additional information. Others have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate should be 1/3 heads. Task Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty is asked the question.
#Dyalect
Dyalect
let experiments = 10000 var heads = 0 var wakenings = 0 for _ in 1..experiments { wakenings += 1 match rnd(min: 0, max: 10) { <5 => heads += 1, _ => wakenings += 1 } } print("Wakenings over \(experiments) experiments: \(wakenings)") print("Sleeping Beauty should estimate a credence of: \(Float(heads) / Float(wakenings))")
http://rosettacode.org/wiki/Sleeping_Beauty_problem
Sleeping Beauty problem
Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss. If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to estimate the probability that the coin toss was heads. Her estimate is recorded and she is then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied. If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to estimate the probability the coin toss was heads, but is then given a drug which makes her forget that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday. Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always estimate the probability of heads as 1/2, since she does not have any additional information. Others have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate should be 1/3 heads. Task Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty is asked the question.
#Excel
Excel
SLEEPINGB =LAMBDA(n, LET( headsWakes, LAMBDA(x, IF(1 = x, {1,1}, {0,2} ) )( RANDARRAY(n, 1, 0, 1, TRUE) ), CHOOSE( {1,2}, SUM(INDEX(headsWakes, 0, 1)), SUM(INDEX(headsWakes, 0, 2)) ) ) )