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/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;
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[NeighbourQ, CellDistance, VisualizeHidato, HiddenSingle, \ NakedN, HiddenN, ChainSearch, HidatoSolve, Cornering, ValidPuzzle, \ GapSearch, ReachDelete, GrowNeighbours] NeighbourQ[cell1_, cell2_] := (CellDistance[cell1, cell2] === 1) ValidPuzzle[cells_List, cands_List] := MemberQ[cands, {1}] \[And] MemberQ[cands, {Length[cells]}] \[And] Length[cells] == Length[candidates] \[And] MinMax[Flatten[cands]] === {1, Length[cells]} \[And] (Union @@ cands === Range[Length[cells]]) CellDistance[cell1_, cell2_] := ChessboardDistance[cell1, cell2] VisualizeHidato[cells_List, cands_List] := Module[{grid, nums, cb, hx}, grid = {EdgeForm[Thick], MapThread[ If[Length[#2] > 1, {FaceForm[], Rectangle[#1]}, {FaceForm[LightGray], Rectangle[#1]}] &, {cells, cands}]}; nums = MapThread[ If[Length[#1] == 1, Text[Style[First[#1], 16], #2 + 0.5 {1, 1}], Text[ Tooltip[Style[Length[#1], Red, 10], #1], #2 + 0.5 {1, 1}]] &, {cands, cells}]; cb = CoordinateBounds[cells]; Graphics[{grid, nums}, PlotRange -> cb + {{-0.5, 1.5}, {-0.5, 1.5}}, ImageSize -> 60 (1 + cb[[1, 2]] - cb[[1, 1]])] ] HiddenSingle[cands_List] := Module[{singles, newcands = cands}, singles = Cases[Tally[Flatten[cands]], {_, 1}]; If[Length[singles] > 0, singles = Sort[singles[[All, 1]]]; newcands = If[ContainsAny[#, singles], Intersection[#, singles], #] & /@ newcands; newcands , cands ] ] HiddenN[cands_List, n_Integer?(# > 1 &)] := Module[{tmp, out}, tmp = cands; tmp = Join @@ MapIndexed[{#1, First[#2]} &, tmp, {2}]; tmp = Transpose /@ GatherBy[tmp, First]; tmp[[All, 1]] = tmp[[All, 1, 1]]; tmp = Select[tmp, 2 <= Length[Last[#]] <= n &]; If[Length[tmp] > 0, tmp = Transpose /@ Subsets[tmp, {n}]; tmp[[All, 2]] = Union @@@ tmp[[All, 2]]; tmp = Select[tmp, Length[Last[#]] == n &]; If[Length[tmp] > 0, (* for each tmp {cands, cells} in each of the cells delete everything except the cands *)   out = cands; Do[ Do[ out[[c]] = Select[out[[c]], MemberQ[t[[1]], #] &]; , {c, t[[2]]} ] , {t, tmp} ]; out , cands ] , cands ] ] NakedN[cands_List, n_Integer?(# > 1 &)] := Module[{tmp, newcands, ids}, tmp = {Range[Length[cands]], cands}\[Transpose]; tmp = Select[tmp, 2 <= Length[Last[#]] <= n &]; If[Length[tmp] > 0, tmp = Transpose /@ Subsets[tmp, {n}]; tmp[[All, 2]] = Union @@@ tmp[[All, 2]]; tmp = Select[tmp, Length[Last[#]] == n &]; If[Length[tmp] > 0, newcands = cands; Do[ ids = Complement[Range[Length[newcands]], t[[1]]]; newcands[[ids]] = DeleteCases[newcands[[ids]], Alternatives @@ t[[2]], \[Infinity]]; , {t, tmp} ]; newcands , cands ] , cands ] ] Cornering[cells_List, cands_List] := Module[{newcands, neighbours, filled, neighboursfiltered, cellid, filledneighours, begin, end, beginend}, filled = Flatten[MapIndexed[If[Length[#1] == 1, #2, {}] &, cands]]; begin = If[MemberQ[cands, {1}], {}, {1}]; end = If[MemberQ[cands, {Length[cells]}], {}, {Length[cells]}]; beginend = Join[begin, end]; neighbours = Outer[NeighbourQ, cells, cells, 1]; neighbours = Association[ MapIndexed[ First[#2] -> {Complement[Flatten[Position[#1, True]], filled], Intersection[Flatten[Position[#1, True]], filled]} &, neighbours]]; KeyDropFrom[neighbours, filled]; neighbours = Select[neighbours, Length[First[#]] == 1 &]; If[Length[neighbours] > 0, newcands = cands; neighbours = KeyValueMap[List, neighbours]; Do[ cellid = n[[1]]; filledneighours = n[[2, 2]]; filledneighours = Join @@ cands[[filledneighours]]; filledneighours = Union[filledneighours - 1, filledneighours + 1]; filledneighours = Union[filledneighours, beginend]; newcands[[cellid]] = Intersection[newcands[[cellid]], filledneighours]; , {n, neighbours} ]; newcands , cands ] ] ChainSearch[cells_, cands_] := Module[{neighbours, sols, out}, neighbours = Outer[NeighbourQ, cells, cells, 1]; neighbours = Association[ MapIndexed[First[#2] -> Flatten[Position[#1, True]] &, neighbours]]; sols = Reap[ChainSearch[neighbours, cands, {}];][[2]]; If[Length[sols] > 0, sols = sols[[1]]; If[Length[sols] > 1, Print["multiple solutions found, showing first"]; ]; sols = First[sols]; out = cands; out[[sols]] = List /@ Range[Length[out]]; out , cands ] ] ChainSearch[neighbours_, cands_List, solcellids_List] := Module[{largest, largestid, next, poss}, largest = Length[solcellids]; largestid = Last[solcellids, 0]; If[largest < Length[cands], next = largest + 1; poss = Flatten[MapIndexed[If[MemberQ[#1, next], First[#2], {}] &, cands]]; If[Length[poss] > 0, If[largest > 0, poss = Intersection[poss, neighbours[largestid]]; ]; poss = Complement[poss, solcellids]; (* can't be in previous path*)   If[Length[poss] > 0, (* there are 'next' ones iterate over, calling this function *) Do[ ChainSearch[neighbours, cands, Append[solcellids, p]] , {p, poss} ] ] , Print["There should be a next!"]; Abort[]; ] , Sow[solcellids] (* we found a solution with this ordering of cells *) ] ] GrowNeighbours[neighbours_, set_List] := Module[{lastdone, ids, newneighbours, old}, old = Join @@ set[[All, All, 1]]; lastdone = Last[set]; ids = lastdone[[All, 1]]; newneighbours = Union @@ (neighbours /@ ids); newneighbours = Complement[newneighbours, old]; (*only new ones*)   If[Length[newneighbours] > 0, Append[set, Thread[{newneighbours, lastdone[[1, 2]] + 1}]] , set ] ] ReachDelete[cells_List, cands_List, neighbours_, startid_] := Module[{seed, distances, val, newcands}, If[MatchQ[cands[[startid]], {_}], val = cands[[startid, 1]]; seed = {{{startid, 0}}}; distances = Join @@ FixedPoint[GrowNeighbours[neighbours, #] &, seed]; If[Length[distances] > 0, distances = Select[distances, Last[#] > 0 &]; If[Length[distances] > 0, newcands = cands; distances[[All, 2]] = Transpose[ val + Outer[Times, {-1, 1}, distances[[All, 2]] - 1]]; Do[newcands[[\[CurlyPhi][[1]]]] = Complement[newcands[[\[CurlyPhi][[1]]]], Range @@ \[CurlyPhi][[2]]]; , {\[CurlyPhi], distances} ]; newcands , cands ] , cands ] , Print["invalid starting point for neighbour search"]; Abort[]; ] ] GapSearch[cells_List, cands_List] := Module[{givensid, givens, neighbours}, givensid = Flatten[Position[cands, {_}]]; givens = {cells[[givensid]], givensid, Flatten[cands[[givensid]]]}\[Transpose]; If[Length[givens] > 0, givens = SortBy[givens, Last]; givens = Split[givens, Last[#2] == Last[#1] + 1 &]; givens = If[Length[#] <= 2, #, #[[{1, -1}]]] & /@ givens; If[Length[givens] > 0, givens = Join @@ givens; If[Length[givens] > 0, neighbours = Outer[NeighbourQ, cells, cells, 1]; neighbours = Association[ MapIndexed[First[#2] -> Flatten[Position[#1, True]] &, neighbours]]; givens = givens[[All, 2]]; Fold[ReachDelete[cells, #1, neighbours, #2] &, cands, givens] , cands ] , cands ] , cands ] ] HidatoSolve[cells_List, cands_List] := Module[{newcands = cands, old}, If[ValidPuzzle[cells, cands] \[Or] 1 == 1, old = -1; newcands = GapSearch[cells, newcands]; While[old =!= newcands, old = newcands; newcands = GapSearch[cells, newcands]; If[old === newcands, newcands = HiddenSingle[newcands]; If[old === newcands, newcands = NakedN[newcands, 2]; newcands = HiddenN[newcands, 2]; If[old === newcands, newcands = NakedN[newcands, 3]; newcands = HiddenN[newcands, 3]; If[old === newcands, newcands = Cornering[cells, newcands]; If[old === newcands, newcands = NakedN[newcands, 4]; newcands = HiddenN[newcands, 4]; If[old === newcands, newcands = NakedN[newcands, 5]; newcands = HiddenN[newcands, 5]; If[old === newcands, newcands = NakedN[newcands, 6]; newcands = HiddenN[newcands, 6]; If[old === newcands, newcands = NakedN[newcands, 7]; newcands = HiddenN[newcands, 7]; If[old === newcands, newcands = NakedN[newcands, 8]; newcands = HiddenN[newcands, 8]; ] ] ] ] ] ] ] ] ] ]; If[Length[Flatten[newcands]] > Length[newcands], (* if not solved do a depth-first brute force search*)   newcands = ChainSearch[cells, newcands]; ]; (*Print@VisualizeHidato[cells,newcands];*) newcands , Print[ "There seems to be something wrong with your Hidato puzzle. Check \ if the begin and endpoints are given, the cells and candidates have \ the same length, all the numbers are among the \ candidates\[Ellipsis]"] ] ] cells = {{1, 4}, {1, 5}, {1, 6}, {1, 7}, {1, 8}, {2, 4}, {2, 5}, {2, 6}, {2, 7}, {2, 8}, {3, 3}, {3, 4}, {3, 5}, {3, 6}, {3, 7}, {3, 8}, {4, 3}, {4, 4}, {4, 5}, {4, 6}, {4, 7}, {4, 8}, {5, 2}, {5, 3}, {5, 4}, {5, 5}, {5, 6}, {5, 7}, {5, 8}, {6, 2}, {6, 3}, {6, 4}, {6, 5}, {6, 6}, {7, 1}, {7, 2}, {7, 3}, {7, 4}, {8, 1}, {8, 2}}; (* cartesian coordinates of the cells *) candidates = ConstantArray[Range@Length[cells], Length[ cells]]; (* all the cells start with candidates 1 through 40 *)   hints = { {{1, 4}, {27}}, {{2, 5}, {26}}, {{7, 1}, {5}}, {{6, 2}, {7}}, {{5, 3}, {18}}, {{5, 4}, {9}}, {{5, 5}, {40}}, {{6, 5}, {11}}, {{4, 5}, {13}}, {{4, 6}, {21}}, {{4, 7}, {22}}, {{3, 7}, {24}}, {{3, 8}, {35}}, {{2, 8}, {33}}, {{7, 4}, {1}} }; indices = Flatten[Position[cells, #] & /@ hints[[All, 1]]]; candidates[[indices]] = hints[[All, 2]]; VisualizeHidato[cells, candidates] out = HidatoSolve[cells, candidates]; VisualizeHidato[cells, out]
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.
#Lua
Lua
function sorting( a, b ) return a[1] < b[1] end   tab = { {"C++", 1979}, {"Ada", 1983}, {"Ruby", 1995}, {"Eiffel", 1985} }   table.sort( tab, sorting ) for _, v in ipairs( tab ) do print( unpack(v) ) end
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).
#XPL0
XPL0
include c:\cxpl\codes;   int Hole, Max, I; char Box(8), Str; def A, B, C, D, E, F, G, H; [for Hole:= 0 to 7 do Box(Hole):= Hole+1; Max:= 7; while abs(Box(D)-Box(A)) < 2 or abs(Box(D)-Box(C)) < 2 or abs(Box(D)-Box(G)) < 2 or abs(Box(D)-Box(E)) < 2 or abs(Box(A)-Box(C)) < 2 or abs(Box(C)-Box(G)) < 2 or abs(Box(G)-Box(E)) < 2 or abs(Box(E)-Box(A)) < 2 or abs(Box(E)-Box(B)) < 2 or abs(Box(E)-Box(H)) < 2 or abs(Box(E)-Box(F)) < 2 or abs(Box(B)-Box(D)) < 2 or abs(Box(D)-Box(H)) < 2 or abs(Box(H)-Box(F)) < 2 or abs(Box(F)-Box(B)) < 2 do loop [I:= Box(0); \next permutation for Hole:= 0 to Max-1 do Box(Hole):= Box(Hole+1); Box(Max):= I; if I # Max+1 then [Max:= 7; quit] else Max:= Max-1]; Str:= " # # /|\ /|\ / | X | \ / |/ \| \ # - # - # - # \ |\ /| / \ | X | / \|/ \|/ # # "; Hole:= 0; I:= 0; repeat if Str(I)=^# then [Str(I):= Box(Hole)+^0; Hole:= Hole+1]; I:= I+1; until Hole = 8; Text(0, Str); ]
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).
#zkl
zkl
const PegA=0, PegB=1, PegC=2, PegD=3, PegE=4, PegF=5, PegG=6, PegH=7; connections:=T( T(PegA, PegC), T(PegA, PegD), T(PegA, PegE), T(PegB, PegD), T(PegB, PegE), T(PegB, PegF), T(PegC, PegD), T(PegD, PegE), T(PegE, PegF), T(PegG, PegC), T(PegG, PegD), T(PegG, PegE), T(PegH, PegD), T(PegH, PegE), T(PegH, PegF) ); CZ:=connections.len(); #<<< // Use "raw" string in a "here doc" so \ isn't a quote char board:= 0'$ A B /|\ /|\ / | X | \ / |/ \| \ C - D - E - F \ |\ /| / \ | X | / \|/ \|/ G H$; #<<< // end "here doc"   perm:=T(PegA,PegB,PegC,PegD,PegE,PegF,PegG,PegH); // Peg[8] foreach p in (Utils.Helpers.permuteW(perm)){ // permutation iterator if(connections.filter1('wrap([(a,b)]){ (p[a] - p[b]).abs()<=1 })) continue; board.translate("ABCDEFGH",p.apply('+(1)).concat()).println(); break; // comment out to see all 16 solutions }
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.
#Lasso
Lasso
local(array) = array(5,20,3,2,6,1,4) #array->sort #array // 1, 2, 3, 4, 5, 6, 20   // Reverse the sort order #array->sort(false) #array // 20, 6, 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.
#Liberty_BASIC
Liberty BASIC
N =20 dim IntArray( N)   print "Original order" for i =1 to N t =int( 1000 *rnd( 1)) IntArray( i) =t print t next i   sort IntArray(), 1, N   print "Sorted oprder" for i =1 to N print IntArray( i) next i
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
#PureBasic
PureBasic
Procedure Bubble_sort(Array idx(1), n, Array buf(1)) Protected i, j SortArray(idx(),#PB_Sort_Ascending) For i=0 To n For j=i+1 To n If buf(idx(j)) < buf(idx(i)) Swap buf(idx(j)), buf(idx(i)) EndIf Next Next EndProcedure   Procedure main() DataSection values: Data.i 7, 6, 5, 4, 3, 2, 1, 0 indices:Data.i 6, 1, 7 EndDataSection   Dim values.i(7) :CopyMemory(?values, @values(), SizeOf(Integer)*8) Dim indices.i(2):CopyMemory(?indices,@indices(),SizeOf(Integer)*3)   If OpenConsole() Protected i PrintN("Before sort:") For i=0 To ArraySize(values()) Print(Str(values(i))+" ") Next   PrintN(#CRLF$+#CRLF$+"After sort:") Bubble_sort(indices(), ArraySize(indices()), values()) For i=0 To ArraySize(values()) Print(Str(values(i))+" ") Next   Print(#CRLF$+#CRLF$+"Press ENTER to exit") Input() EndIf EndProcedure   main()
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.
#REXX
REXX
/*REXX program sorts a (stemmed) array using the merge-sort method. */ /* using mycmp function for the sort order */ /********************************************************************** * mergesort taken from REXX (adapted for ooRexx (and all other REXXes)) * 28.07.2013 Walter Pachl **********************************************************************/ Call gena /* generate the array elements. */ Call showa 'before sort' /* show the before array elements.*/ Call mergeSort highitem /* invoke the merge sort for array*/ Call showa ' after sort' /* show the after array elements.*/ Exit /* stick a fork in it, we're done.*/ /*---------------------------------GENa subroutine-------------------*/ gena: a.='' /* assign default value for a stem*/ a.1='---The seven deadly sins---'/* everybody: pick your favorite.*/ a.2='===========================' a.3='pride' a.4='avarice' a.5='wrath' a.6='envy' a.7='gluttony' a.8='sloth' a.9='lust' Do highitem=1 While a.highitem\=='' /*find number of entries */ End highitem=highitem-1 /* adjust highitem by -1. */ Return /*---------------------------------MERGETOa subroutine---------------*/ mergetoa: Procedure Expose a. !. Parse Arg l,n Select When n==1 Then Nop When n==2 Then Do h=l+1 If mycmp(a.l,a.h)=1 Then Do _=a.h a.h=a.l a.l=_ End End Otherwise Do m=n%2 Call mergeToa l+m,n-m Call mergeTo! l,m,1 i=1 j=l+m Do k=l While k<j If j==l+n|mycmp(!.i,a.j)<>1 Then Do a.k=!.i i=i+1 End Else Do a.k=a.j j=j+1 End End End End Return /*---------------------------------MERGESORT subroutine--------------*/ mergesort: Procedure Expose a. Call mergeToa 1,arg(1) Return /*---------------------------------MERGETO! subroutine---------------*/ mergeto!: Procedure Expose a. !. Parse Arg l,n,_ Select When n==1 Then  !._=a.l When n==2 Then Do h=l+1 q=1+_ If mycmp(a.l,a.h)=1 Then Do q=_ _=q+1 End  !._=a.l  !.q=a.h Return End Otherwise Do m=n%2 Call mergeToa l,m Call mergeTo! l+m,n-m,m+_ i=l j=m+_ Do k=_ While k<j If j==n+_|mycmp(a.i,!.j)<>1 Then Do  !.k=a.i i=i+1 End Else Do  !.k=!.j j=j+1 End End End End Return /*---------------------------------SHOWa subroutine------------------*/ showa: widthh=length(highitem) /* maximum the width of any line.*/ Do j=1 For highitem Say 'element' right(j,widthh) arg(1)':' a.j End Say copies('-',60) /* show a separator line (fence).*/ Return   mycmp: Procedure /********************************************************************** * shorter string considered higher * when lengths are equal: caseless 'Z' considered higher than 'X' etc. * Result: 1 B consider higher than A * -1 A consider higher than B * 0 A==B (caseless) **********************************************************************/ Parse Upper Arg A,B A=strip(A) B=strip(B) I = length(A) J = length(B) Select When I << J THEN res=1 When I >> J THEN res=-1 When A >> B THEN res=1 When A << B THEN res=-1 Otherwise res=0 End RETURN res
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.
#Janet
Janet
  (defn bubble-sort! [arr] (def arr-len (length arr)) (when (< arr-len 2) (break arr)) # at this point there are two or more elements (loop [i :down-to [(dec arr-len) 0]] (for j 0 i (def left-elt (get arr j)) (def right-elt (get arr (inc j))) (when (> left-elt right-elt) (put arr j right-elt) (put arr (inc j) left-elt)))) arr)   (comment   (let [n 100 arr (seq [i :range [0 n]] (* n (math/random)))] (deep= (bubble-sort! (array ;arr)) (sort (array ;arr)))) # => true   )  
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.
#REXX
REXX
/*REXX program sorts an array using the gnome sort algorithm (elements contain blanks). */ call gen /*generate the @ stemmed array. */ call show 'before sort' /*display the before array elements.*/ say copies('▒', 60) /*show a separator line between sorts. */ call gnomeSort # /*invoke the well─known gnome sort. */ call show ' after sort' /*display the after array elements.*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ gen: @.=; @.1= '---the seven virtues---'; @.4= "Hope"  ; @.7= 'Justice' @.2= '======================='; @.5= "Charity [Love]"; @.8= 'Prudence' @.3= 'Faith'  ; @.6= "Fortitude"  ; @.9= 'Temperance' do #=1 while @.#\==''; end; #= #-1; w= length(#); return /*get #items*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ gnomeSort: procedure expose @.; parse arg n; k= 2 /*N: is number items. */ do j=3 while k<=n; p= k - 1 /*P: is previous item.*/ if @.p<<[email protected] then do; k= j; iterate; end /*order is OK so far. */ _= @.p; @.p= @.k; @.k= _ /*swap two @ entries. */ k= k - 1; if k==1 then k= j; else j= j-1 /*test for 1st index. */ end /*j*/; return /*──────────────────────────────────────────────────────────────────────────────────────*/ show: do j=1 for #; say ' element' right(j, w) arg(1)":" @.j; end; 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
#R
R
cocktailSort <- function(A) { repeat { swapped <- FALSE for(i in seq_len(length(A) - 1)) { if(A[i] > A[i + 1]) { A[c(i, i + 1)] <- A[c(i + 1, i)]#The cool trick mentioned above. swapped <- TRUE } } if(!swapped) break swapped <- FALSE for(i in (length(A)-1):1) { if(A[i] > A[i + 1]) { A[c(i, i + 1)] <- A[c(i + 1, i)] swapped <- TRUE } } if(!swapped) break } A } #Examples taken from the Haxe solution. ints <- c(1, 10, 2, 5, -1, 5, -19, 4, 23, 0) numerics <- c(1, -3.2, 5.2, 10.8, -5.7, 7.3, 3.5, 0, -4.1, -9.5) strings <- c("We", "hold", "these", "truths", "to", "be", "self-evident", "that", "all", "men", "are", "created", "equal")
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.
#Nim
Nim
import net   var s = newSocket() s.connect("localhost", Port(256)) s.send("Hello Socket World") s.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.
#Objeck
Objeck
  use Net;   bundle Default { class Socket { function : Main(args : String[]) ~ Nil { socket := TCPSocket->New("localhost", 256); if(socket->IsOpen()) { socket->WriteString("hello socket world"); socket->Close(); } } } }  
http://rosettacode.org/wiki/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Snake is a game where the player maneuvers a line which grows in length every time the snake reaches a food source. Task Implement a variant of the Snake game, in any interactive environment, in which a sole player attempts to eat items by running into them with the head of the snake. Each item eaten makes the snake longer and a new item is randomly generated somewhere else on the plane. The game ends when the snake attempts to eat himself.
#Nim
Nim
import macros, os, random import ncurses   when defined(Linux): proc positional_putch(x, y: int; ch: char) = mvaddch(x.cint, y.cint, ch.chtype) proc updateScreen = refresh() proc nonBlockingGetch(): char = let c = getch() result = if c in 0..255: char(c) else: '\0' proc closeScreen = endwin()   else: error "Not implemented"   const   W = 80 H = 40 Space = 0 Food = 1 Border = 2 Symbol = [' ', '@', '.']   type   Dir {.pure.} = enum North, East, South, West Game = object board: array[W * H, int] head: int dir: Dir quit: bool     proc age(game: var Game) = ## Reduce a time-to-live, effectively erasing the tail. for i in 0..<W*H: if game.board[i] < 0: inc game.board[i]     proc plant(game: var Game) = ## Put a piece of food at random empty position. var r: int while true: r = rand(W * H - 1) if game.board[r] == Space: break game.board[r] = Food     proc start(game: var Game) = ## Initialize the board, plant a very first food item. for i in 0..<W: game.board[i] = Border game.board[i + (H - 1) * W] = Border for i in 0..<H: game.board[i * W] = Border game.board[i * W + W - 1] = Border game.head = W * (H - 1 - (H and 1)) shr 1 # Screen center for any H. game.board[game.head] = -5 game.dir = North game.quit = false game.plant()     proc step(game: var Game) = let len = game.board[game.head] case game.dir of North: dec game.head, W of South: inc game.head, W of West: dec game.head of East: inc game.head   case game.board[game.head] of Space: game.board[game.head] = len - 1 # Keep in mind "len" is negative. game.age() of Food: game.board[game.head] = len - 1 game.plant() else: game.quit = true     proc show(game: Game) = for i in 0..<W*H: positionalPutch(i div W, i mod W, if game.board[i] < 0: '#' else: Symbol[game.board[i]]) updateScreen()     var game: Game randomize() let win = initscr() cbreak() # Make sure thre is no buffering. noecho() # Suppress echoing of characters. nodelay(win, true) # Non-blocking mode. game.start()   while not game.quit: game.show() case nonBlockingGetch() of 'i': game.dir = North of 'j': game.dir = West of 'k': game.dir = South of 'l': game.dir = East of 'q': game.quit = true else: discard game.step() os.sleep(300) # Adjust here: 100 is very fast.   sleep(1000) closeScreen()
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers. Example Using the number 166 Find the prime factors of 166 which are: 2 x 83 Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13 Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13 Therefore, the number 166 is a Smith number. Task Write a program to find all Smith numbers below 10000. See also from Wikipedia:   [Smith number]. from MathWorld:   [Smith number]. from OEIS A6753:   [OEIS sequence A6753]. from OEIS A104170:   [Number of Smith numbers below 10^n]. from The Prime pages:   [Smith numbers].
#Factor
Factor
USING: formatting grouping io kernel math.primes.factors math.ranges math.text.utils sequences sequences.deep ;   : (smith?) ( n factors -- ? ) [ 1 digit-groups sum ] [ [ 1 digit-groups ] map flatten sum = ] bi* ; inline   : smith? ( n -- ? ) dup factors dup length 1 = [ 2drop f ] [ (smith?) ] if ;   10,000 [1,b] [ smith? ] filter 10 group [ [ "%4d " printf ] each nl ] each
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers. Example Using the number 166 Find the prime factors of 166 which are: 2 x 83 Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13 Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13 Therefore, the number 166 is a Smith number. Task Write a program to find all Smith numbers below 10000. See also from Wikipedia:   [Smith number]. from MathWorld:   [Smith number]. from OEIS A6753:   [OEIS sequence A6753]. from OEIS A104170:   [Number of Smith numbers below 10^n]. from The Prime pages:   [Smith numbers].
#Fortran
Fortran
MODULE FACTORISE !Produce a little list... USE PRIMEBAG !This is a common need. INTEGER LASTP !Some size allowances. PARAMETER (LASTP = 9) !2*3*5*7*11*13*17*19*23*29 = 6,469,693,230, > 2,147,483,647. TYPE FACTORED !Represent a number fully factored. INTEGER PVAL(0:LASTP) !As a list of prime number indices with PVAL(0) the count. INTEGER PPOW(LASTP) !And the powers. for the fingered primes. END TYPE FACTORED !Rather than as a simple number multiplied out.   CONTAINS !Now for the details. SUBROUTINE SHOWFACTORS(N) !First, to show an internal data structure. TYPE(FACTORED) N !It is supplied as a list of prime factors. INTEGER I !A stepper. DO I = 1,N.PVAL(0) !Step along the list. IF (I.GT.1) WRITE (MSG,"('x',$)") !Append a glyph for "multiply". WRITE (MSG,"(I0,$)") N.PVAL(I) !The prime number's value. IF (N.PPOW(I).GT.1) WRITE (MSG,"('^',I0,$)") N.PPOW(I) !With an interesting power? END DO !On to the next element in the list. WRITE (MSG,1) N.PVAL(0) !End the line 1 FORMAT (": Factor count ",I0) !With a count of prime factors. END SUBROUTINE SHOWFACTORS !Hopefully, this will not be needed often.   TYPE(FACTORED) FUNCTION FACTOR(IT) !Into a list of primes and their powers. Careful! 1 is not a factor of N, but if N is prime, N is. N = product of its prime factors. INTEGER IT,N !The number and a similar style copy to damage. INTEGER F,FP !A factor and a power. IF (IT.LE.0) STOP "Factor only positive numbers!" !Or else... FACTOR.PVAL(0) = 0 !No prime factors have been found. One need not apply. F = 0 !NEXTPRIME(F) will return 2, the first factor to try. N = IT !A copy I can damage. Collapse N into its prime factors. 10 DO WHILE(N.GT.1) !Carthaga delenda est? IF (ISPRIME(N)) THEN!If the remnant is a prime number, F = N !Then it is the last factor. FP = 1 !Its power is one. N = 1 !And the reduction is finished. ELSE !Otherwise, continue trying larger factors. FP = 0 !It has no power yet. 11 F = NEXTPRIME(F) !Go for the next possible factor. DO WHILE(MOD(N,F).EQ.0) !Well? FP = FP + 1 !Count a factor.. N = N/F !Reduce the number. END DO !Until F's multiplicity is exhausted. IF (FP.LE.0) GO TO 11 !No presence? Try the next factor: N has some... END IF !One way or another, F is a prime factor and FP its power. IF (FACTOR.PVAL(0).GE.LASTP) THEN !Have I room in the list? WRITE (MSG,1) IT,LASTP !Alas. 1 FORMAT ("Factoring ",I0," but with provision for only ", !This shouldn't happen, 1 I0," distinct prime factors!") !If LASTP is correct for the current INTEGER size. CALL SHOWFACTORS(FACTOR) !Show what has been found so far. STOP "Not enough storage!" !Quite. END IF !But normally, FACTOR.PVAL(0) = FACTOR.PVAL(0) + 1 !Admit another factor. FACTOR.PVAL(FACTOR.PVAL(0)) = F !The prime number found to be a factor. FACTOR.PPOW(FACTOR.PVAL(0)) = FP !Place its power. END DO !Now seee what has survived. END FUNCTION FACTOR !Thus, a list of primes and their powers. END MODULE FACTORISE !Careful! PVAL(0) is the number of prime factors.   MODULE SMITHSTUFF !Now for the strange stuff. CONTAINS !The two special workers. INTEGER FUNCTION DIGITSUM(N,BASE) !Sums the digits of N. INTEGER N,IT !The number, and a copy I can damage. INTEGER BASE !The base for arithmetic, IF (N.LT.0) STOP "DigitSum: negative numbers need not apply!" DIGITSUM = 0 !Here we go. IT = N !This value will be damaged. DO WHILE(IT.GT.0) !Something remains? DIGITSUM = MOD(IT,BASE) + DIGITSUM !Yes. Grap the low-order digit. IT = IT/BASE !And descend a power. END DO !Perhaps something still remains. END FUNCTION DIGITSUM !Numerology.   LOGICAL FUNCTION SMITHNUM(N,BASE) !Worse numerology. USE FACTORISE !To find the prime factord of N. INTEGER N !The number of interest. INTEGER BASE !The base of the numerology. TYPE(FACTORED) F !A list. INTEGER I,FD !Assistants. F = FACTOR(N) !Hopefully, LASTP is large enough for N. c write (6,"(a,I0,1x)",advance="no") "N=",N c call ShowFactors(F) FD = 0 !Attempts via the SUM facility involved too many requirements. DO I = 1,F.PVAL(0) !For each of the prime factors found... FD = DIGITSUM(F.PVAL(I),BASE)*F.PPOW(I) + FD !Not forgetting the multiplicity. END DO !On to the next prime factor in the list. SMITHNUM = FD.EQ.DIGITSUM(N,BASE) !This is the rule. END FUNCTION SMITHNUM !So, is N a joker? END MODULE SMITHSTUFF !Simple enough.   USE PRIMEBAG !Gain access to GRASPPRIMEBAG. USE SMITHSTUFF !The special stuff. INTEGER LAST !Might as well document this. PARAMETER (LAST = 9999) !The specification is BELOW 10000... INTEGER I,N,BASE !Workers. INTEGER NB,BAG(20) !Prepare a line's worth of results. MSG = 6 !Standard output.   WRITE (MSG,1) LAST !Hello. 1 FORMAT ('To find the "Smith" numbers up to ',I0) IF (.NOT.GRASPPRIMEBAG(66)) STOP "Gan't grab my file!" !Attempt in hope.   10 DO BASE = 2,12 !Flexible numerology. WRITE (MSG,11) BASE !Here we go again. 11 FORMAT (/,"Working in base ",I0) N = 0 !None found. NB = 0 !So, none are bagged. DO I = 1,LAST !Step through the span. IF (ISPRIME(I)) CYCLE !Prime numbers are boring Smith numbers. Skip them. IF (SMITHNUM(I,BASE)) THEN !So? N = N + 1 !Count one in. IF (NB.GE.20) THEN !A full line's worth with another to come? WRITE (MSG,12) BAG !Yep. Roll the line to make space. 12 FORMAT (20I6) !This will do for a nice table. NB = 0 !The line is now ready. END IF !So much for a line buffer. NB = NB + 1 !Count another entry. BAG(NB) = I !Place it. END IF !So much for a Smith style number. END DO !On to the next candidate number. WRITE (MSG,12) BAG(1:NB)!Wave the tail end. WRITE (MSG,13) N !Save the human some counting. 13 FORMAT (I9," found.") !Just in case. END DO !On to the next base. END !That was strange.
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;
#Nim
Nim
import strutils, algorithm, sequtils, strformat   type Hidato = object board: seq[seq[int]] given: seq[int] start: (int, int)   proc initHidato(s: string): Hidato = var lines = s.splitLines() let cols = lines[0].splitWhitespace().len() let rows = lines.len() result.board = newSeqWith(rows + 2, newSeq[int](cols + 2)) # Make room for borders.   for i in 0 .. result.board.high: for j in 0 .. result.board[0].high: result.board[i][j] = -1   for r, row in lines: for c, cell in row.splitWhitespace().pairs(): case cell of "__" : result.board[r + 1][c + 1] = 0 continue of "." : continue else : let val = parseInt(cell) result.board[r + 1][c + 1] = val result.given.add(val) if val == 1: result.start = (r + 1, c + 1) result.given.sort()     proc solve(hidato: var Hidato; r, c, n: int; next = 0): bool = if n > hidato.given[^1]: return true if hidato.board[r][c] < 0: return false if hidato.board[r][c] > 0 and hidato.board[r][c] != n: return false if hidato.board[r][c] == 0 and hidato.given[next] == n: return false   let back = hidato.board[r][c] hidato.board[r][c] = n for i in -1 .. 1: for j in -1 .. 1: if back == n: if hidato.solve(r + i, c + j, n + 1, next + 1): return true else: if hidato.solve(r + i, c + j, n + 1, next): return true hidato.board[r][c] = back result = false     proc print(hidato: Hidato) = for row in hidato.board: for val in row: stdout.write if val == -1: " . " elif val == 0: "__ " else: &"{val:2} " writeLine(stdout, "")     const Hi = """ __ 33 35 __ __ . . . __ __ 24 22 __ . . . __ __ __ 21 __ __ . . __ 26 __ 13 40 11 . . 27 __ __ __ 9 __ 1 . . . __ __ 18 __ __ . . . . . __ 7 __ __ . . . . . . 5 __"""   var hidato = initHidato(Hi) hidato.print() echo("") echo("Found:") discard hidato.solve(hidato.start[0], hidato.start[1], 1) hidato.print()
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Sort an array of composite structures by a key. For example, if you define a composite structure that presents a name-value pair (in pseudo-code): Define structure pair such that: name as a string value as a string and an array of such pairs: x: array of pairs then define a sort routine that sorts the array x by the key name. This task can always be accomplished with Sorting Using a Custom Comparator. If your language is not listed here, please see the other article.
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Flush ' empty stack of values Class Quick { Private: partition=lambda-> { Read &A(), p, r : i = p-1 : x=A(r) For j=p to r-1 {If .LE(A(j), x) Then i++:Swap A(i),A(j) } : Swap A(i+1), A(r) : Push i+2, i } Public: LE=Lambda->Number<=Number Module ForStrings { .partition<=lambda-> { Read &a$(), p, r : i = p-1 : x$=a$(r) For j=p to r-1 {If a$(j)<= x$ Then i++:Swap a$(i),a$(j) } : Swap a$(i+1), a$(r) : Push i+2, i } } Function quicksort { Read ref$ { loop : If Stackitem() >= Stackitem(2) Then Drop 2 : if empty then {Break} else continue over 2,2 : call .partition(ref$) :shift 3 } } } Quick=Quick() Quick.LE=lambda (a, b)->{ =a.name$<=b.name$ } Data "Joe", 5531 Data "Adam", 2341 Data "Bernie", 122 Data "Walter", 1234 Data "David", 19 Class pair { name$ value_ } Document Doc$={Unsorted Pairs: } Dim A(1 to 5)=pair() For i=1 to 5 { For A(i) { Read .name$, .value_ Doc$=Format$("{0}, {1}", .name$, .value_)+{ } } }   Call Quick.quicksort(&A(),1, 5) Doc$={ Sorted Pairs } k=Each(A()) While k { getone=array(k) For getone { Doc$=Format$("{0}, {1}", .name$, .value_)+{ } } } Report Doc$ Clipboard Doc$ } Checkit module Checkit2 { Inventory Alfa="Joe":=5531, "Adam":=2341, "Bernie":=122 Append Alfa, "Walter":=1234, "David":=19 Sort Alfa k=Each(Alfa) While k { Print eval$(Alfa, k^), Eval(k) } } Checkit2 module Checkit3 { class any { x class: Module any (.x) {} } Inventory Alfa="Joe":=any(5531), "Adam":=any(2341), "Bernie":=any(122) Append Alfa, "Walter":=any(1234), "David":=any(19) Sort Alfa k=Each(Alfa) While k { \\ k^ is the index number by k cursor \\ Alfa("joe") return object \\ Alfa(0!) return first element object \\ Alfa(k^!) return (k^) objext Print eval$(Alfa, k^), Alfa(k^!).x } } Checkit3  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
events = {{"2009-12-25", "Christmas Day"}, {"2009-04-22", "Earth Day"}, {"2009-09-07", "Labor Day"}, {"2009-07-04", "Independence Day"}, {"2009-10-31", "Halloween"}, {"2009-05-25", "Memorial Day"}, {"2009-03-14", "PI Day"}, {"2009-01-01", "New Year's Day"}, {"2009-12-31", "New Year's Eve"}, {"2009-11-26", "Thanksgiving"}, {"2009-02-14", "St. Valentine's Day"}, {"2009-03-17", "St. Patrick's Day"}, {"2009-01-19", "Martin Luther King Day"}, {"2009-02-16", "President's Day"}}; date = 1; name = 2; SortBy[events, #[[name]] &] // Grid SortBy[events, #[[date]] &] // Grid
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.
#Lingo
Lingo
l = [7, 4, 23] l.sort() put l -- [4, 7, 23]
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.
#LiveCode
LiveCode
put "3,2,5,4,1" into X sort items of X numeric put X -- outputs "1,2,3,4,5"
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
#Python
Python
>>> def sort_disjoint_sublist(data, indices): indices = sorted(indices) values = sorted(data[i] for i in indices) for index, value in zip(indices, values): data[index] = value     >>> d = [7, 6, 5, 4, 3, 2, 1, 0] >>> i = set([6, 1, 7]) >>> sort_disjoint_sublist(d, i) >>> d [7, 0, 5, 4, 3, 2, 1, 6] >>> # Which could be more cryptically written as: >>> def sort_disjoint_sublist(data, indices): for index, value in zip(sorted(indices), sorted(data[i] for i in indices)): data[index] = value     >>>
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.
#Ring
Ring
  load "stdlib.ring"   sList = newlist(8, 2) aList = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"] ind = len(aList)   for n = 1 to ind sList[n] [1] = aList[n] sList[n] [2] = len(aList[n]) next   nList = sortFirstSecond(sList, 2) oList = newlist(8, 2) count = 0   for n = len(nList) to 1 step -1 count = count + 1 oList[count] [1] = nList[n] [1] oList[count] [2] = nList[n] [2] next   for n = 1 to len(oList) - 1 temp1 = oList[n] [1] temp2 = oList[n+1] [1] if (oList[n] [2] = oList[n+1] [2]) and (strcmp(temp1, temp2) > 0) temp = oList[n] [1] oList[n] [1] = oList[n+1] [1] oList[n+1] [1] = temp ok next   for n = 1 to len(oList) see oList[n] [1] + nl next  
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.
#Ruby
Ruby
words = %w(Here are some sample strings to be sorted) p words.sort_by {|word| [-word.size, word.downcase]}
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.
#Java
Java
public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) { boolean changed = false; do { changed = false; for (int a = 0; a < comparable.length - 1; a++) { if (comparable[a].compareTo(comparable[a + 1]) > 0) { E tmp = comparable[a]; comparable[a] = comparable[a + 1]; comparable[a + 1] = tmp; changed = true; } } } while (changed); }
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.
#Ring
Ring
  aList = [ 5, 6, 1, 2, 9, 14, 15, 7, 8, 97] gnomeSort(aList) for i=1 to len(aList) see "" + aList[i] + " " next   func gnomeSort a i = 2 j = 3 while i < len(a) if a[i-1] <= a[i] i = j j = j + 1 else temp = a[i-1] a[i-1] = a[i] a[i] = temp i = i - 1 if i = 1 i = j j = j + 1 ok ok end  
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
#Racket
Racket
  #lang racket (require (only-in srfi/43 vector-swap!))   (define (cocktail-sort! xs) (define (ref i) (vector-ref xs i)) (define (swap i j) (vector-swap! xs i j)) (define len (vector-length xs)) (define (bubble from to delta) (for/fold ([swaps 0]) ([i (in-range from to delta)]) (cond [(> (ref i) (ref (+ i 1))) (swap i (+ i 1)) (+ swaps 1)] [swaps]))) (let loop () (cond [(zero? (bubble 0 (- len 2) 1)) xs] [(zero? (bubble (- len 2) 0 -1)) xs] [(loop)])))  
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.
#Objective-C
Objective-C
// declare the class to conform to NSStreamDelegate protocol   // in some method NSOutputStream *oStream; [NSStream getStreamsToHost:[NSHost hostWithName:@"localhost"] port:256 inputStream:NULL outputStream:&oStream]; [oStream setDelegate:self]; [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [oStream open];     // later, in the same class: - (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)streamEvent { NSOutputStream *oStream = (NSOutputStream *)aStream; if (streamEvent == NSStreamEventHasBytesAvailable) { NSString *str = @"hello socket world"; const char *rawstring = [str UTF8String]; [oStream write:rawstring maxLength:strlen(rawstring)]; [oStream close]; } }
http://rosettacode.org/wiki/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Snake is a game where the player maneuvers a line which grows in length every time the snake reaches a food source. Task Implement a variant of the Snake game, in any interactive environment, in which a sole player attempts to eat items by running into them with the head of the snake. Each item eaten makes the snake longer and a new item is randomly generated somewhere else on the plane. The game ends when the snake attempts to eat himself.
#OCaml
OCaml
(* A simple Snake Game *) open Sdl   let width, height = (640, 480)   type pos = int * int   type game_state = { pos_snake: pos; seg_snake: pos list; dir_snake: [`left | `right | `up | `down]; pos_fruit: pos; sleep_time: int; game_over: bool; }   let red = (255, 0, 0) let blue = (0, 0, 255) let green = (0, 255, 0) let black = (0, 0, 0) let alpha = 255   let fill_rect renderer (x, y) = let rect = Rect.make4 x y 20 20 in Render.fill_rect renderer rect; ;;     let display_game renderer state = let bg_color, snake_color, fruit_color = if state.game_over then (red, black, green) else (black, blue, red) in Render.set_draw_color renderer bg_color alpha; Render.clear renderer; Render.set_draw_color renderer fruit_color alpha; fill_rect renderer state.pos_fruit; Render.set_draw_color renderer snake_color alpha; List.iter (fill_rect renderer) state.seg_snake; Render.render_present renderer; ;;     let proc_events dir_snake = function | Event.KeyDown { Event.keycode = Keycode.Left } -> `left | Event.KeyDown { Event.keycode = Keycode.Right } -> `right | Event.KeyDown { Event.keycode = Keycode.Up } -> `up | Event.KeyDown { Event.keycode = Keycode.Down } -> `down | Event.KeyDown { Event.keycode = Keycode.Q } | Event.KeyDown { Event.keycode = Keycode.Escape } | Event.Quit _ -> Sdl.quit (); exit 0 | _ -> (dir_snake)     let rec event_loop dir_snake = match Event.poll_event () with | None -> (dir_snake) | Some ev -> let dir = proc_events dir_snake ev in event_loop dir     let rec pop = function | [_] -> [] | hd :: tl -> hd :: (pop tl) | [] -> invalid_arg "pop"     let rec new_pos_fruit seg_snake = let new_pos = (20 * Random.int 32, 20 * Random.int 24) in if List.mem new_pos seg_snake then new_pos_fruit seg_snake else (new_pos)     let update_state req_dir ({ pos_snake; seg_snake; pos_fruit; dir_snake; sleep_time; game_over; } as state) = if game_over then state else let dir_snake = match dir_snake, req_dir with | `left, `right -> dir_snake | `right, `left -> dir_snake | `up, `down -> dir_snake | `down, `up -> dir_snake | _ -> req_dir in let pos_snake = let x, y = pos_snake in match dir_snake with | `left -> (x - 20, y) | `right -> (x + 20, y) | `up -> (x, y - 20) | `down -> (x, y + 20) in let game_over = let x, y = pos_snake in List.mem pos_snake seg_snake || x < 0 || y < 0 || x >= width || y >= height in let seg_snake = pos_snake :: seg_snake in let seg_snake, pos_fruit, sleep_time = if pos_snake = pos_fruit then (seg_snake, new_pos_fruit seg_snake, sleep_time - 1) else (pop seg_snake, pos_fruit, sleep_time) in { pos_snake; seg_snake; pos_fruit; dir_snake; sleep_time; game_over; }     let () = Random.self_init (); Sdl.init [`VIDEO]; let window, renderer = Render.create_window_and_renderer ~width ~height ~flags:[] in Window.set_title ~window ~title:"Snake OCaml-SDL2"; let initial_state = { pos_snake = (100, 100); seg_snake = [ (100, 100); ( 80, 100); ( 60, 100); ]; pos_fruit = (200, 200); dir_snake = `right; sleep_time = 120; game_over = false; } in   let rec main_loop state = let req_dir = event_loop state.dir_snake in let state = update_state req_dir state in display_game renderer state; Timer.delay state.sleep_time; main_loop state in main_loop initial_state
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers. Example Using the number 166 Find the prime factors of 166 which are: 2 x 83 Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13 Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13 Therefore, the number 166 is a Smith number. Task Write a program to find all Smith numbers below 10000. See also from Wikipedia:   [Smith number]. from MathWorld:   [Smith number]. from OEIS A6753:   [OEIS sequence A6753]. from OEIS A104170:   [Number of Smith numbers below 10^n]. from The Prime pages:   [Smith numbers].
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub getPrimeFactors(factors() As UInteger, n As UInteger) If n < 2 Then Return Dim factor As UInteger = 2 Do If n Mod factor = 0 Then Redim Preserve factors(0 To UBound(factors) + 1) factors(UBound(factors)) = factor n \= factor If n = 1 Then Return Else ' non-prime factors will always give a remainder > 0 as their own factors have already been removed ' so it's not worth checking that the next potential factor is prime factor += 1 End If Loop End Sub   Function sumDigits(n As UInteger) As UInteger If n < 10 Then Return n Dim sum As UInteger = 0 While n > 0 sum += n Mod 10 n \= 10 Wend Return sum End Function   Function isSmith(n As UInteger) As Boolean If n < 2 Then Return False Dim factors() As UInteger getPrimeFactors factors(), n If UBound(factors) = 0 Then Return False '' n must be prime if there's only one factor Dim primeSum As UInteger = 0 For i As UInteger = 0 To UBound(factors) primeSum += sumDigits(factors(i)) Next Return sumDigits(n) = primeSum End Function   Print "The Smith numbers below 10000 are : " Print Dim count As UInteger = 0 For i As UInteger = 2 To 9999 If isSmith(i) Then Print Using "#####"; i; count += 1 End If Next Print : Print Print count; " numbers found" Print Print "Press any key to quit" Sleep
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;
#Perl
Perl
use strict; use List::Util 'max';   our (@grid, @known, $n);   sub show_board { for my $r (@grid) { print map(!defined($_) ? ' ' : $_ ? sprintf("%3d", $_) : ' __' , @$r), "\n" } }   sub parse_board { @grid = map{[map(/^_/ ? 0 : /^\./ ? undef: $_, split ' ')]} split "\n", shift(); for my $y (0 .. $#grid) { for my $x (0 .. $#{$grid[$y]}) { $grid[$y][$x] > 0 and $known[$grid[$y][$x]] = "$y,$x"; } } $n = max(map { max @$_ } @grid); }   sub neighbors { my ($y, $x) = @_; my @out; for ( [-1, -1], [-1, 0], [-1, 1], [ 0, -1], [ 0, 1], [ 1, -1], [ 1, 0], [ 1, 1]) { my $y1 = $y + $_->[0]; my $x1 = $x + $_->[1]; next if $x1 < 0 || $y1 < 0; next unless defined $grid[$y1][$x1]; push @out, "$y1,$x1"; } @out }   sub try_fill { my ($v, $coord) = @_; return 1 if $v > $n;   my ($y, $x) = split ',', $coord; my $old = $grid[$y][$x];   return if $old && $old != $v; return if exists $known[$v] and $known[$v] ne $coord;   $grid[$y][$x] = $v; print "\033[0H"; show_board();   try_fill($v + 1, $_) && return 1 for neighbors($y, $x);   $grid[$y][$x] = $old; return }   parse_board # ". 4 . # _ 7 _ # 1 _ _";   # " 1 _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . 74 # . . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ # . . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ # ";   "__ 33 35 __ __ .. .. .. . __ __ 24 22 __ .. .. .. . __ __ __ 21 __ __ .. .. . __ 26 __ 13 40 11 .. .. . 27 __ __ __ 9 __ 1 .. . . . __ __ 18 __ __ .. . . .. . . __ 7 __ __ . . .. .. .. . . 5 __ .";   print "\033[2J"; try_fill(1, $known[1]);
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.
#MAXScript
MAXScript
fn keyCmp comp1 comp2 = ( case of ( (comp1[1] > comp2[1]): 1 (comp1[1] < comp2[1]): -1 default: 0 ) )   people = #(#("joe", 39), #("dave", 37), #("bob", 42)) qsort people keyCmp print people
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.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   -- ============================================================================= class RSortCompsiteStructure public   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public static places = [ - PairBean('London', 'UK'), PairBean('New York', 'US') - , PairBean('Boston', 'US'), PairBean('Washington', 'US') - , PairBean('Washington', 'UK'), PairBean("Birmingham", 'US') - , PairBean("Birmingham", 'UK'), PairBean("Boston", 'UK') - ] say displayArray(places) Arrays.sort(places, PairComparator()) say displayArray(places) return   method displayArray(harry = PairBean[]) constant disp = '' loop elmt over harry disp = disp','elmt end elmt return '['disp.substr(2)']' -- trim leading comma   -- ============================================================================= class RSortCompsiteStructure.PairBean properties indirect name value method PairBean(name_, value_) public setName(name_) setValue(value_) return method toString() public returns String return '('getName()','getValue()')'   -- ============================================================================= class RSortCompsiteStructure.PairComparator implements Comparator method compare(lft = Object, rgt = Object) public binary returns int cRes = int if lft <= RSortCompsiteStructure.PairBean, rgt <= RSortCompsiteStructure.PairBean then do lName = String (RSortCompsiteStructure.PairBean lft).getName() rName = String (RSortCompsiteStructure.PairBean rgt).getName() cRes = lName.compareTo(rName) if cRes == 0 then do lVal = String (RSortCompsiteStructure.PairBean lft).getValue() rVal = String (RSortCompsiteStructure.PairBean rgt).getValue() cRes = lVal.compareTo(rVal) end end else signal IllegalArgumentException('Arguments must be of type PairBean') return cRes  
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.
#Lua
Lua
t = {4, 5, 2} table.sort(t) print(unpack(t))
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.
#Maple
Maple
sort([5,7,8,3,6,1]); sort(Array([5,7,8,3,6,1]))
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
#R
R
values=c(7,6,5,4,3,2,1,0) indices=c(7,2,8) values[sort(indices)]=sort(values[indices]) print(values)
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
#Racket
Racket
  #lang racket   (define (sort-disjoint l is) (define xs (sort (for/list ([x l] [i (in-naturals)] #:when (memq i is)) x) <)) (let loop ([l l] [i 0] [xs xs]) (cond [(null? l) l] [(memq i is) (cons (car xs) (loop (cdr l) (add1 i) (cdr xs)))] [else (cons (car l) (loop (cdr l) (add1 i) xs))])))   (sort-disjoint '(7 6 5 4 3 2 1 0) '(6 1 7)) ;; --> '(7 0 5 4 3 2 1 6)  
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.
#Rust
Rust
  fn main() { let mut words = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]; words.sort_by(|l, r| Ord::cmp(&r.len(), &l.len()).then(Ord::cmp(l, r))); println!("{:?}", words); }  
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.
#Sather
Sather
class MAIN is   custom_comp(a, b:STR):BOOL is l ::= a.length - b.length; if l = 0 then return a.lower < b.lower; end; return l > 0; end;   main is s:ARRAY{STR} := |"this", "is", "an", "array", "of", "strings", "to", "sort"|;   s.insertion_sort_by(bind(custom_comp(_,_))); loop #OUT + s.elt! + "\n"; end; end; end;
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort A   bubble   sort is generally considered to be the simplest sorting algorithm. A   bubble   sort is also known as a   sinking   sort. Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses. Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets. The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it.   If the first value is greater than the second, their positions are switched.   Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).   Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.   A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits. This can be expressed in pseudo-code as follows (assuming 1-based indexing): repeat if itemCount <= 1 return hasChanged := false decrement itemCount repeat with index from 1 to itemCount if (item at index) > (item at (index + 1)) swap (item at index) with (item at (index + 1)) hasChanged := true until hasChanged = false Task Sort an array of elements using the bubble sort algorithm.   The elements must have a total order and the index of the array can be of any discrete type.   For languages where this is not possible, sort an array of integers. References The article on Wikipedia. Dance interpretation.
#JavaScript
JavaScript
Array.prototype.bubblesort = function() { var done = false; while (!done) { done = true; for (var i = 1; i<this.length; i++) { if (this[i-1] > this[i]) { done = false; [this[i-1], this[i]] = [this[i], this[i-1]] } } } return this; }
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.
#Ruby
Ruby
class Array def gnomesort! i, j = 1, 2 while i < length if self[i-1] <= self[i] i, j = j, j+1 else self[i-1], self[i] = self[i], self[i-1] i -= 1 if i == 0 i, j = j, j+1 end end end self end end ary = [7,6,5,9,8,4,3,1,2,0] ary.gnomesort! # => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
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
#Raku
Raku
sub cocktail_sort ( @a ) { my $range = 0 ..^ @a.end; loop { my $swapped_forward = 0; for $range.list -> $i { if @a[$i] > @a[$i+1] { @a[ $i, $i+1 ] .= reverse; $swapped_forward = 1; } } last if not $swapped_forward;   my $swapped_backward = 0; for $range.reverse -> $i { if @a[$i] > @a[$i+1] { @a[ $i, $i+1 ] .= reverse; $swapped_backward = 1; } } last if not $swapped_backward; } return @a; }   my @weights = (^50).map: { 100 + ( 1000.rand.Int / 10 ) }; say @weights.sort.Str eq @weights.&cocktail_sort.Str ?? 'ok' !! 'not ok';
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.
#OCaml
OCaml
open Unix   let init_socket addr port = let inet_addr = (gethostbyname addr).h_addr_list.(0) in let sockaddr = ADDR_INET (inet_addr, port) in let sock = socket PF_INET SOCK_STREAM 0 in connect sock sockaddr; (* convert the file descriptor into high-level channels: *) let outchan = out_channel_of_descr sock in let inchan = in_channel_of_descr sock in (inchan, outchan)
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.
#Oz
Oz
declare Socket = {New Open.socket init} in {Socket connect(port:256)} {Socket write(vs:"hello socket world")} {Socket close}
http://rosettacode.org/wiki/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Snake is a game where the player maneuvers a line which grows in length every time the snake reaches a food source. Task Implement a variant of the Snake game, in any interactive environment, in which a sole player attempts to eat items by running into them with the head of the snake. Each item eaten makes the snake longer and a new item is randomly generated somewhere else on the plane. The game ends when the snake attempts to eat himself.
#Perl
Perl
use utf8; use Time::HiRes qw(sleep); use Term::ANSIColor qw(colored); use Term::ReadKey qw(ReadMode ReadLine);   binmode(STDOUT, ':utf8');   use constant { VOID => 0, HEAD => 1, BODY => 2, TAIL => 3, FOOD => 4, };   use constant { LEFT => [+0, -1], RIGHT => [+0, +1], UP => [-1, +0], DOWN => [+1, +0], };   use constant { BG_COLOR => "on_black", SLEEP_SEC => 0.05, };   use constant { SNAKE_COLOR => ('bold green' . ' ' . BG_COLOR), FOOD_COLOR => ('red' . ' ' . BG_COLOR), };   use constant { U_HEAD => colored('▲', SNAKE_COLOR), D_HEAD => colored('▼', SNAKE_COLOR), L_HEAD => colored('◀', SNAKE_COLOR), R_HEAD => colored('▶', SNAKE_COLOR),   U_BODY => colored('╹', SNAKE_COLOR), D_BODY => colored('╻', SNAKE_COLOR), L_BODY => colored('╴', SNAKE_COLOR), R_BODY => colored('╶', SNAKE_COLOR),   U_TAIL => colored('╽', SNAKE_COLOR), D_TAIL => colored('╿', SNAKE_COLOR), L_TAIL => colored('╼', SNAKE_COLOR), R_TAIL => colored('╾', SNAKE_COLOR),   A_VOID => colored(' ', BG_COLOR), A_FOOD => colored('❇', FOOD_COLOR), };   local $| = 1;   my $w = eval { `tput cols` } || 80; my $h = eval { `tput lines` } || 24; my $r = "\033[H";   my @grid = map { [map { [VOID] } 1 .. $w] } 1 .. $h;   my $dir = LEFT; my @head_pos = ($h / 2, $w / 2); my @tail_pos = ($head_pos[0], $head_pos[1] + 1);   $grid[$head_pos[0]][$head_pos[1]] = [HEAD, $dir]; # head $grid[$tail_pos[0]][$tail_pos[1]] = [TAIL, $dir]; # tail   sub create_food { my ($food_x, $food_y);   do { $food_x = rand($w); $food_y = rand($h); } while ($grid[$food_y][$food_x][0] != VOID);   $grid[$food_y][$food_x][0] = FOOD; }   create_food();   sub display { my $i = 0;   print $r, join("\n", map { join("", map { my $t = $_->[0]; if ($t != FOOD and $t != VOID) { my $p = $_->[1]; $i = $p eq UP ? 0 : $p eq DOWN ? 1 : $p eq LEFT ? 2 : 3; } $t == HEAD ? (U_HEAD, D_HEAD, L_HEAD, R_HEAD)[$i] : $t == BODY ? (U_BODY, D_BODY, L_BODY, R_BODY)[$i] : $t == TAIL ? (U_TAIL, D_TAIL, L_TAIL, R_TAIL)[$i] : $t == FOOD ? (A_FOOD) : (A_VOID);   } @{$_} ) } @grid ); }   sub move { my $grew = 0;   # Move the head { my ($y, $x) = @head_pos;   my $new_y = ($y + $dir->[0]) % $h; my $new_x = ($x + $dir->[1]) % $w;   my $cell = $grid[$new_y][$new_x]; my $t = $cell->[0];   if ($t == BODY or $t == TAIL) { die "Game over!\n"; } elsif ($t == FOOD) { create_food(); $grew = 1; }   # Create a new head $grid[$new_y][$new_x] = [HEAD, $dir];   # Replace the current head with body $grid[$y][$x] = [BODY, $dir];   # Save the position of the head @head_pos = ($new_y, $new_x); }   # Move the tail if (not $grew) { my ($y, $x) = @tail_pos;   my $pos = $grid[$y][$x][1]; my $new_y = ($y + $pos->[0]) % $h; my $new_x = ($x + $pos->[1]) % $w;   $grid[$y][$x][0] = VOID; # erase the current tail $grid[$new_y][$new_x][0] = TAIL; # create a new tail   # Save the position of the tail @tail_pos = ($new_y, $new_x); } }   ReadMode(3); while (1) { my $key; until (defined($key = ReadLine(-1))) { move(); display(); sleep(SLEEP_SEC); }   if ($key eq "\e[A" and $dir ne DOWN ) { $dir = UP } elsif ($key eq "\e[B" and $dir ne UP ) { $dir = DOWN } elsif ($key eq "\e[C" and $dir ne LEFT ) { $dir = RIGHT } elsif ($key eq "\e[D" and $dir ne RIGHT) { $dir = LEFT } }
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers. Example Using the number 166 Find the prime factors of 166 which are: 2 x 83 Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13 Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13 Therefore, the number 166 is a Smith number. Task Write a program to find all Smith numbers below 10000. See also from Wikipedia:   [Smith number]. from MathWorld:   [Smith number]. from OEIS A6753:   [OEIS sequence A6753]. from OEIS A104170:   [Number of Smith numbers below 10^n]. from The Prime pages:   [Smith numbers].
#F.C5.8Drmul.C3.A6
Fōrmulæ
  package main   import "fmt"   func numPrimeFactors(x uint) int { var p uint = 2 var pf int if x == 1 { return 1 } for { if (x % p) == 0 { pf++ x /= p if x == 1 { return pf } } else { p++ } } }   func primeFactors(x uint, arr []uint) { var p uint = 2 var pf int if x == 1 { arr[pf] = 1 return } for { if (x % p) == 0 { arr[pf] = p pf++ x /= p if x == 1 { return } } else { p++ } } }   func sumDigits(x uint) uint { var sum uint for x != 0 { sum += x % 10 x /= 10 } return sum }   func sumFactors(arr []uint, size int) uint { var sum uint for a := 0; a < size; a++ { sum += sumDigits(arr[a]) } return sum }   func listAllSmithNumbers(maxSmith uint) { var arr []uint var a uint for a = 4; a < maxSmith; a++ { numfactors := numPrimeFactors(a) arr = make([]uint, numfactors) if numfactors < 2 { continue } primeFactors(a, arr) if sumDigits(a) == sumFactors(arr, numfactors) { fmt.Printf("%4d ", a) } } }   func main() { const maxSmith = 10000 fmt.Printf("All the Smith Numbers less than %d are:\n", maxSmith) listAllSmithNumbers(maxSmith) fmt.Println() }  
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;
#Phix
Phix
with javascript_semantics sequence board, warnsdorffs, knownx, knowny integer width, height, limit, nchars, tries string fmt, blank constant ROW = 1, COL = 2 constant moves = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}} function onboard(integer row, integer col) return row>=1 and row<=height and col>=nchars and col<=nchars*width end function procedure init_warnsdorffs() integer nrow,ncol for row=1 to height do for col=nchars to nchars*width by nchars do for move=1 to length(moves) do nrow = row+moves[move][ROW] ncol = col+moves[move][COL]*nchars if onboard(nrow,ncol) and board[nrow][ncol]='_' then warnsdorffs[nrow][ncol] += 1 end if end for end for end for end procedure function solve(integer row, integer col, integer n) integer nrow, ncol tries+= 1 if n>limit then return 1 end if if knownx[n] then for move=1 to length(moves) do nrow = row+moves[move][ROW] ncol = col+moves[move][COL]*nchars if nrow = knownx[n] and ncol = knowny[n] then if solve(nrow,ncol,n+1) then return 1 end if exit end if end for return 0 end if sequence wmoves = {} for move=1 to length(moves) do nrow = row+moves[move][ROW] ncol = col+moves[move][COL]*nchars if onboard(nrow,ncol) and board[nrow][ncol]='_' then wmoves = append(wmoves,{warnsdorffs[nrow][ncol],nrow,ncol}) end if end for wmoves = sort(wmoves) -- avoid creating orphans if length(wmoves)<2 or wmoves[2][1]>1 then for m=1 to length(wmoves) do {?,nrow,ncol} = wmoves[m] warnsdorffs[nrow][ncol] -= 1 end for for m=1 to length(wmoves) do {?,nrow,ncol} = wmoves[m] board[nrow][ncol-nchars+1..ncol] = sprintf(fmt,n) if solve(nrow,ncol,n+1) then return 1 end if board[nrow][ncol-nchars+1..ncol] = blank end for for m=1 to length(wmoves) do {?,nrow,ncol} = wmoves[m] warnsdorffs[nrow][ncol] += 1 end for end if return 0 end function procedure Hidato(sequence s, integer w, integer h, integer lim) integer y, ch, ch2, k atom t0 = time() s = split(s,'\n') width = w height = h nchars = length(sprintf(" %d",lim)) fmt = sprintf(" %%%dd",nchars-1) blank = repeat('_',nchars) board = repeat(repeat(' ',width*nchars),height) knownx = repeat(0,lim) knowny = repeat(0,lim) limit = 0 for x=1 to height do for y=nchars to width*nchars by nchars do if y>length(s[x]) then ch = '.' else ch = s[x][y] end if if ch='_' then limit += 1 elsif ch!='.' then k = ch-'0' ch2 = s[x][y-1] if ch2!=' ' then k += (ch2-'0')*10 board[x][y-1] = ch2 end if knownx[k] = x knowny[k] = y limit += 1 end if board[x][y] = ch end for end for warnsdorffs = repeat(repeat(0,width*nchars),height) init_warnsdorffs() tries = 0 if solve(knownx[1],knowny[1],2) then puts(1,join(board,"\n")) printf(1,"\nsolution found in %d tries (%3.2fs)\n",{tries,time()-t0}) else puts(1,"no solutions found\n") end if end procedure constant board1 = """ __ 33 35 __ __ .. .. .. __ __ 24 22 __ .. .. .. __ __ __ 21 __ __ .. .. __ 26 __ 13 40 11 .. .. 27 __ __ __ 9 __ 1 .. .. .. __ __ 18 __ __ .. .. .. .. .. __ 7 __ __ .. .. .. .. .. .. 5 __""" Hidato(board1,8,8,40) constant board2 = """ . 4 . _ 7 _ 1 _ _""" Hidato(board2,3,3,7) constant board3 = """ 1 _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . 74 . . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . . . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ .""" Hidato(board3,50,3,74) constant board4 = """ 54 __ 60 59 __ 67 __ 69 __ __ 55 __ __ 63 65 __ 72 71 51 50 56 62 __ .. .. .. .. __ __ __ 14 .. .. 17 __ .. 48 10 11 .. 15 __ 18 __ 22 __ 46 __ .. 3 __ 19 23 __ __ 44 __ 5 __ 1 33 32 __ __ 43 7 __ 36 __ 27 __ 31 42 __ __ 38 __ 35 28 __ 30""" Hidato(board4,9,9,72) constant board5 = """ __ 58 __ 60 __ __ 63 66 __ 57 55 59 53 49 __ 65 __ 68 __ 8 __ __ 50 __ 46 45 __ 10 6 __ .. .. .. __ 43 70 __ 11 12 .. .. .. 72 71 __ __ 14 __ .. .. .. 30 39 __ 15 3 17 __ 28 29 __ __ 40 __ __ 19 22 __ __ 37 36 __ 1 20 __ 24 __ 26 __ 34 33""" Hidato(board5,9,9,72) constant board6 = """ 1 __ .. .. .. __ __ .. .. .. __ __ .. .. .. __ __ .. .. .. __ __ .. .. .. __ __ .. .. .. __ __ .. .. .. __ __ .. .. .. __ __ .. .. .. 82 .. .. __ .. __ .. .. __ .. __ .. .. __ .. __ .. .. __ .. __ .. .. __ .. __ .. .. __ .. __ .. .. __ .. __ .. .. __ .. __ .. .. __ .. __ .. .. __ .. __ .. .. __ .. __ .. .. __ .. __ .. .. __ .. __ .. .. __ .. __ .. .. __ .. __ .. .. __ .. __ .. .. __ .. __ .. .. __ .. __ .. .. __ __ __ .. .. __ __ __ .. .. __ __ __ .. .. __ __ __ .. .. __ __ __ .. .. __ __ __ .. .. __ __ __ .. .. __ __ __ .. .. __ __ __ .. .. ..""" Hidato(board6,46,4,82)
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.
#Nim
Nim
import algorithm, sugar   var people = @{"joe": 120, "foo": 31, "bar": 51} sort(people, (x,y) => cmp(x[0], y[0])) echo people
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.
#Objeck
Objeck
  use Collection;   class Entry implements Compare { @name : String; @value : Float;   New(name : String, value : Float) { @name := name; @value := value; }   method : public : Compare(rhs : Compare) ~ Int { return @name->Compare(rhs->As(Entry)->GetName()); }   method : public : GetName() ~ String { return @name; }   method : public : HashID() ~ Int { return @name->HashID(); }   method : public : ToString() ~ String { return "name={$@name}, value={$@value}"; } }   class Sorter { function : Main(args : String[]) ~ Nil { entries := CompareVector->New(); entries->AddBack(Entry->New("Krypton", 83.798)); entries->AddBack(Entry->New("Beryllium", 9.012182)); entries->AddBack(Entry->New("Silicon", 28.0855)); entries->AddBack(Entry->New("Cobalt", 58.933195)); entries->AddBack(Entry->New("Selenium", 78.96)); entries->AddBack(Entry->New("Germanium", 72.64));   entries->Sort(); each(i : entries) { entries->Get(i)->As(Entry)->ToString()->PrintLine(); }; } }  
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
numbers=Sort[{2,4,3,1,2}]
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#MATLAB
MATLAB
a = [4,3,7,-2,9,1]; b = sort(a) % b contains elements of a in ascending order [b,idx] = sort(a) % b contains a(idx)
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
#Raku
Raku
my @values = 7, 6, 5, 4, 3, 2, 1, 0; my @indices = 6, 1, 7;   @values[ @indices.sort ] .= sort;   say @values;
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.
#Scala
Scala
List("Here", "are", "some", "sample", "strings", "to", "be", "sorted").sortWith{(a,b) => val cmp=a.size-b.size (if (cmp==0) -a.compareTo(b) else cmp) > 0 }
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.
#Scheme
Scheme
(use srfi-13);;Syntax for module inclusion depends on implementation, ;;a sort function may be predefined, or available through srfi 95 (define (mypred? a b) (let ((len-a (string-length a)) (len-b (string-length b))) (if (= len-a len-b) (string>? (string-downcase b) (string-downcase a)) (> len-a len-b))))   (sort '("sorted" "here" "strings" "sample" "Some" "are" "be" "to") mypred?)
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.
#jq
jq
def bubble_sort: def swap(i;j): .[i] as $x | .[i]=.[j] | .[j]=$x;   # input/output: [changed, list] reduce range(0; length) as $i ( [false, .]; if $i > 0 and (.[0]|not) then . else reduce range(0; (.[1]|length) - $i - 1) as $j (.[0] = false; .[1] as $list | if $list[$j] > $list[$j + 1] then [true, ($list|swap($j; $j+1))] else . end ) end ) | .[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.
#Rust
Rust
fn gnome_sort<T: PartialOrd>(a: &mut [T]) { let len = a.len(); let mut i: usize = 1; let mut j: usize = 2; while i < len { if a[i - 1] <= a[i] { // for descending sort, use >= for comparison i = j; j += 1; } else { a.swap(i - 1, i); i -= 1; if i == 0 { i = j; j += 1; } } } }   fn main() { let mut v = vec![10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6]; println!("before: {:?}", v); gnome_sort(&mut v); println!("after: {:?}", v); }
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
#REXX
REXX
/*REXX program sorts an array using the cocktail─sort method, A.K.A.: happy hour sort,*/ /* bidirectional bubble sort, */ /* cocktail shaker sort, ripple sort,*/ /* a selection sort variation, */ /* shuffle sort, shuttle sort, or */ /* a bubble sort variation. */ call gen@ /*generate some array elements. */ call show@ 'before sort' /*show unsorted array elements. */ say copies('█', 101) /*show a separator line (a fence). */ call cocktailSort # /*invoke the cocktail sort subroutine. */ call show@ ' after sort' /*show sorted array elements. */ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ cocktailSort: procedure expose @.; parse arg N; nn= N-1 /*N: is number of items. */ do until done; done= 1 do j=1 for nn; jp= j+1 if @.j>@.jp then do; done=0; [email protected]; @[email protected]; @.jp=_; end end /*j*/ if done then leave /*No swaps done? Finished*/ do k=nn for nn by -1; kp= k+1 if @.k>@.kp then do; done=0; [email protected]; @[email protected]; @.kp=_; end end /*k*/ end /*until*/ return /*──────────────────────────────────────────────────────────────────────────────────────*/ gen@: @.= /*assign a default value for the stem. */ @.1 ='---the 22 card tarot deck (larger deck has 56 additional cards in 4 suits)---' @.2 ='==========symbol====================pip======================================' @.3 ='the juggler ◄─── I' @.4 ='the high priestess [Popess] ◄─── II' @.5 ='the empress ◄─── III' @.6 ='the emperor ◄─── IV' @.7 ='the hierophant [Pope] ◄─── V' @.8 ='the lovers ◄─── VI' @.9 ='the chariot ◄─── VII' @.10='justice ◄─── VIII' @.11='the hermit ◄─── IX' @.12='fortune [the wheel of] ◄─── X' @.13='strength ◄─── XI' @.14='the hanging man ◄─── XII' @.15='death [often unlabeled] ◄─── XIII' @.16='temperance ◄─── XIV' @.17='the devil ◄─── XV' @.18='lightning [the tower] ◄─── XVI' @.19='the stars ◄─── XVII' @.20='the moon ◄─── XVIII' @.21='the sun ◄─── XIX' @.22='judgment ◄─── XX' @.23='the world ◄─── XXI' @.24='the fool [often unnumbered] ◄─── XXII'   do #=1 until @.#==''; end; #= #-1 /*find how many entries in the array. */ return /* [↑] adjust for DO loop advancement.*/ /*──────────────────────────────────────────────────────────────────────────────────────*/ show@: w= length(#); do j=1 for # /*#: is the number of items in @. */ say 'element' right(j, w) arg(1)":" @.j end /*j*/ /* ↑ */ return /* └─────max width of any line.*/
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.
#Pascal
Pascal
Program Sockets_ExampleA;   Uses { Free Pascal RTL sockets unit } sockets;   Var TCP_Sock: integer; Remote_Addr: TSockAddr;   Message: string; PMessage: Pchar; Message_Len: integer;     Begin { Fill the record (struct) with the server's address information } With Remote_Addr do begin Sin_family := AF_INET; Sin_addr := StrToNetAddr('127.0.0.1'); Sin_port := HtoNs(256); end;   { Returns an IPv4 TCP socket descriptor } TCP_Sock := fpSocket(AF_INET, SOCK_STREAM, IPPROTO_IP);   { Most routines in this unit return -1 on failure } If TCP_Sock = -1 then begin WriteLn('Failed to create new socket descriptor'); Halt(1); end;   { Attempt to connect to the address supplied above } If fpConnect(TCP_Sock, @Remote_Addr, SizeOf(Remote_Addr)) = -1 then begin { Specifc error codes can be retrieved by calling the SocketError function } WriteLn('Failed to contact server'); Halt(1); end;   { Finally, send the message to the server and disconnect } Message := 'Hello socket world'; PMessage := @Message; Message_Len := StrLen(PMessage);   If fpSend(TCP_Sock, PMessage, Message_Len, 0) <> Message_Len then begin WriteLn('An error occurred while sending data to the server'); Halt(1); end;   CloseSocket(TCP_Sock); End.  
http://rosettacode.org/wiki/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Snake is a game where the player maneuvers a line which grows in length every time the snake reaches a food source. Task Implement a variant of the Snake game, in any interactive environment, in which a sole player attempts to eat items by running into them with the head of the snake. Each item eaten makes the snake longer and a new item is randomly generated somewhere else on the plane. The game ends when the snake attempts to eat himself.
#Phix
Phix
constant W = 60, H = 30, MAX_LEN = 600 enum NORTH, EAST, SOUTH, WEST   sequence board, snake bool alive integer tailIdx, headIdx, hdX, hdY, d, points   procedure createField() clear_screen() board = repeat("+"&repeat(' ',W-2)&'+',H) for x=1 to W do board[1,x] = '+' end for board[H] = board[1] board[1+rand(H-2),1+rand(W-2)] = '@'; snake = repeat(0,MAX_LEN) board[3,4] = '#'; tailIdx = 1; headIdx = 5; for c=tailIdx to headIdx do snake[c] = {3,3+c} end for {hdY,hdX} = snake[headIdx-1]; d = EAST; points = 0; end procedure   procedure drawField() for y=1 to H do for x=1 to W do integer t = board[y,x] if t!=' ' then position(y,x) if x=hdX and y=hdY then text_color(14); puts(1,'O'); else text_color({10,9,12}[find(t,"#+@")]); puts(1,t); end if end if end for end for position(H+1,1); text_color(7); printf(1,"Points: %d",points) end procedure   procedure readKey() integer k = find(get_key(),{333,331,328,336}) if k then d = {EAST,WEST,NORTH,SOUTH}[k] end if end procedure   procedure moveSnake() integer x,y switch d do case NORTH: hdY -= 1 case EAST: hdX += 1 case SOUTH: hdY += 1 case WEST: hdX -= 1 end switch integer t = board[hdY,hdX]; if t!=' ' and t!='@' then alive = false; return; end if board[hdY,hdX] = '#'; snake[headIdx] = {hdY,hdX}; headIdx += 1; if headIdx>MAX_LEN then headIdx = 1 end if if t=='@' then points += 1 while 1 do x = 1+rand(W-2); y = 1+rand(H-2); if board[y,x]=' ' then board[y,x] = '@' return end if end while end if {y,x} = snake[tailIdx]; position(y,x); puts(1,' '); board[y,x] = ' '; tailIdx += 1; if tailIdx>MAX_LEN then tailIdx = 1 end if end procedure   procedure play() while true do createField(); alive = true; cursor(NO_CURSOR) while alive do drawField(); readKey(); moveSnake(); sleep(0.05) end while cursor(BLOCK_CURSOR); position(H+2,1); bk_color(0); text_color(11); puts(1,"Play again [Y/N]? ") if upper(wait_key())!='Y' then return end if end while end procedure play()
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers. Example Using the number 166 Find the prime factors of 166 which are: 2 x 83 Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13 Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13 Therefore, the number 166 is a Smith number. Task Write a program to find all Smith numbers below 10000. See also from Wikipedia:   [Smith number]. from MathWorld:   [Smith number]. from OEIS A6753:   [OEIS sequence A6753]. from OEIS A104170:   [Number of Smith numbers below 10^n]. from The Prime pages:   [Smith numbers].
#Go
Go
  package main   import "fmt"   func numPrimeFactors(x uint) int { var p uint = 2 var pf int if x == 1 { return 1 } for { if (x % p) == 0 { pf++ x /= p if x == 1 { return pf } } else { p++ } } }   func primeFactors(x uint, arr []uint) { var p uint = 2 var pf int if x == 1 { arr[pf] = 1 return } for { if (x % p) == 0 { arr[pf] = p pf++ x /= p if x == 1 { return } } else { p++ } } }   func sumDigits(x uint) uint { var sum uint for x != 0 { sum += x % 10 x /= 10 } return sum }   func sumFactors(arr []uint, size int) uint { var sum uint for a := 0; a < size; a++ { sum += sumDigits(arr[a]) } return sum }   func listAllSmithNumbers(maxSmith uint) { var arr []uint var a uint for a = 4; a < maxSmith; a++ { numfactors := numPrimeFactors(a) arr = make([]uint, numfactors) if numfactors < 2 { continue } primeFactors(a, arr) if sumDigits(a) == sumFactors(arr, numfactors) { fmt.Printf("%4d ", a) } } }   func main() { const maxSmith = 10000 fmt.Printf("All the Smith Numbers less than %d are:\n", maxSmith) listAllSmithNumbers(maxSmith) fmt.Println() }  
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;
#Picat
Picat
import sat.   main => M = {{ _,33,35, _, _, 0, 0, 0}, { _, _,24,22, _, 0, 0, 0}, { _, _, _,21, _, _, 0, 0}, { _,26, _,13,40,11, 0, 0}, {27, _, _, _, 9, _, 1, 0}, { 0, 0, _, _,18, _, _, 0}, { 0, 0, 0, 0, _, 7, _, _}, { 0, 0, 0, 0, 0, 0, 5, _}}, MaxR = len(M), MaxC = len(M[1]), NZeros = len([1 : R in 1..MaxR, C in 1..MaxC, M[R,C] == 0]), M :: 0..MaxR*MaxC-NZeros, Vs = [{(R,C),1} : R in 1..MaxR, C in 1..MaxC, M[R,C] !== 0], find_start(M,MaxR,MaxC,StartR,StartC), Es = [{(R,C),(R1,C1),_} : R in 1..MaxR, C in 1..MaxC, M[R,C] !== 0, neibs(M,MaxR,MaxC,R,C,Neibs), (R1,C1) in [(StartR,StartC)|Neibs], M[R1,C1] !== 0], hcp(Vs,Es), foreach ({(R,C),(R1,C1),B} in Es) B #/\ M[R1,C1] #!= 1 #=> M[R1,C1] #= M[R,C]+1 end, solve(M), foreach (R in 1..MaxR) foreach (C in 1..MaxC) if M[R,C] == 0 then printf("%4c", '.') else printf("%4d", M[R,C]) end end, nl end.   find_start(M,MaxR,MaxC,StartR,StartC) => between(1,MaxR,StartR), between(1,MaxC,StartC), M[StartR,StartC] == 1,!.   neibs(M,MaxR,MaxC,R,C,Neibs) => Neibs = [(R1,C1) : Dr in -1..1, Dc in -1..1, R1 = R+Dr, C1 = C+Dc, R1 >= 1, R1 =< MaxR, C1 >= 1, C1 =< MaxC, (R1,C1) != (R,C), M[R1,C1] !== 0].  
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Sort an array of composite structures by a key. For example, if you define a composite structure that presents a name-value pair (in pseudo-code): Define structure pair such that: name as a string value as a string and an array of such pairs: x: array of pairs then define a sort routine that sorts the array x by the key name. This task can always be accomplished with Sorting Using a Custom Comparator. If your language is not listed here, please see the other article.
#Objective-C
Objective-C
@interface Pair : NSObject { NSString *name; NSString *value; } +(instancetype)pairWithName:(NSString *)n value:(NSString *)v; -(instancetype)initWithName:(NSString *)n value:(NSString *)v; -(NSString *)name; -(NSString *)value; @end   @implementation Pair +(instancetype)pairWithName:(NSString *)n value:(NSString *)v { return [[self alloc] initWithName:n value:v]; } -(instancetype)initWithName:(NSString *)n value:(NSString *)v { if ((self = [super init])) { name = n; value = v; } return self; } -(NSString *)name { return name; } -(NSString *)value { return value; } -(NSString *)description { return [NSString stringWithFormat:@"< %@ -> %@ >", name, value]; } @end   int main() { @autoreleasepool {   NSArray *pairs = @[ [Pair pairWithName:@"06-07" value:@"Ducks"], [Pair pairWithName:@"00-01" value:@"Avalanche"], [Pair pairWithName:@"02-03" value:@"Devils"], [Pair pairWithName:@"01-02" value:@"Red Wings"], [Pair pairWithName:@"03-04" value:@"Lightning"], [Pair pairWithName:@"04-05" value:@"lockout"], [Pair pairWithName:@"05-06" value:@"Hurricanes"], [Pair pairWithName:@"99-00" value:@"Devils"], [Pair pairWithName:@"07-08" value:@"Red Wings"], [Pair pairWithName:@"08-09" value:@"Penguins"]];   // optional 3rd arg: you can also specify a selector to compare the keys NSSortDescriptor *sd = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];   // it takes an array of sort descriptors, and it will be ordered by the // first one, then if it's a tie by the second one, etc. NSArray *sorted = [pairs sortedArrayUsingDescriptors:@[sd]]; NSLog(@"%@", sorted);   }   return 0; }
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#Maxima
Maxima
sort([9, 4, 3, 7, 6, 1, 10, 2, 8, 5]);
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#MAXScript
MAXScript
arr = #(5, 4, 3, 2, 1) arr = sort arr
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
#REXX
REXX
/*REXX program uses a disjointed sublist to sort a random list of values. */ parse arg old ',' idx /*obtain the optional lists from the CL*/ if old='' then old= 7 6 5 4 3 2 1 0 /*Not specified: Then use the default.*/ if idx='' then idx= 7 2 8 /* " " " " " " */ say ' list of indices:' idx; say /* [↑] is for one─based lists. */ say ' unsorted list:' old /*display the old list of numbers. */ say ' sorted list:' disjoint_sort(old,idx) /*sort 1st list using 2nd list indices.*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ disjoint_sort: procedure; parse arg x,ix; y=; z=; p= 0 ix= sortL(ix) /*ensure the index list is sorted*/ do i=1 for words(ix) /*extract indexed values from X.*/ z= z word(x, word(ix, i) ) /*pick the correct value from X.*/ end /*j*/ z= sortL(z) /*sort extracted (indexed) values*/ do m=1 for words(x) /*re─build (re-populate) X list.*/ if wordpos(m, ix)==0 then y=y word(x,m) /*is the same or new?*/ else do; p= p + 1; y= y word(z, p) end end /*m*/ return strip(y) /*──────────────────────────────────────────────────────────────────────────────────────*/ sortL: procedure; parse arg L; n= words(L); do j=1 for n; @.j= word(L,j) end /*j*/ do k=1 for n-1 /*sort a list using a slow method*/ do m=k+1 to n; if @.m<@.k then parse value @.k @.m with @.m @.k end /*m*/ end /*k*/ /* [↑] use PARSE for swapping.*/ $= @.1; do j=2 to n; $= $ @.j end /*j*/ return $
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.
#Sidef
Sidef
func mycmp(a, b) { (b.len <=> a.len) || (a.lc <=> b.lc) }; var strings = %w(Here are some sample strings to be sorted); var sorted = strings.sort(mycmp);
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.
#Slate
Slate
define: #words -> #('here' 'are' 'some' 'sample' 'strings' 'to' 'sort' 'since' 'this' 'exercise' 'is' 'not' 'really' 'all' 'that' 'dumb' '(sorry)'). words sortBy: [| :first :second | (first lexicographicallyCompare: second) isNegative]
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.
#Julia
Julia
function bubblesort!(arr::AbstractVector) for _ in 2:length(arr), j in 1:length(arr)-1 if arr[j] > arr[j+1] arr[j], arr[j+1] = arr[j+1], arr[j] end end return arr end   v = rand(-10:10, 10) println("# unordered: $v\n -> ordered: ", bubblesort!(v))
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.
#Scala
Scala
object GnomeSort { def gnomeSort(a: Array[Int]): Unit = { var (i, j) = (1, 2) while ( i < a.length) if (a(i - 1) <= a(i)) { i = j; j += 1 } else { val tmp = a(i - 1) a(i - 1) = a(i) a({i -= 1; i + 1}) = tmp i = if (i == 0) {j += 1; j - 1} else i } } }
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
#Ring
Ring
  aList = [ 5, 6, 1, 2, 9, 14, 2, 15, 6, 7, 8, 97] flag = 0 cocktailSort(aList) for i=1 to len(aList) see "" + aList[i] + " " next   func cocktailSort A n = len(A) while flag = 0 flag = 1 for i = 1 to n-1 if A[i] > A[i+1] temp = A[i] A[i] = A[i+1] A [i+1] = temp flag = 0 ok next end  
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.
#Perl
Perl
use Socket;   $host = gethostbyname('localhost'); $in = sockaddr_in(256, $host); $proto = getprotobyname('tcp'); socket(Socket_Handle, AF_INET, SOCK_STREAM, $proto); connect(Socket_Handle, $in); send(Socket_Handle, 'hello socket world', 0, $in); close(Socket_Handle);
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.
#Phix
Phix
without js -- (sockets) include builtins\sockets.e constant msg = "hello socket world" atom sock = socket(AF_INET, SOCK_STREAM) if sock>=0 then atom pSockAddr = sockaddr_in(AF_INET, "localhost", 256) integer res = connect(sock, pSockAddr) if res=SOCKET_ERROR then crash("connect (%v)",{get_socket_error()}) end if string pm = msg while true do integer len = length(pm), slen = send(sock, pm) if slen<0 or slen=len then exit end if pm = pm[slen+1..$] end while closesocket(sock) end if WSACleanup()
http://rosettacode.org/wiki/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Snake is a game where the player maneuvers a line which grows in length every time the snake reaches a food source. Task Implement a variant of the Snake game, in any interactive environment, in which a sole player attempts to eat items by running into them with the head of the snake. Each item eaten makes the snake longer and a new item is randomly generated somewhere else on the plane. The game ends when the snake attempts to eat himself.
#Python
Python
from __future__ import annotations   import itertools import random   from enum import Enum   from typing import Any from typing import Tuple   import pygame as pg   from pygame import Color from pygame import Rect   from pygame.surface import Surface   from pygame.sprite import AbstractGroup from pygame.sprite import Group from pygame.sprite import RenderUpdates from pygame.sprite import Sprite     class Direction(Enum): UP = (0, -1) DOWN = (0, 1) LEFT = (-1, 0) RIGHT = (1, 0)   def opposite(self, other: Direction): return (self[0] + other[0], self[1] + other[1]) == (0, 0)   def __getitem__(self, i: int): return self.value[i]     class SnakeHead(Sprite): def __init__( self, size: int, position: Tuple[int, int], facing: Direction, bounds: Rect, ) -> None: super().__init__() self.image = Surface((size, size)) self.image.fill(Color("aquamarine4")) self.rect = self.image.get_rect() self.rect.center = position self.facing = facing self.size = size self.speed = size self.bounds = bounds   def update(self, *args: Any, **kwargs: Any) -> None: # Move the snake in the direction it is facing. self.rect.move_ip( ( self.facing[0] * self.speed, self.facing[1] * self.speed, ) )   # Move to the opposite side of the screen if the snake goes out of bounds. if self.rect.right > self.bounds.right: self.rect.left = 0 elif self.rect.left < 0: self.rect.right = self.bounds.right   if self.rect.bottom > self.bounds.bottom: self.rect.top = 0 elif self.rect.top < 0: self.rect.bottom = self.bounds.bottom   def change_direction(self, direction: Direction): if not self.facing == direction and not direction.opposite(self.facing): self.facing = direction     class SnakeBody(Sprite): def __init__( self, size: int, position: Tuple[int, int], colour: str = "white", ) -> None: super().__init__() self.image = Surface((size, size)) self.image.fill(Color(colour)) self.rect = self.image.get_rect() self.rect.center = position     class Snake(RenderUpdates): def __init__(self, game: Game) -> None: self.segment_size = game.segment_size self.colours = itertools.cycle(["aquamarine1", "aquamarine3"])   self.head = SnakeHead( size=self.segment_size, position=game.rect.center, facing=Direction.RIGHT, bounds=game.rect, )   neck = [ SnakeBody( size=self.segment_size, position=game.rect.center, colour=next(self.colours), ) for _ in range(2) ]   super().__init__(*[self.head, *neck])   self.body = Group() self.tail = neck[-1]   def update(self, *args: Any, **kwargs: Any) -> None: self.head.update()   # Snake body sprites don't update themselves. We update them here. segments = self.sprites() for i in range(len(segments) - 1, 0, -1): # Current sprite takes the position of the previous sprite. segments[i].rect.center = segments[i - 1].rect.center   def change_direction(self, direction: Direction): self.head.change_direction(direction)   def grow(self): tail = SnakeBody( size=self.segment_size, position=self.tail.rect.center, colour=next(self.colours), ) self.tail = tail self.add(self.tail) self.body.add(self.tail)     class SnakeFood(Sprite): def __init__(self, game: Game, size: int, *groups: AbstractGroup) -> None: super().__init__(*groups) self.image = Surface((size, size)) self.image.fill(Color("red")) self.rect = self.image.get_rect()   self.rect.topleft = ( random.randint(0, game.rect.width), random.randint(0, game.rect.height), )   self.rect.clamp_ip(game.rect)   # XXX: This approach to random food placement might end badly if the # snake is very large. while pg.sprite.spritecollideany(self, game.snake): self.rect.topleft = ( random.randint(0, game.rect.width), random.randint(0, game.rect.height), )   self.rect.clamp_ip(game.rect)     class Game: def __init__(self) -> None: self.rect = Rect(0, 0, 640, 480) self.background = Surface(self.rect.size) self.background.fill(Color("black"))   self.score = 0 self.framerate = 16   self.segment_size = 10 self.snake = Snake(self) self.food_group = RenderUpdates(SnakeFood(game=self, size=self.segment_size))   pg.init()   def _init_display(self) -> Surface: bestdepth = pg.display.mode_ok(self.rect.size, 0, 32) screen = pg.display.set_mode(self.rect.size, 0, bestdepth)   pg.display.set_caption("Snake") pg.mouse.set_visible(False)   screen.blit(self.background, (0, 0)) pg.display.flip()   return screen   def draw(self, screen: Surface): dirty = self.snake.draw(screen) pg.display.update(dirty)   dirty = self.food_group.draw(screen) pg.display.update(dirty)   def update(self, screen): self.food_group.clear(screen, self.background) self.food_group.update() self.snake.clear(screen, self.background) self.snake.update()   def main(self) -> int: screen = self._init_display() clock = pg.time.Clock()   while self.snake.head.alive(): for event in pg.event.get(): if event.type == pg.QUIT or ( event.type == pg.KEYDOWN and event.key in (pg.K_ESCAPE, pg.K_q) ): return self.score   # Change direction using the arrow keys. keystate = pg.key.get_pressed()   if keystate[pg.K_RIGHT]: self.snake.change_direction(Direction.RIGHT) elif keystate[pg.K_LEFT]: self.snake.change_direction(Direction.LEFT) elif keystate[pg.K_UP]: self.snake.change_direction(Direction.UP) elif keystate[pg.K_DOWN]: self.snake.change_direction(Direction.DOWN)   # Detect collisions after update. self.update(screen)   # Snake eats food. for food in pg.sprite.spritecollide( self.snake.head, self.food_group, dokill=False ): food.kill() self.snake.grow() self.score += 1   # Increase framerate to speed up gameplay. if self.score % 5 == 0: self.framerate += 1   self.food_group.add(SnakeFood(self, self.segment_size))   # Snake hit its own tail. if pg.sprite.spritecollideany(self.snake.head, self.snake.body): self.snake.head.kill()   self.draw(screen) clock.tick(self.framerate)   return self.score     if __name__ == "__main__": game = Game() score = game.main() print(score)  
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers. Example Using the number 166 Find the prime factors of 166 which are: 2 x 83 Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13 Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13 Therefore, the number 166 is a Smith number. Task Write a program to find all Smith numbers below 10000. See also from Wikipedia:   [Smith number]. from MathWorld:   [Smith number]. from OEIS A6753:   [OEIS sequence A6753]. from OEIS A104170:   [Number of Smith numbers below 10^n]. from The Prime pages:   [Smith numbers].
#Haskell
Haskell
import Data.Numbers.Primes (primeFactors) import Data.List (unfoldr) import Data.Tuple (swap) import Data.Bool (bool)   isSmith :: Int -> Bool isSmith n = pfs /= [n] && sumDigits n == foldr ((+) . sumDigits) 0 pfs where sumDigits = sum . baseDigits 10 pfs = primeFactors n   baseDigits :: Int -> Int -> [Int] baseDigits base = unfoldr remQuot where remQuot 0 = Nothing remQuot x = Just (swap (quotRem x base))   lowSmiths :: [Int] lowSmiths = filter isSmith [2 .. 9999]   lowSmithCount :: Int lowSmithCount = length lowSmiths   main :: IO () main = mapM_ putStrLn [ "Count of Smith Numbers below 10k:" , show lowSmithCount , "\nFirst 15 Smith Numbers:" , unwords (show <$> take 15 lowSmiths) , "\nLast 12 Smith Numbers below 10k:" , unwords (show <$> drop (lowSmithCount - 12) lowSmiths) ]
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;
#PicoLisp
PicoLisp
(load "@lib/simul.l")   (de hidato (Lst) (let Grid (grid (length (maxi length Lst)) (length Lst)) (mapc '((G L) (mapc '((This Val) (nond (Val (with (: 0 1 1) (con (: 0 1))) # Cut off west (with (: 0 1 -1) (set (: 0 1))) # east (with (: 0 -1 1) (con (: 0 -1))) # south (with (: 0 -1 -1) (set (: 0 -1))) # north (set This) ) ((=T Val) (=: val Val)) ) ) G L ) ) Grid (apply mapcar (reverse Lst) list) ) (let Todo (by '((This) (: val)) sort (mapcan '((Col) (filter '((This) (: val)) Col)) Grid ) ) (let N 1 (with (pop 'Todo) (recur (N Todo) (unless (> (inc 'N) (; Todo 1 val)) (find '((Dir) (with (Dir This) (cond ((= N (: val)) (if (cdr Todo) (recurse N @) T) ) ((not (: val)) (=: val N) (or (recurse N Todo) (=: val NIL)) ) ) ) ) (quote west east south north ((X) (or (south (west X)) (west (south X)))) ((X) (or (north (west X)) (west (north X)))) ((X) (or (south (east X)) (east (south X)))) ((X) (or (north (east X)) (east (north X)))) ) ) ) ) ) ) ) (disp Grid 0 '((This) (if (: val) (align 3 @) " ") ) ) ) )
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.
#OCaml
OCaml
# let people = [("Joe", 12); ("Bob", 8); ("Alice", 9); ("Harry", 2)];; val people : (string * int) list = [("Joe", 12); ("Bob", 8); ("Alice", 9); ("Harry", 2)] # let sortedPeopleByVal = List.sort (fun (_, v1) (_, v2) -> compare v1 v2) people;; val sortedPeopleByVal : (string * int) list = [("Harry", 2); ("Bob", 8); ("Alice", 9); ("Joe", 12)]
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.
#Mercury
Mercury
:- module sort_int_list. :- interface. :- import_module io.   :- pred main(io::di, uo::uo) is det.   :- implementation. :- import_module list.   main(!IO) :- Nums = [2, 4, 0, 3, 1, 2], list.sort(Nums, Sorted), io.write(Sorted, !IO), io.nl(!IO).
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.
#min
min
(5 2 1 3 4) '> sort print
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
#Ring
Ring
  aList = [7, 6, 5, 4, 3, 2, 1, 0] indList = [7, 2, 8] bList = [] for n = 1 to len(indList) add(bList,[indList[n],aList[indList[n]]]) next bList1 = sort(bList,1) bList2 = sort(bList,2) for n = 1 to len(bList) aList[bList1[n][1]] = bList2[n][2] next showarray(aList)   func showarray vect svect = "" for n in vect svect += " " + n + "," next  ? "[" + left(svect, len(svect) - 1) + "]"  
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
#Ruby
Ruby
def sort_disjoint_sublist!(ar, indices) values = ar.values_at(*indices).sort indices.sort.zip(values).each{ |i,v| ar[i] = v } ar end   values = [7, 6, 5, 4, 3, 2, 1, 0] indices = [6, 1, 7] p sort_disjoint_sublist!(values, indices)
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.
#Smalltalk
Smalltalk
#('here' 'are' 'some' 'sample' 'strings' 'to' 'sort' 'since' 'this' 'exercise' 'is' 'not' 'really' 'all' 'that' 'dumb' '(sorry)' ) asSortedCollection sortBlock: [:first :second | (second size = first size) ifFalse: [second size < first size] ifTrue: [first < second]]
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.
#Kotlin
Kotlin
import java.util.Comparator   fun <T> bubbleSort(a: Array<T>, c: Comparator<T>) { var changed: Boolean do { changed = false for (i in 0..a.size - 2) { if (c.compare(a[i], a[i + 1]) > 0) { val tmp = a[i] a[i] = a[i + 1] a[i + 1] = tmp changed = true } } } while (changed) }
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.
#Scheme
Scheme
; supply comparison function, which returns true if first and second ; arguments are in order or equal. (define (gnome-sort-compar in-order input-list) (let gnome ((p (list (car input-list))) (n (cdr input-list))) (if (null? n) ; no more flowerpots? p ; we're done (let ((prev-pot (car p)) (next-pot (car n))) (if (in-order next-pot prev-pot) ; if the pots are in order, step forwards. ; otherwise, exchange the two pots, and step backwards. (gnome (cons next-pot p) ; Prev list grows (cdr n)) ; Next list shorter by one (if (null? (cdr p)) ; are we at the beginning? (gnome ; if so, we can't step back (list next-pot) ; simply exchange the pots without (cons prev-pot (cdr n))) ; changing lengths of lists (gnome (cdr p) ; Prev list shorter by one (cons next-pot (cons prev-pot (cdr n))))))))))
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
#Ruby
Ruby
class Array def cocktailsort! begin swapped = false 0.upto(length - 2) do |i| if self[i] > self[i + 1] self[i], self[i + 1] = self[i + 1], self[i] swapped = true end end break unless swapped   swapped = false (length - 2).downto(0) do |i| if self[i] > self[i + 1] self[i], self[i + 1] = self[i + 1], self[i] swapped = true end end end while swapped self end end
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.
#PHP
PHP
$socket = fsockopen('localhost', 256); fputs($socket, 'hello socket world'); fclose($socket);
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#PicoLisp
PicoLisp
(when (connect "localhost" 256) (out @ (prinl "hello socket world")) (close @) )
http://rosettacode.org/wiki/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Snake is a game where the player maneuvers a line which grows in length every time the snake reaches a food source. Task Implement a variant of the Snake game, in any interactive environment, in which a sole player attempts to eat items by running into them with the head of the snake. Each item eaten makes the snake longer and a new item is randomly generated somewhere else on the plane. The game ends when the snake attempts to eat himself.
#Raku
Raku
use SDL2::Raw; use Cairo;   constant W = 1280; constant H = 960;   constant FIELDW = W div 32; constant FIELDH = H div 32;   SDL_Init(VIDEO);   my $window = SDL_CreateWindow( 'Snake', SDL_WINDOWPOS_CENTERED_MASK, SDL_WINDOWPOS_CENTERED_MASK, W, H, OPENGL );   my $render = SDL_CreateRenderer($window, -1, ACCELERATED +| PRESENTVSYNC);   my $snake_image = Cairo::Image.record( -> $_ { .save; .rectangle: 0, 0, 64, 64; .clip; .rgb: 0, 1, 0; .rectangle: 0, 0, 64, 64; .fill :preserve; .rgb: 0, 0, 0; .stroke; .restore;   .save; .translate: 64, 0; .rectangle: 0, 0, 64, 64; .clip; .rgb: 1, 0, 0; .arc: 32, 32, 30, 0, 2 * pi; .fill :preserve; .rgb: 0, 0, 0; .stroke; .restore; }, 128, 128, Cairo::FORMAT_ARGB32);   my $snake_texture = SDL_CreateTexture( $render, %PIXELFORMAT<ARGB8888>, STATIC, 128, 128 );   SDL_UpdateTexture( $snake_texture, SDL_Rect.new( :x(0), :y(0), :w(128), :h(128) ), $snake_image.data, $snake_image.stride // 128 * 4 );   SDL_SetTextureBlendMode($snake_texture, 1);   SDL_SetRenderDrawBlendMode($render, 1);   my $snakepiece_srcrect = SDL_Rect.new(:w(64), :h(64)); my $nompiece_srcrect = SDL_Rect.new(:w(64), :h(64), :x(64));   my $event = SDL_Event.new;   enum GAME_KEYS ( K_UP => 82, K_DOWN => 81, K_LEFT => 80, K_RIGHT => 79, );   my Complex @snakepieces = 10+10i; my Complex @noms; my Complex $snakedir = 1+0i; my $nomspawn = 0; my $snakespeed = 0.1; my $snakestep = 0; my $nom = 4;   my $last_frame_start = now; main: loop { my $start = now; my $dt = $start - $last_frame_start // 0.00001; while SDL_PollEvent($event) { my $casted_event = SDL_CastEvent($event); given $casted_event { when *.type == QUIT { last main } when *.type == KEYDOWN { if GAME_KEYS(.scancode) -> $comm { given $comm { when 'K_LEFT' { $snakedir = -1+0i unless $snakedir == 1+0i } when 'K_RIGHT' { $snakedir = 1+0i unless $snakedir == -1+0i } when 'K_UP' { $snakedir = 0-1i unless $snakedir == 0+1i } when 'K_DOWN' { $snakedir = 0+1i unless $snakedir == 0-1i } } } } } }   if ($nomspawn -= $dt) < 0 { $nomspawn += 1; @noms.push: (^FIELDW).pick + (^FIELDH).pick * i unless @noms > 3; @noms.pop if @noms[*-1] == any(@snakepieces); }   if ($snakestep -= $dt) < 0 { $snakestep += $snakespeed;   @snakepieces.unshift: do given @snakepieces[0] { ($_.re + $snakedir.re) % FIELDW + (($_.im + $snakedir.im) % FIELDH) * i }   if @snakepieces[2..*].first( * == @snakepieces[0], :k ) -> $idx { @snakepieces = @snakepieces[0..($idx + 1)]; }   @noms .= grep( { $^piece == @snakepieces[0] ?? ($nom += 1) && False !! True } );   if $nom == 0 { @snakepieces.pop; } else { $nom = $nom - 1; } }   for @snakepieces { SDL_SetTextureColorMod( $snake_texture, 255, (cos((++$) / 2) * 100 + 155).round, 255 );   SDL_RenderCopy( $render, $snake_texture, $snakepiece_srcrect, SDL_Rect.new(.re * 32, .im * 32, 32, 32) ); }   SDL_SetTextureColorMod($snake_texture, 255, 255, 255);   for @noms { SDL_RenderCopy( $render, $snake_texture, $nompiece_srcrect, SDL_Rect.new(.re * 32, .im * 32, 32, 32) ) }   SDL_RenderPresent($render); SDL_SetRenderDrawColor($render, 0, 0, 0, 0); SDL_RenderClear($render);   $last_frame_start = $start; sleep(1 / 50); }   SDL_Quit();
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers. Example Using the number 166 Find the prime factors of 166 which are: 2 x 83 Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13 Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13 Therefore, the number 166 is a Smith number. Task Write a program to find all Smith numbers below 10000. See also from Wikipedia:   [Smith number]. from MathWorld:   [Smith number]. from OEIS A6753:   [OEIS sequence A6753]. from OEIS A104170:   [Number of Smith numbers below 10^n]. from The Prime pages:   [Smith numbers].
#J
J
digits=: 10&#.inv sumdig=: +/@,@digits notprime=: -.@(1&p:) smith=: #~ notprime * (=&sumdig q:)every
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers. Example Using the number 166 Find the prime factors of 166 which are: 2 x 83 Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13 Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13 Therefore, the number 166 is a Smith number. Task Write a program to find all Smith numbers below 10000. See also from Wikipedia:   [Smith number]. from MathWorld:   [Smith number]. from OEIS A6753:   [OEIS sequence A6753]. from OEIS A104170:   [Number of Smith numbers below 10^n]. from The Prime pages:   [Smith numbers].
#Java
Java
import java.util.*;   public class SmithNumbers {   public static void main(String[] args) { for (int n = 1; n < 10_000; n++) { List<Integer> factors = primeFactors(n); if (factors.size() > 1) { int sum = sumDigits(n); for (int f : factors) sum -= sumDigits(f); if (sum == 0) System.out.println(n); } } }   static List<Integer> primeFactors(int n) { List<Integer> result = new ArrayList<>();   for (int i = 2; n % i == 0; n /= i) result.add(i);   for (int i = 3; i * i <= n; i += 2) { while (n % i == 0) { result.add(i); n /= i; } }   if (n != 1) result.add(n);   return result; }   static int sumDigits(int n) { int sum = 0; while (n > 0) { sum += (n % 10); n /= 10; } return sum; } }
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle
Solve a Hidato puzzle
The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always connected. The number “1” is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique. It may be assumed that the difference between numbers present on the grid is not greater than lucky 13. The aim is to place a natural number in each blank square so that in the sequence of numbered squares from “1” upwards, each square is in the wp:Moore neighborhood of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints). Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order. A square may only contain one number. In a proper Hidato puzzle, the solution is unique. For example the following problem has the following solution, with path marked on it: Related tasks A* search algorithm N-queens problem Solve a Holy Knight's tour Solve a Knight's tour Solve a Hopido puzzle Solve a Numbrix puzzle Solve the no connection puzzle;
#Prolog
Prolog
:- use_module(library(clpfd)).   hidato :- init1(Li), % skip first blank line init2(1, 1, 10, Li), my_write(Li).     init1(Li) :- Li = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, A, 33, 35, B, C, 0, 0, 0, 0, 0, D, E, 24, 22, F, 0, 0, 0, 0, 0, G, H, I, 21, J, K, 0, 0, 0, 0, L, 26, M, 13, 40, 11, 0, 0, 0, 0, 27, N, O, P, 9, Q, 1, 0, 0, 0, 0, 0, R, S, 18, T, U, 0, 0, 0, 0, 0, 0, 0, V, 7, W, X, 0, 0, 0, 0, 0, 0, 0, 0, 5, Y, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],   LV = [ A, 33, 35, B, C, D, E, 24, 22, F, G, H, I, 21, J, K, L, 26, M, 13, 40, 11, 27, N, O, P, 9, Q, 1, R, S, 18, T, U, V, 7, W, X, 5, Y],     LV ins 1..40, all_distinct(LV).   % give the constraints % Stop before the last line init2(_N, Col, Max_Col, _L) :- Col is Max_Col - 1.   % skip zeros init2(N, Lig, Col, L) :- I is N + Lig * Col, element(I, L, 0), !, V is N+1, ( V > Col -> N1 = 1, Lig1 is Lig + 1; N1 = V, Lig1 = Lig), init2(N1, Lig1, Col, L).     % skip first column init2(1, Lig, Col, L) :- !, init2(2, Lig, Col, L) .   % skip last column init2(Col, Lig, Col, L) :- !, Lig1 is Lig+1, init2(1, Lig1, Col, L).   % V5 V3 V6 % V1 V V2 % V7 V4 V8 % general case init2(N, Lig, Col, L) :- I is N + Lig * Col, element(I, L, V),   I1 is I - 1, I2 is I + 1, I3 is I - Col, I4 is I + Col, I5 is I3 - 1, I6 is I3 + 1, I7 is I4 - 1, I8 is I4 + 1,   maplist(compute_BI(L, V), [I1,I2,I3,I4,I5,I6,I7,I8], VI, BI),   sum(BI, #=, SBI),   ( ((V #= 1 #\/ V #= 40) #/\ SBI #= 1) #\/ (V #\= 1 #/\ V #\= 40 #/\ SBI #= 2)) #<==> 1,   labeling([ffc, enum], [V | VI]),   N1 is N+1, init2(N1, Lig, Col, L).   compute_BI(L, V, I, VI, BI) :- element(I, L, VI), VI #= 0 #==> BI #= 0, ( VI #\= 0 #/\ (V - VI #= 1 #\/ VI - V #= 1)) #<==> BI.   % display the result my_write([0, A, B, C, D, E, F, G, H, 0 | T]) :- maplist(my_write_1, [A, B, C, D, E, F, G, H]), nl, my_write(T).   my_write([]).   my_write_1(0) :- write(' ').   my_write_1(X) :- writef('%3r', [X]).
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.
#Oforth
Oforth
[["Joe",5531], ["Adam",2341], ["Bernie",122], ["David",19]] sortBy(#first) println
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.
#Ol
Ol
  (import (scheme char))   (define (comp a b) (string-ci<? (a 'name #f) (b 'name #f)))   (for-each print (sort comp (list { 'name "David" 'value "Manager" } { 'name "Alice" 'value "Sales" } { 'name "Joanna" 'value "Director" } { 'name "Henry" 'value "Admin" } { 'name "Tim" 'value "Sales" } { 'name "Juan" 'value "Admin" })))  
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.
#Modula-3
Modula-3
MODULE ArraySort EXPORTS Main;   IMPORT IntArraySort;   VAR arr := ARRAY [1..10] OF INTEGER{3, 6, 1, 2, 10, 7, 9, 4, 8, 5};   BEGIN IntArraySort.Sort(arr); END ArraySort.
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.
#MUMPS
MUMPS
SORTARRAY(X,SEP)  ;X is the list of items to sort  ;X1 is the temporary array  ;SEP is the separator string between items in the list X  ;Y is the returned list  ;This routine uses the inherent sorting of the arrays NEW I,X1,Y SET Y="" FOR I=1:1:$LENGTH(X,SEP) SET X1($PIECE(X,SEP,I))="" SET I="" FOR SET I=$O(X1(I)) Q:I="" SET Y=$SELECT($L(Y)=0:I,1:Y_SEP_I) KILL I,X1 QUIT Y
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
#Run_BASIC
Run BASIC
sortData$ = "7, 6, 5, 4, 3, 2, 1, 0" sortIdx$ = "7, 2, 8"   numSort = 8 dim sortData(numSort) for i = 1 to numSort sortData(i) = val(word$(sortData$,i,",")) next i   while word$(sortIdx$,s + 1) <> "" s = s + 1 idx = val(word$(sortIdx$,s)) gosub [bubbleSort] wend end   [bubbleSort] sortSw = 1 while sortSw = 1 sortSw = 0 for i = idx to numSort - 1 ' start sorting at idx if sortData(i) > sortData(i+1) then sortSw = 1 sortHold = sortData(i) sortData(i) = sortData(i+1) sortData(i+1) = sortHold end if next i wend RETURN
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
#Rust
Rust
use std::collections::BTreeSet;   fn disjoint_sort(array: &mut [impl Ord], indices: &[usize]) { let mut sorted = indices.to_owned(); sorted.sort_unstable_by_key(|k| &array[*k]); indices .iter() .zip(sorted.iter()) .map(|(&a, &b)| if a > b { (b, a) } else { (a, b) }) .collect::<BTreeSet<_>>() .iter() .for_each(|(a, b)| array.swap(*a, *b)) }   fn main() { let mut array = [7, 6, 5, 4, 3, 2, 1, 0]; let indices = [6, 1, 7]; disjoint_sort(&mut array, &indices); println!("{:?}", array); }  
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.
#Standard_ML
Standard ML
fun mygt (s1, s2) = if size s1 <> size s2 then size s2 > size s1 else String.map Char.toLower s1 > String.map Char.toLower s2
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.
#Swift
Swift
import Foundation   var list = ["this", "is", "a", "set", "of", "strings", "to", "sort", "This", "Is", "A", "Set", "Of", "Strings", "To", "Sort"]   list.sortInPlace {lhs, rhs in let lhsCount = lhs.characters.count let rhsCount = rhs.characters.count let result = rhsCount - lhsCount   if result == 0 { return lhs.lowercaseString > rhs.lowercaseString }   return lhsCount > rhsCount }
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.
#Lambdatalk
Lambdatalk
  {def bubblesort {def bubblesort.swap! {lambda {:a :n :i} {if {> :i :n} then :a else {bubblesort.swap! {if {> {A.get :i :a} {A.get {+ :i 1} :a}} then {A.set! :i {A.get {+ :i 1} :a} {A.set! {+ :i 1} {A.get :i :a} :a}} else :a}  :n {+ :i 1}} }}} {def bubblesort.r {lambda {:a :n} {if {<= :n 1} then :a else {bubblesort.r {bubblesort.swap! :a :n 0} {- :n 1}} }}}   {lambda {:a} {bubblesort.r :a {- {A.length :a} 1}}}} -> bubblesort   {bubblesort {A.new 0 3 86 20 27 67 31 16 37 42 8 47 7 84 5 29}} -> [0,3,5,7,8,16,20,27,29,31,37,42,47,67,84,86]  
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.
#Sidef
Sidef
class Array { method gnomesort { var (i=1, j=2); var len = self.len; while (i < len) { if (self[i-1] <= self[i]) { (i, j) = (j, j+1); } else { self[i-1, i] = self[i, i-1]; if (--i == 0) { (i, j) = (j, j+1); } } } return self; } }   var ary = [7,6,5,9,8,4,3,1,2,0]; say ary.gnomesort;