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/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.
#Python
Python
people = [('joe', 120), ('foo', 31), ('bar', 51)] sorted(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.
#R
R
sortbyname <- function(x, ...) x[order(names(x), ...)] x <- c(texas=68.9, ohio=87.8, california=76.2, "new york"=88.2) sortbyname(x)
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.
#Order
Order
#include <order/interpreter.h>   ORDER_PP( 8seq_sort(8less, 8seq(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.
#Oz
Oz
declare Nums = [2 4 3 1 2] Sorted = {List.sort Nums Value.'<'} in {Show Sorted}
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted. Make your example work with the following list of values and set of indices: Values: [7, 6, 5, 4, 3, 2, 1, 0] Indices: {6, 1, 7} Where the correct result would be: [7, 0, 5, 4, 3, 2, 1, 6]. In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead. The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given. Cf.   Order disjoint list items
#XPL0
XPL0
include xpllib; \for Sort routine int Values, Indices, J, I, T; [Values:= [7, 6, 5, 4, 3, 2, 1, 0]; Indices:= [6, 1, 7]; Sort(Indices, 3); for J:= 3-1 downto 0 do \bubble sort values at Indices for I:= 0 to J-1 do if Values(Indices(I)) > Values(Indices(I+1)) then [T:= Values(Indices(I)); Values(Indices(I)):= Values(Indices(I+1)); Values(Indices(I+1)):= T; ]; for I:= 0 to 8-1 do [IntOut(0, Values(I)); ChOut(0, ^ )]; ]
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
#zkl
zkl
values :=T(7, 6, 5, 4, 3, 2, 1, 0); indices:=T(6, 1, 7);   indices.apply(values.get).sort() // a.get(0) == a[0] .zip(indices.sort()) //-->(v,i) == L(L(0,1),L(1,6),L(6,7)) .reduce(fcn(newList,[(v,i)]){ newList[i]=v; newList },values.copy()) .println(); // new list
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.
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
bubbleSort[{w___, x_, y_, z___}] /; x > y := bubbleSort[{w, y, x, z}] bubbleSort[sortedList_] := sortedList bubbleSort[{10, 3, 7, 1, 4, 3, 8, 13, 9}]
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.
#Ursala
Ursala
gnome_sort "p" =   @NiX ^=lx -+ # iteration ~&r?\~& @lNXrX ->llx2rhPlrPCTxPrtPX~&lltPlhPrCXPrX ~&ll&& @llPrXh not "p", # backward bubble ->~&rhPlCrtPX ~&r&& ~&lZ!| @bh "p"+- # forward scan
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
#Swift
Swift
extension Collection where Element: Comparable { public func cocktailSorted() -> [Element] { var swapped = false var ret = Array(self)   guard count > 1 else { return ret }   repeat { for i in 0...ret.count-2 where ret[i] > ret[i + 1] { (ret[i], ret[i + 1]) = (ret[i + 1], ret[i]) swapped = true }   guard swapped else { break }   swapped = false   for i in stride(from: ret.count - 2, through: 0, by: -1) where ret[i] > ret[i + 1] { (ret[i], ret[i + 1]) = (ret[i + 1], ret[i]) swapped = true } } while swapped   return ret } }   let arr = (1...10).shuffled()   print("Before: \(arr)") print("Cocktail sort: \(arr.cocktailSorted())")
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
#Tcl
Tcl
package require Tcl 8.5 package require struct::list   proc cocktailsort {A} { set len [llength $A] set swapped true while {$swapped} { set swapped false for {set i 0} {$i < $len - 1} {incr i} { set j [expr {$i + 1}] if {[lindex $A $i] > [lindex $A $j]} { struct::list swap A $i $j set swapped true } } if { ! $swapped} { break } set swapped false for {set i [expr {$len - 2}]} {$i >= 0} {incr i -1} { set j [expr {$i + 1}] if {[lindex $A $i] > [lindex $A $j]} { struct::list swap A $i $j set swapped true } } } return $A }
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Slate
Slate
[ | socket | [ | addr stream | addr: (Net SocketAddress newOn: '127.0.0.1:256'). socket: (Net Socket newFor: addr domain type: Net Socket Types Stream protocol: Net Socket Protocols Default). socket connectTo: addr. stream: (Net SocketStream newOn: socket). stream nextPutAll: ('hello socket world' as: ByteArray). stream flush ] ensure: [socket close] ] do.
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.
#Smalltalk
Smalltalk
PackageLoader fileInPackage: 'TCP'!   Object subclass: #HelloSocket instanceVariableNames: 'ss' classVariableNames: '' poolDictionaries: '' category: 'SimpleEcho'!   !HelloSocket class methodsFor: 'instance creation'!   port: anInteger | ses | ses := super new. ses init: anInteger. ^ses !!   !HelloSocket methodsFor: 'instance initialization'!   init: anInteger ss := (TCP.ServerSocket port: anInteger). ^self !!   !HelloSocket methodsFor: 'running'!   run | s | [ ss waitForConnection. s := (ss accept). [self handleSocket: s] fork ] repeat !!   !HelloSocket methodsFor: 'handling'!   handleSocket: s | msg | msg := 'hello socket world'. msg displayOn: s. (String with: (Character value: 10)) displayOn: s. s flush !!   Smalltalk at: #helloServer put: (HelloSocket port: 2560).   helloServer run.
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].
#PARI.2FGP
PARI/GP
isSmith(n)=my(f=factor(n)); if(#f~==1 && f[1,2]==1, return(0)); sum(i=1, #f~, sumdigits(f[i, 1])*f[i, 2]) == sumdigits(n); select(isSmith, [1..9999])
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].
#Pascal
Pascal
program SmithNum; {$IFDEF FPC} {$MODE objFPC} //result and useful for x64 {$CODEALIGN PROC=64} {$ENDIF} uses sysutils; type tdigit = byte; tSum = LongInt; const base = 10; //maxDigitCnt *(base-1) <= High(tSum) //maxDigitCnt <= High(tSum) DIV (base-1); maxDigitCnt = 16;   StartPrimNo = 6; csegsieveSIze = 2*3*5*7*11*13;//prime 0..5 type tDgtSum = record dgtNum : LongInt; dgtSum : tSum; dgts : array[0..maxDigitCnt-1] of tdigit; end; tNumFactype = word; tnumFactor = record numfacCnt: tNumFactype; numfacts : array[1..15] of tNumFactype; end; tpnumFactor= ^tnumFactor;   tsieveprim = record spPrim : Word; spDgtsum : Word; spOffset : LongWord; end; tpsieveprim = ^tsieveprim;   tsievePrimarr = array[0..6542-1] of tsieveprim; tsegmSieve = array[1..csegsieveSIze] of tnumFactor;   var Primarr:tsievePrimarr; copySieve, actSieve : tsegmSieve; PrimDgtSum :tDgtSum; PrimCnt : NativeInt;   function IncDgtSum(var ds:tDgtSum):boolean; //add 1 to dgts and corrects sum of Digits //return if overflow happens var i : NativeInt; Begin i := High(ds.dgts); inc(ds.dgtNum); repeat IF ds.dgts[i] < Base-1 then //add one and done Begin inc(ds.dgts[i]); inc(ds.dgtSum); BREAK; end else Begin ds.dgts[i] := 0; dec(ds.dgtSum,Base-1); end; dec(i); until i < Low(ds.dgts); result := i < Low(ds.dgts) end;   procedure OutDgtSum(const ds:tDgtSum); var i : NativeInt; Begin i := Low(ds.dgts); repeat write(ds.dgts[i]:3); inc(i); until i > High(ds.dgts); writeln(' sum of digits : ',ds.dgtSum:3); end;   procedure OutSieve(var s:tsegmSieve); var i,j : NativeInt; Begin For i := Low(s) to High(s) do with s[i] do Begin write(i:6,numfacCnt:4); For j := 1 to numfacCnt do write(numFacts[j]:5); writeln; end; end;   procedure SieveForPrimes; // sieve for all primes < High(Word) var sieve : array of byte; pS : pByte; p,i : NativeInt; Begin setlength(sieve,High(Word)); Fillchar(sieve[Low(sieve)],length(sieve),#0); pS:= @sieve[0]; //zero based dec(pS);// make it one based //sieve p := 2; repeat i := p*p; IF i> High(Word) then BREAK; repeat pS[i] := 1; inc(i,p); until i > High(Word); repeat inc(p) until pS[p] = 0; until false; //now fill array of primes fillchar(PrimDgtSum,SizeOf(PrimDgtSum),#0); IncDgtSum(PrimDgtSum);//1 i := 0; For p := 2 to High(Word) do Begin IncDgtSum(PrimDgtSum); if pS[p] = 0 then Begin with PrimArr[i] do Begin spOffset := 2*p;//start at 2*prime spPrim := p; spDgtsum := PrimDgtSum.dgtSum; end; inc(i); end; end; PrimCnt := i-1; end;   procedure MarkWithPrime(SpIdx:NativeInt;var sf:tsegmSieve); var i : NativeInt; pSf :^tnumFactor; MarkPrime : NativeInt; Begin with Primarr[SpIdx] do Begin MarkPrime := spPrim; i := spOffSet; IF i <= csegsieveSize then Begin pSf := @sf[i]; repeat pSf^.numFacts[pSf^.numfacCnt+1] := SpIdx; inc(pSf^.numfacCnt); inc(pSf,MarkPrime); inc(i,MarkPrime); until i > csegsieveSize; end; spOffset := i-csegsieveSize; end; end;   procedure InitcopySieve(var cs:tsegmSieve); var pr: NativeInt; Begin fillchar(cs[Low(cs)],sizeOf(cs),#0); For Pr := 0 to 5 do Begin with Primarr[pr] do spOffset := spPrim;//mark the prime too MarkWithPrime(pr,cs); end; end;   procedure MarkNextSieve(var s:tsegmSieve); var idx: NativeInt; Begin s:= copySieve; For idx := StartPrimNo to PrimCnt do MarkWithPrime(idx,s); end;   function DgtSumInt(n: NativeUInt):NativeUInt; var r : NativeUInt; Begin result := 0; repeat r := n div base; inc(result,n-base*r); n := r until r = 0; end;   {function DgtSumOfFac(pN: tpnumFactor;dgtNo:tDgtSum):boolean;} function TestSmithNum(pN: tpnumFactor;dgtNo:tDgtSum):boolean; var i,k,r,dgtSumI,dgtSumTarget : NativeUInt; pSp:tpsieveprim; pNumFact : ^tNumFactype; Begin i := dgtNo.dgtNum; dgtSumTarget :=dgtNo.dgtSum;   dgtSumI := 0; with pN^ do Begin k := numfacCnt; pNumFact := @numfacts[k]; end;   For k := k-1 downto 0 do Begin pSp := @PrimArr[pNumFact^]; r := i DIV pSp^.spPrim; repeat i := r; r := r DIV pSp^.spPrim; inc(dgtSumI,pSp^.spDgtsum); until (i - r* pSp^.spPrim) <> 0; IF dgtSumI > dgtSumTarget then Begin result := false; EXIT; end; dec(pNumFact); end; If i <> 1 then inc(dgtSumI,DgtSumInt(i)); result := dgtSumI = dgtSumTarget end;   function CheckSmithNo(var s:tsegmSieve;var dgtNo:tDgtSum;Lmt:NativeInt=csegsieveSIze):NativeUInt; var pNumFac : tpNumFactor; i : NativeInt; Begin result := 0; i := low(s); pNumFac := @s[i]; For i := i to lmt do Begin incDgtSum(dgtNo); IF pNumFac^.numfacCnt<> 0 then IF TestSmithNum(pNumFac,dgtNo) then Begin inc(result); //Mark as smith number inc(pNumFac^.numfacCnt,1 shl 15); end; inc(pNumFac); end; end;   const limit = 100*1000*1000; var actualNo :tDgtSum; i,s : NativeInt; Begin SieveForPrimes; InitcopySieve(copySieve); i := 1; s:= -6;//- 2,3,5,7,11,13   fillchar(actualNo,SizeOf(actualNo),#0); while i < Limit-csegsieveSize do Begin MarkNextSieve(actSieve); inc(s,CheckSmithNo(actSieve,actualNo)); inc(i, csegsieveSize); end; //check the rest MarkNextSieve(actSieve); inc(s,CheckSmithNo(actSieve,actualNo,Limit-i+1)); write(s:8,' smith-numbers up to ',actualNo.dgtnum:10); end.  
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;
#Tcl
Tcl
proc init {initialConfiguration} { global grid max filled set max 1 set y 0 foreach row [split [string trim $initialConfiguration "\n"] "\n"] { set x 0 set rowcontents {} foreach cell $row { if {![string is integer -strict $cell]} {set cell -1} lappend rowcontents $cell set max [expr {max($max, $cell)}] if {$cell > 0} { dict set filled $cell [list $y $x] } incr x } lappend grid $rowcontents incr y } }   proc findseps {} { global max filled set result {} for {set i 1} {$i < $max-1} {incr i} { if {[dict exists $filled $i]} { for {set j [expr {$i+1}]} {$j <= $max} {incr j} { if {[dict exists $filled $j]} { if {$j-$i > 1} { lappend result [list $i $j [expr {$j-$i}]] } break } } } } return [lsort -integer -index 2 $result] }   proc makepaths {sep} { global grid filled lassign $sep from to len lassign [dict get $filled $from] y x set result {} foreach {dx dy} {-1 -1 -1 0 -1 1 0 -1 0 1 1 -1 1 0 1 1} { discover [expr {$x+$dx}] [expr {$y+$dy}] [expr {$from+1}] $to \ [list [list $from $x $y]] $grid } return $result } proc discover {x y n limit path model} { global filled # Check for illegal if {[lindex $model $y $x] != 0} return upvar 1 result result lassign [dict get $filled $limit] ly lx # Special case if {$n == $limit-1} { if {abs($x-$lx)<=1 && abs($y-$ly)<=1 && !($lx==$x && $ly==$y)} { lappend result [lappend path [list $n $x $y] [list $limit $lx $ly]] } return } # Check for impossible if {abs($x-$lx) > $limit-$n || abs($y-$ly) > $limit-$n} return # Recursive search lappend path [list $n $x $y] lset model $y $x $n incr n foreach {dx dy} {-1 -1 -1 0 -1 1 0 -1 0 1 1 -1 1 0 1 1} { discover [expr {$x+$dx}] [expr {$y+$dy}] $n $limit $path $model } }   proc applypath {path} { global grid filled puts "Found unique path for [lindex $path 0 0] -> [lindex $path end 0]" foreach cell [lrange $path 1 end-1] { lassign $cell n x y lset grid $y $x $n dict set filled $n [list $y $x] } }   proc printgrid {} { global grid max foreach row $grid { foreach cell $row { puts -nonewline [format " %*s" [string length $max] [expr { $cell==-1 ? "." : $cell }]] } puts "" } }   proc solveHidato {initialConfiguration} { init $initialConfiguration set limit [llength [findseps]] while {[llength [set seps [findseps]]] && [incr limit -1]>=0} { foreach sep $seps { if {[llength [set paths [makepaths $sep]]] == 1} { applypath [lindex $paths 0] break } } } puts "" printgrid }
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.
#Racket
Racket
  #lang racket   (define data '([Joe 5531] [Adam 2341] [Bernie 122] [Walter 1234] [David 19]))   (sort data < #:key cadr) ;; --> '((David 19) (Bernie 122) (Walter 1234) (Adam 2341) (Joe 5531))   ;; Demonstrating a "key" that is not just a direct element (sort data string<? #:key (compose1 symbol->string car)) ;; --> '((Adam 2341) (Bernie 122) (David 19) (Joe 5531) (Walter 1234))  
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.
#Raku
Raku
my class Employee { has Str $.name; has Rat $.wage; }   my $boss = Employee.new( name => "Frank Myers" , wage => 6755.85 ); my $driver = Employee.new( name => "Aaron Fast" , wage => 2530.40 ); my $worker = Employee.new( name => "John Dude" , wage => 2200.00 ); my $salesman = Employee.new( name => "Frank Mileeater" , wage => 4590.12 );   my @team = $boss, $driver, $worker, $salesman;   my @orderedByName = @team.sort( *.name )».name; my @orderedByWage = @team.sort( *.wage )».name;   say "Team ordered by name (ascending order):"; say @orderedByName.join(' '); say "Team ordered by wage (ascending order):"; say @orderedByWage.join(' ');
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.
#PARI.2FGP
PARI/GP
vecsort(v)
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.
#MATLAB
MATLAB
function list = bubbleSort(list)   hasChanged = true; itemCount = numel(list);   while(hasChanged)   hasChanged = false; itemCount = itemCount - 1;   for index = (1:itemCount)   if(list(index) > list(index+1)) list([index index+1]) = list([index+1 index]); %swap hasChanged = true; end %if   end %for end %while end %bubbleSort
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.
#VBA
VBA
Private Function gnomeSort(s As Variant) As Variant Dim i As Integer: i = 1 Dim j As Integer: j = 2 Dim tmp As Integer Do While i < UBound(s) If s(i) <= s(i + 1) Then i = j j = j + 1 Else tmp = s(i) s(i) = s(i + 1) s(i + 1) = tmp i = i - 1 If i = 0 Then i = j j = j + 1 End If End If Loop gnomeSort = s End Function   Public Sub main() Debug.Print Join(gnomeSort([{5, 3, 1, 7, 4, 1, 1, 20}]), ", ") End Sub
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
#uBasic.2F4tH
uBasic/4tH
PRINT "Cocktail sort:" n = FUNC (_InitArray) PROC _ShowArray (n) PROC _Cocktailsort (n) PROC _ShowArray (n) PRINT   END     _Cocktailsort PARAM (1) ' Cocktail sort LOCAL (2) b@ = 0   DO WHILE b@ = 0 b@ = 1 FOR c@=1 TO a@-1 IF @(c@) < @(c@-1) THEN PROC _Swap (c@, c@-1) : b@ = 0 NEXT UNTIL b@ b@ = 1 FOR c@=a@-1 TO 1 STEP -1 IF @(c@) < @(c@-1) THEN PROC _Swap (c@, c@-1) : b@ = 0 NEXT LOOP RETURN     _Swap PARAM(2) ' Swap two array elements PUSH @(a@) @(a@) = @(b@) @(b@) = POP() RETURN     _InitArray ' Init example array PUSH 4, 65, 2, -31, 0, 99, 2, 83, 782, 1   FOR i = 0 TO 9 @(i) = POP() NEXT   RETURN (i)     _ShowArray PARAM (1) ' Show array subroutine FOR i = 0 TO a@-1 PRINT @(i), NEXT   PRINT RETURN
http://rosettacode.org/wiki/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.
#Symsyn
Symsyn
  '127.0.0.1' $addr connect $addr 256 sok 'hello socket world' [sok] close sok  
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.
#Standard_ML
Standard ML
val txt = Word8VectorSlice.full (Byte.stringToBytes "hello world" ) ; val set = fn socket => fn ipnr => fn portnr => fn text => ( Socket.connect (socket, INetSock.toAddr ( Option.valOf (NetHostDB.fromString(ipnr) ) , portnr )) ; Socket.sendVec(socket, text) before Socket.close socket ) ;  
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Tcl
Tcl
set io [socket localhost 256] puts -nonewline $io "hello socket world" close $io
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].
#Perl
Perl
use ntheory qw/:all/; my @smith; forcomposites { push @smith, $_ if sumdigits($_) == sumdigits(join("",factor($_))); } 10000-1; say scalar(@smith), " Smith numbers below 10000."; say "@smith";
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].
#Phix
Phix
with javascript_semantics function sum_digits(integer n, base=10) integer res = 0 while n do res += remainder(n,base) n = floor(n/base) end while return res end function function smith(integer n) sequence p = prime_factors(n,true,-1) if length(p)=1 then return false end if integer sp = sum(apply(p,sum_digits)), sn = sum_digits(n) return sn=sp end function sequence s = apply(filter(tagset(10000),smith),sprint) printf(1,"%d smith numbers found: %s\n",{length(s),join(shorten(s,"",8),", ")})
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;
#Wren
Wren
import "/sort" for Sort import "/fmt" for Fmt   var board = [] var given = [] var start = []   var setUp = Fn.new { |input| var nRows = input.count var puzzle = List.filled(nRows, null) for (i in 0...nRows) puzzle[i] = input[i].split(" ") var nCols = puzzle[0].count var list = [] board = List.filled(nRows+2, null) for (i in 0...board.count) board[i] = List.filled(nCols+2, -1) for (r in 0...nRows) { var row = puzzle[r] for (c in 0...nCols) { var cell = row[c] if (cell == "_") { board[r + 1][c + 1] = 0 } else if (cell != ".") { var value = Num.fromString(cell) board[r + 1][c + 1] = value list.add(value) if (value == 1) start = [r + 1, c + 1] } } } Sort.quick(list) given = list }   var solve // recursive solve = Fn.new { |r, c, n, next| if (n > given[-1]) return true var back = board[r][c] if (back != 0 && back != n) return false if (back == 0 && given[next] == n) return false var next2 = next if (back == n) next2 = next2 + 1 board[r][c] = n for (i in -1..1) { for (j in -1..1) if (solve.call(r + i, c + j, n + 1, next2)) return true } board[r][c] = back return false }   var printBoard = Fn.new { for (row in board) { for (c in row) { if (c == -1) { System.write(" . ") } else if (c > 0) { Fmt.write("$2d ", c) } else { System.write("__ ") } } System.print() } }   var input = [ "_ 33 35 _ _ . . .", "_ _ 24 22 _ . . .", "_ _ _ 21 _ _ . .", "_ 26 _ 13 40 11 . .", "27 _ _ _ 9 _ 1 .", ". . _ _ 18 _ _ .", ". . . . _ 7 _ _", ". . . . . . 5 _" ] setUp.call(input) printBoard.call() System.print("\nFound:") solve.call(start[0], start[1], 1, 0) printBoard.call()
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.
#REXX
REXX
/*REXX program sorts an array of composite structures (which has two classes of data).*/ #=0 /*number elements in structure (so far)*/ name='tan'  ; value= 0; call add name,value /*tan peanut M&M's are 0% of total*/ name='orange'; value=10; call add name,value /*orange " " " 10% " " */ name='yellow'; value=20; call add name,value /*yellow " " " 20% " " */ name='green' ; value=20; call add name,value /*green " " " 20% " " */ name='red'  ; value=20; call add name,value /*red " " " 20% " " */ name='brown' ; value=30; call add name,value /*brown " " " 30% " " */ call show 'before sort', # say copies('▒', 70) call xSort # call show ' after sort', # exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ add: procedure expose # @.; #=#+1 /*bump the number of structure entries.*/ @.#.color=arg(1); @.#.pc=arg(2) /*construct a entry of the structure. */ return /*──────────────────────────────────────────────────────────────────────────────────────*/ show: procedure expose @.; do j=1 for arg(2) /*2nd arg≡number of structure elements.*/ say right(arg(1),30) right(@.j.color,9) right(@.j.pc,4)'%' end /*j*/ /* [↑] display what, name, value. */ return /*──────────────────────────────────────────────────────────────────────────────────────*/ xSort: procedure expose @.; parse arg N; h=N do while h>1; h=h%2 do i=1 for N-h; j=i; k=h+i do while @.k.color<@.j.color /*swap elements.*/ [email protected]; @[email protected]; @.k.color=_ [email protected]; @.j.pc [email protected]; @.k.pc =_ if h>=j then leave; j=j-h; k=k-h end /*while @.k.color ···*/ end /*i*/ end /*while h>1*/ return
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#Peloton
Peloton
Construct a list of numbers <@ LETCNSLSTLIT>L|65^84^1^25^77^4^47^2^42^44^41^25^69^3^51^45^4^39^</@> Numbers sort as strings <@ ACTSRTENTLST>L</@> <@ SAYDMPLST>L</@> <@ ACTSRTENTLSTLIT>L|__StringDescending</@> <@ SAYDMPLST>L</@>   Construct another list of numbers <@ LETCNSLSTLIT>list|65^84^1^25^77^4^47^2^42^44^41^25^69^3^51^45^4^39^</@> Numbers sorted as numbers <@ ACTSRTENTLSTLIT>list|__Numeric</@> <@ SAYDMPLST>list</@> <@ ACTSRTENTLSTLIT>list|__NumericDescending</@> <@ SAYDMPLST>list</@>
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.
#Perl
Perl
@nums = (2,4,3,1,2); @sorted = sort {$a <=> $b} @nums;
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.
#MAXScript
MAXScript
fn bubbleSort arr = ( while true do ( changed = false for i in 1 to (arr.count - 1) do ( if arr[i] > arr[i+1] then ( swap arr[i] arr[i+1] changed = true ) ) if not changed then exit ) arr )
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.
#VBScript
VBScript
function gnomeSort( a ) dim i dim j i = 1 j = 2 do while i < ubound( a ) + 1 if a(i-1) <= a(i) then i = j j = j + 1 else swap a(i-1), a(i) i = i - 1 if i = 0 then i = j j = j + 1 end if end if loop gnomeSort = a end function   sub swap( byref x, byref y ) dim temp temp = x x = y y = temp end sub
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
#Ursala
Ursala
#import std   ctsort = ^=+ +^|(==?/~&l+ @r+ ~&x++ @x,^/~&)+ ("p". =><> ~&r?\~&C "p"?lrhPX/~&C ~&rhPlrtPCC)^~/not ~&
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.
#Toka
Toka
needs sockets   #! A simple abstraction layer that makes writing trivial servers easy value| server.socket server.connection server.action | [ ( n- ) pBind to server.socket ] is server.setSocket [ ( - ) server.socket pAccept to server.connection ] is server.acceptConnection [ ( - ) server.connection pClose drop ] is server.closeConnection [ ( $- ) >r server.connection r> string.getLength pWrite drop ] is server.send [ ( an- ) server.connection -rot pRead drop ] is server.recieve [ ( qn- ) swap to server.action server.setSocket [ server.acceptConnection server.action invoke server.closeConnection TRUE ] whileTrue ] is server.start   #! The actual server [ " hello socket world" server.send ] 256 server.start
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.
#TXR
TXR
(let* ((server (first (getaddrinfo "localhost" 256))) (sock (open-socket server.family sock-stream))) (sock-connect sock server) (put-string "hello socket world"))
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].
#PicoLisp
PicoLisp
(de factor (N) (make (let (D 2 L (1 2 2 . (4 2 4 2 4 6 2 6 .)) M (sqrt N)) (while (>= M D) (if (=0 (% N D)) (setq M (sqrt (setq N (/ N (link D))))) (inc 'D (pop 'L)) ) ) (link N) ) ) ) (de sumdigits (N) (sum format (chop N)) ) (de smith (X) (make (for N X (let R (factor N) (and (cdr R) (= (sum sumdigits R) (sumdigits N)) (link N) ) ) ) ) ) (let L (smith 10000) (println 'first-10 (head 10 L)) (println 'last-10 (tail 10 L)) (println 'all (length L)) )
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].
#PL.2FI
PL/I
smith: procedure options(main); /* find the digit sum of N */ digitSum: procedure(nn) returns(fixed); declare (n, nn, s) fixed; s = 0; do n=nn repeat(n/10) while(n>0); s = s + mod(n,10); end; return(s); end digitSum;   /* find and count factors of N */ factors: procedure(nn, facs) returns(fixed); declare (n, nn, cnt, fac, facs(16)) fixed; cnt = 0; if nn<=1 then return(0);   /* factors of two */ do n=nn repeat(n/2) while(mod(n,2)=0); cnt = cnt + 1; facs(cnt) = 2; end;   /* take out odd factors */ do fac=3 repeat(fac+2) while(fac <= n); do n=n repeat(n/fac) while(mod(n,fac) = 0); cnt = cnt + 1; facs(cnt) = fac; end; end;   return(cnt); end factors;   /* see if a number is a Smith number */ smith: procedure(n) returns(bit); declare (n, nfacs, facsum, i, facs(16)) fixed; nfacs = factors(n, facs); if nfacs <= 1 then return('0'b); /* primes are not Smith numbers */   facsum = 0; do i=1 to nfacs; facsum = facsum + digitSum(facs(i)); end; return(facsum = digitSum(n)); end smith;   /* print all Smith numbers up to 10000 */ declare (i, cnt) fixed; cnt = 0; do i=2 to 9999; if smith(i) then do; put edit(i) (F(5)); cnt = cnt + 1; if mod(cnt,16) = 0 then put skip; end; end; put skip list('Found', cnt, 'Smith numbers.'); end smith;
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;
#zkl
zkl
hi:= // 0==empty cell, X==not a cell #<<< "0 33 35 0 0 X X X 0 0 24 22 0 X X X 0 0 0 21 0 0 X X 0 26 0 13 40 11 X X 27 0 0 0 9 0 1 X X X 0 0 18 0 0 X X X X X 0 7 0 0 X X X X X X 5 0"; #<<<   board,given,start:=setup(hi); print_board(board); solve(board,given, start.xplode(), 1); println(); print_board(board);
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.
#Ring
Ring
  aList= sort([:Eight = 8, :Two = 2, :Five = 5, :Nine = 9, :One = 1,  :Three = 3, :Six = 6, :Seven = 7, :Four = 4, :Ten = 10] , 2) for item in aList  ? item[1] + space(10-len(item[1])) + item[2] next  
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.
#Ruby
Ruby
Person = Struct.new(:name,:value) do def to_s; "name:#{name}, value:#{value}" end end   list = [Person.new("Joe",3), Person.new("Bill",4), Person.new("Alice",20), Person.new("Harry",3)] puts list.sort_by{|x|x.name} puts puts list.sort_by(&:value)
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.
#Phix
Phix
?sort({9, 10, 3, 1, 4, 5, 8, 7, 6, 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.
#Phixmonti
Phixmonti
include ..\Utilitys.pmt   ( 9 10 3 1 4 5 8 7 6 2 ) sort print
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.
#MMIX
MMIX
Ja IS $127   LOC Data_Segment DataSeg GREG @ Array IS @-Data_Segment OCTA 999,200,125,1,1020,40,4,5,60,100 ArrayLen IS (@-Array-Data_Segment)/8   NL IS @-Data_Segment BYTE #a,0 LOC @+(8-@)&7   Buffer IS @-Data_Segment     LOC #1000 GREG @ sorted IS $5 i IS $6 size IS $1 a IS $0 t IS $20 t1 IS $21 t2 IS $22 % Input: $0 ptr to array, $1 its length (in octabyte) % Trashed: $5, $6, $1, $20, $21, $22 BubbleSort SETL sorted,1 % sorted = true SUB size,size,1 % size-- SETL i,0 % i = 0 3H CMP t,i,size % i < size ? BNN t,1F % if false, end for loop 8ADDU $12,i,a % compute addresses of the ADDU t,i,1 % octas a[i] and a[i+1] 8ADDU $11,t,a LDO t1,$12,0 % get their values LDO t2,$11,0 CMP t,t1,t2 % compare BN t,2F % if t1<t2, next STO t1,$11,0 % else swap them STO t2,$12,0 SETL sorted,0 % sorted = false 2H INCL i,1 % i++ JMP 3B % next (for loop) 1H PBZ sorted,BubbleSort % while sorted is false, loop GO Ja,Ja,0 % Help function (Print an octabyte) % Input: $0 (the octabyte) BufSize IS 64 GREG @ PrintInt8 ADDU t,DataSeg,Buffer % get buffer address ADDU t,t,BufSize % end of buffer SETL t1,0 % final 0 for Fputs STB t1,t,0 1H SUB t,t,1 % t-- DIV $0,$0,10 % ($0,rR) = divmod($0,10) GET t1,rR % get reminder INCL t1,'0' % turn it into ascii digit STB t1,t,0 % store it PBNZ $0,1B % if $0 /= 0, loop OR $255,t,0 % $255 = t TRAP 0,Fputs,StdOut GO Ja,Ja,0 % print and return     Main ADDU $0,DataSeg,Array % $0 = Array address SETL $1,ArrayLen % $1 = Array Len GO Ja,BubbleSort % BubbleSort it SETL $4,ArrayLen % $4 = ArrayLen ADDU $3,DataSeg,Array % $3 = Array address 2H BZ $4,1F % if $4 == 0, break LDO $0,$3,0 % $0 = * ($3 + 0) GO Ja,PrintInt8 % print the octa ADDU $255,DataSeg,NL % add a trailing newline TRAP 0,Fputs,StdOut ADDU $3,$3,8 % next octa SUB $4,$4,1 % $4-- JMP 2B % loop 1H XOR $255,$255,$255 TRAP 0,Halt,0 % exit(0)
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.
#Vlang
Vlang
fn main() { mut a := [170, 45, 75, -90, -802, 24, 2, 66] println("before: $a") gnome_sort(mut a) println("after: $a") }   fn gnome_sort(mut a []int) { for i, j := 1, 2; i < a.len; { if a[i-1] > a[i] { a[i-1], a[i] = a[i], a[i-1] i-- if i > 0 { continue } } i = j j++ } }
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
#Vala
Vala
void swap(int[] array, int i1, int i2) { if (array[i1] == array[i2]) return; var tmp = array[i1]; array[i1] = array[i2]; array[i2] = tmp; }   void cocktail_sort(int[] array) { while(true) { bool flag = false; int[] start = {1, array.length - 1}; int[] end = {array.length, 0}; int[] inc = {1, -1}; for (int it = 0; it < 2; ++it) { flag = true; for (int i = start[it]; i != end[it]; i += inc[it]) if (array[i - 1] > array[i]) { swap(array, i - 1, i); flag = false; } } if (flag) return; } }   void main() { int[] array = {5, -1, 101, -4, 0, 1, 8, 6, 2, 3}; cocktail_sort(array); foreach (int i in array) { stdout.printf("%d ", i); } }
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.
#UNIX_Shell
UNIX Shell
echo "hello socket world" | nc localhost 256
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.
#Ursa
Ursa
decl port p p.connect "localhost" 256 out "hello socket world" endl p p.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.
#Visual_Basic_.NET
Visual Basic .NET
Imports System Imports System.IO Imports System.Net.Sockets   Public Class Program Public Shared Sub Main(ByVal args As String[]) Dim tcp As New TcpClient("localhost", 256) Dim writer As New StreamWriter(tcp.GetStream())   writer.Write("hello socket world") writer.Flush()   tcp.Close() End Sub End Class
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].
#PL.2FM
PL/M
100H:   /* CP/M BDOS FUNCTIONS */ BDOS: PROCEDURE (F,A); DECLARE F BYTE, A ADDRESS; GO TO 5; END BDOS; EXIT: PROCEDURE; GO TO 0; END EXIT; PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;   /* PRINT NUMBER */ PR$NUM: PROCEDURE (N); DECLARE S (6) BYTE INITIAL (' $'); DECLARE N ADDRESS, I BYTE; I = 5; DIGIT: S(I := I-1) = '0' + N MOD 10; IF (N := N / 10) > 0 THEN GO TO DIGIT; DO WHILE I>0; S(I := I-1) =' '; END; CALL PRINT(.S); END PR$NUM;   /* SUM OF DIGITS OF N */ DIGIT$SUM: PROCEDURE (N) BYTE; DECLARE N ADDRESS, SUM BYTE; SUM = 0; DO WHILE N > 0; SUM = SUM + N MOD 10; N = N / 10; END; RETURN SUM; END DIGIT$SUM;   /* FIND AND COUNT FACTORS OF N */ FACTORS: PROCEDURE (N, FACBUF) BYTE; DECLARE (N, FACBUF, FAC, FACS BASED FACBUF) ADDRESS; DECLARE COUNT BYTE; COUNT = 0; IF N <= 1 THEN RETURN 0;   /* TAKE OUT FACTORS OF TWO */ DO WHILE NOT N; FACS(COUNT) = 2; COUNT = COUNT + 1; N = SHR(N, 1); END;   /* TAKE OUT ODD FACTORS */ FAC = 3; DO WHILE FAC <= N; DO WHILE N MOD FAC = 0; N = N / FAC; FACS(COUNT) = FAC; COUNT = COUNT + 1; END; FAC = FAC + 2; END;   RETURN COUNT; END FACTORS;   /* SEE IF A NUMBER IS A SMITH NUMBER */ SMITH: PROCEDURE (N) BYTE; DECLARE FACS (16) ADDRESS; DECLARE N ADDRESS, (F, NFACS, FACSUM) BYTE; IF (NFACS := FACTORS(N, .FACS)) <= 1 THEN RETURN 0; /* PRIMES ARE NOT SMITH NUMBERS */   FACSUM = 0; DO F = 0 TO NFACS-1; FACSUM = FACSUM + DIGIT$SUM(FACS(F)); END;   RETURN FACSUM = DIGIT$SUM(N); END SMITH;   /* PRINT ALL SMITH NUMBERS UP TO 10.000 */ DECLARE (I, COUNT) ADDRESS; COUNT = 0; DO I = 2 TO 9$999; IF SMITH(I) THEN DO; CALL PR$NUM(I); COUNT = COUNT + 1; IF (COUNT AND 0FH) = 0 THEN CALL PRINT(.(13,10,'$')); END; END; CALL PRINT(.(13,10,'FOUND $')); CALL PR$NUM(COUNT); CALL PRINT(.' SMITH NUMBERS.$'); CALL EXIT; EOF
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.
#Run_BASIC
Run BASIC
sqliteconnect #mem, ":memory:" ' create in memory db mem$ = "CREATE TABLE people(num integer, name text,city text)" #mem execute(mem$) data "1","George","Redding","2","Fred","Oregon","3","Ben","Seneca","4","Steve","Fargo","5","Frank","Houston"   for i = 1 to 5 ' read data and place in memory DB read num$ :read name$: read city$ #mem execute("INSERT INTO people VALUES(";num$;",'";name$;"','";city$;"')") next i #mem execute("SELECT * FROM people ORDER BY name") 'sort by name order WHILE #mem hasanswer() #row = #mem #nextrow() num = #row num() name$ = #row name$() city$ = #row city$() print num;" ";name$;" ";city$ WEND
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.
#Rust
Rust
use std::cmp::Ordering;   #[derive(Debug)] struct Employee { name: String, category: String, }   impl Employee { fn new(name: &str, category: &str) -> Self { Employee { name: name.into(), category: category.into(), } } }   impl PartialEq for Employee { fn eq(&self, other: &Self) -> bool { self.name == other.name } }   impl Eq for Employee {}   impl PartialOrd for Employee { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } }   impl Ord for Employee { fn cmp(&self, other: &Self) -> Ordering { self.name.cmp(&other.name) } }   fn main() { let mut employees = vec![ Employee::new("David", "Manager"), Employee::new("Alice", "Sales"), Employee::new("Joanna", "Director"), Employee::new("Henry", "Admin"), Employee::new("Tim", "Sales"), Employee::new("Juan", "Admin"), ]; employees.sort(); for e in employees { println!("{:<6} : {}", e.name, e.category); } }
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.
#PHP
PHP
<?php $nums = array(2,4,3,1,2); sort($nums); ?>
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#PicoLisp
PicoLisp
(sort (2 4 3 1 2)) -> (1 2 2 3 4)
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.
#Modula-2
Modula-2
PROCEDURE BubbleSort(VAR a: ARRAY OF INTEGER); VAR changed: BOOLEAN; temp, count, i: INTEGER; BEGIN count := HIGH(a); REPEAT changed := FALSE; DEC(count); FOR i := 0 TO count DO IF a[i] > a[i+1] THEN temp := a[i]; a[i] := a[i+1]; a[i+1] := temp; changed := TRUE END END UNTIL NOT changed END BubbleSort;
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.
#Wren
Wren
var gnomeSort = Fn.new { |a, asc| var size = a.count var i = 1 var j = 2 while (i < size) { if ((asc && a[i-1] <= a[i]) || (!asc && a[i-1] >= a[i])) { i = j j = j + 1 } else { var t = a[i-1] a[i-1] = a[i] a[i] = t i = i - 1 if (i == 0) { i = j j = j + 1 } } } }   var as = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ]   for (asc in [true, false]) { System.print("Sorting in %(asc ? "ascending" : "descending") order:\n") for (a in as) { var b = (asc) ? a : a.toList System.print("Before: %(b)") gnomeSort.call(b, asc) System.print("After : %(b)") System.print() } }
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) The cocktail shaker sort is an improvement on the Bubble Sort. The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia): function cocktailSort( A : list of sortable items ) do swapped := false for each i in 0 to length( A ) - 2 do if A[ i ] > A[ i+1 ] then // test whether the two // elements are in the wrong // order swap( A[ i ], A[ i+1 ] ) // let the two elements // change places swapped := true; if swapped = false then // we can exit the outer loop here if no swaps occurred. break do-while loop; swapped := false for each i in length( A ) - 2 down to 0 do if A[ i ] > A[ i+1 ] then swap( A[ i ], A[ i+1 ] ) swapped := true; while swapped; // if no elements have been swapped, // then the list is sorted Related task   cocktail sort with shifting bounds
#VBA
VBA
Function cocktail_sort(ByVal s As Variant) As Variant Dim swapped As Boolean Dim f As Integer, t As Integer, d As Integer, tmp As Integer swapped = True f = 1 t = UBound(s) - 1 d = 1 Do While swapped swapped = 0 For i = f To t Step d If Val(s(i)) > Val(s(i + 1)) Then tmp = s(i) s(i) = s(i + 1) s(i + 1) = tmp swapped = True End If Next i '-- swap to and from, and flip direction. '-- additionally, we can reduce one element to be '-- examined, depending on which way we just went. tmp = f f = t + (d = 1) t = tmp + (d = -1) d = -d Loop cocktail_sort = s End Function   Public Sub main() Dim s(9) As Variant For i = 0 To 9 s(i) = CStr(Int(1000 * Rnd)) Next i Debug.Print Join(s, ", ") Debug.Print Join(cocktail_sort(s), ", ") End Sub
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.
#Wren
Wren
/* sockets.wren */   var AF_UNSPEC = 0 var SOCK_STREAM = 1   foreign class AddrInfo { foreign static getAddrInfo(name, service, req, pai)   construct new() {}   foreign family   foreign family=(f)   foreign sockType   foreign sockType=(st)   foreign protocol   foreign addr   foreign addrLen }   foreign class AddrInfoPtr { construct new() {}   foreign deref   foreign free() }   foreign class SockAddrPtr { construct new() {} }   class Socket { foreign static create(domain, type, protocol)   foreign static connect(fd, addr, len)   foreign static send(fd, buf, n, flags)   foreign static close(fd) }   var msg = "hello socket world\n" var hints = AddrInfo.new() hints.family = AF_UNSPEC hints.sockType = SOCK_STREAM var addrInfoPtr = AddrInfoPtr.new() if (AddrInfo.getAddrInfo("localhost", "256", hints, addrInfoPtr) == 0){ var addrs = addrInfoPtr.deref var sock = Socket.create(addrs.family, addrs.sockType, addrs.protocol) if (sock >= 0) { var stat = Socket.connect(sock, addrs.addr, addrs.addrLen) if (stat >= 0) { var pm = msg while (true) { var len = pm.count var slen = Socket.send(sock, pm, len, 0) if (slen < 0 || slen >= len) break pm = pm[slen..-1] } } var status = Socket.close(sock) if (status != 0) System.print("Failed to close socket.") } addrInfoPtr.free() }
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].
#PureBasic
PureBasic
DisableDebugger #ECHO=#True ; #True: Print all results Global NewList f.i()   Procedure.i ePotenz(Wert.i) Define.i var=Wert, i While var i+1 var/10 Wend ProcedureReturn i EndProcedure   Procedure.i n_Element(Wert.i,Stelle.i=1) If Stelle>0 ProcedureReturn (Wert%Int(Pow(10,Stelle))-Wert%Int(Pow(10,Stelle-1)))/Int(Pow(10,Stelle-1)) Else ProcedureReturn 0 EndIf EndProcedure   Procedure.i qSumma(Wert.i) Define.i sum, pos For pos=1 To ePotenz(Wert) sum+ n_Element(Wert,pos) Next pos ProcedureReturn sum EndProcedure   Procedure.b IsPrime(n.i) Define.i i=5 If n<2 : ProcedureReturn #False : EndIf If n%2=0 : ProcedureReturn Bool(n=2) : EndIf If n%3=0 : ProcedureReturn Bool(n=3) : EndIf While i*i<=n If n%i=0 : ProcedureReturn #False : EndIf i+2 If n%i=0 : ProcedureReturn #False : EndIf i+4 Wend ProcedureReturn #True EndProcedure   Procedure PFZ(n.i,pf.i=2) If n>1 And n<>pf If n%pf=0 AddElement(f()) : f()=pf PFZ(n/pf,pf) Else While Not IsPrime(pf+1) : pf+1 : Wend PFZ(n,pf+1) EndIf ElseIf n=pf AddElement(f()) : f()=pf EndIf EndProcedure   OpenConsole("Smith numbers") ;upto=100 : sn=0 : Gosub Smith_loop ;upto=1000 : sn=0 : Gosub Smith_loop upto=10000 : sn=0 : Gosub Smith_loop Input() End   Smith_loop: For i=2 To upto ClearList(f()) : qs=0 PFZ(i) CompilerIf #ECHO : Print(Str(i)+~": \t") : CompilerEndIf ForEach f() CompilerIf #ECHO : Print(Str(F())+~"\t") : CompilerEndIf qs+qSumma(f()) Next If ListSize(f())>1 And qSumma(i)=qs CompilerIf #ECHO : Print("SMITH-NUMBER") : CompilerEndIf sn+1 EndIf CompilerIf #ECHO : PrintN("") : CompilerEndIf Next Print(~"\n"+Str(sn)+" Smith number up to "+Str(upto)) Return
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.
#Scala
Scala
case class Pair(name:String, value:Double) val input = Array(Pair("Krypton", 83.798), Pair("Beryllium", 9.012182), Pair("Silicon", 28.0855)) input.sortBy(_.name) // Array(Pair(Beryllium,9.012182), Pair(Krypton,83.798), Pair(Silicon,28.0855))   // alternative versions: input.sortBy(struct => (struct.name, struct.value)) // additional sort field (name first, then value) input.sortWith((a,b) => a.name.compareTo(b.name) < 0) // arbitrary comparison function
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.
#PL.2FI
PL/I
DCL (T(10)) FIXED BIN(31); /* scratch space of length N/2 */   MERGE: PROCEDURE (A,LA,B,LB,C); DECLARE (A(*),B(*),C(*)) FIXED BIN(31); DECLARE (LA,LB) FIXED BIN(31) NONASGN; DECLARE (I,J,K) FIXED BIN(31);   I=1; J=1; K=1; DO WHILE ((I <= LA) & (J <= LB)); IF(A(I) <= B(J)) THEN DO; C(K)=A(I); K=K+1; I=I+1; END; ELSE DO; C(K)=B(J); K=K+1; J=J+1; END; END; DO WHILE (I <= LA); C(K)=A(I); I=I+1; K=K+1; END; RETURN; END MERGE;   MERGESORT: PROCEDURE (A,N) RECURSIVE ; DECLARE (A(*)) FIXED BINARY(31); DECLARE N FIXED BINARY(31) NONASGN; DECLARE Temp FIXED BINARY; DECLARE (M,I) FIXED BINARY; DECLARE AMP1(N) FIXED BINARY(31) BASED(P); DECLARE P POINTER; IF (N=1) THEN RETURN; M = trunc((N+1)/2); IF (M>1) THEN CALL MERGESORT(A,M); P=ADDR(A(M+1)); IF (N-M > 1) THEN CALL MERGESORT(AMP1,N-M); IF A(M) <= AMP1(1) THEN RETURN; DO I=1 to M; T(I)=A(I); END; CALL MERGE(T,M,AMP1,N-M,A); RETURN; END MERGESORT;
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.
#Modula-3
Modula-3
MODULE Bubble;   PROCEDURE Sort(VAR a: ARRAY OF INTEGER) = VAR sorted: BOOLEAN; temp, len: INTEGER := LAST(a); BEGIN WHILE NOT sorted DO sorted := TRUE; DEC(len); FOR i := FIRST(a) TO len DO IF a[i+1] < a[i] THEN temp := a[i]; a[i] := a[i + 1]; a[i + 1] := temp; sorted := FALSE; END; END; END; END Sort; END Bubble.
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.
#XPL0
XPL0
code ChOut=8, IntOut=11;   proc GnomeSort(A(0..Size-1)); \Sort array A int A, Size; int I, J, T; [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 [T:= A(I-1); A(I-1):= A(I); A(I):= T; \swap I:= I-1; if I = 0 then [I:= J; J:= J+1; ]; ]; ];   int A, I; [A:= [3, 1, 4, 1, -5, 9, 2, 6, 5, 4]; GnomeSort(A, 10); for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )]; ]
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
#VBScript
VBScript
function cocktailSort( byval a ) dim swapped dim i do swapped = false for i = 0 to ubound( a ) - 1 if a(i) > a(i+1) then swap a(i), a(i+1) swapped = true end if next if not swapped then exit do swapped = false for i = ubound( a ) - 1 to 0 step -1 if a(i) > a( i+1) then swap a(i), a(i+1) swapped = true end if next if not swapped then exit do loop cocktailSort = a end function   sub swap( byref a, byref b) dim tmp tmp = a a = b b = tmp end sub
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.
#X86_Assembly
X86 Assembly
  ;using sockets on linux with the 0x80 inturrprets. ; ;assemble ; nasm -o socket.o -f elf32 -g socket.asm ;link ; ld -o socket socket.o ; ; ;Just some assigns for better readability   %assign SOCK_STREAM 1 %assign AF_INET 2 %assign SYS_socketcall 102 %assign SYS_SOCKET 1 %assign SYS_CONNECT 3 %assign SYS_SEND 9 %assign SYS_RECV 10   section .text global _start   ;-------------------------------------------------- ;Functions to make things easier. :] ;-------------------------------------------------- _socket: mov [cArray+0], dword AF_INET mov [cArray+4], dword SOCK_STREAM mov [cArray+8], dword 0 mov eax, SYS_socketcall mov ebx, SYS_SOCKET mov ecx, cArray int 0x80 ret   _connect: call _socket mov dword [sock], eax mov dx, si mov byte [edi+3], dl mov byte [edi+2], dh mov [cArray+0], eax ;sock; mov [cArray+4], edi ;&sockaddr_in; mov edx, 16 mov [cArray+8], edx ;sizeof(sockaddr_in); mov eax, SYS_socketcall mov ebx, SYS_CONNECT mov ecx, cArray int 0x80 ret   _send: mov edx, [sock] mov [sArray+0],edx mov [sArray+4],eax mov [sArray+8],ecx mov [sArray+12], dword 0 mov eax, SYS_socketcall mov ebx, SYS_SEND mov ecx, sArray int 0x80 ret   _exit: push 0x1 mov eax, 1 push eax int 0x80   _print: mov ebx, 1 mov eax, 4 int 0x80 ret ;-------------------------------------------------- ;Main code body ;--------------------------------------------------   _start: mov esi, szIp mov edi, sockaddr_in xor eax,eax xor ecx,ecx xor edx,edx .cc: xor ebx,ebx .c: lodsb inc edx sub al,'0' jb .next imul ebx,byte 10 add ebx,eax jmp short .c .next: mov [edi+ecx+4],bl inc ecx cmp ecx,byte 4 jne .cc   mov word [edi], AF_INET mov esi, szPort xor eax,eax xor ebx,ebx .nextstr1: lodsb test al,al jz .ret1 sub al,'0' imul ebx,10 add ebx,eax jmp .nextstr1 .ret1: xchg ebx,eax mov [sport], eax   mov si, [sport] call _connect cmp eax, 0 jnz short _fail mov eax, msg mov ecx, msglen call _send call _exit   _fail: mov edx, cerrlen mov ecx, cerrmsg call _print call _exit     _recverr: call _exit _dced: call _exit   section .data cerrmsg db 'failed to connect :(',0xa cerrlen equ $-cerrmsg msg db 'Hello socket world!',0xa msglen equ $-msg   szIp db '127.0.0.1',0 szPort db '256',0   section .bss sock resd 1 ;general 'array' for syscall_socketcall argument arg. cArray resd 1 resd 1 resd 1 resd 1   ;send 'array'. sArray resd 1 resd 1 resd 1 resd 1 ;duh? sockaddr_in resb 16 ;.. sport resb 2 buff resb 1024  
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].
#Python
Python
from sys import stdout     def factors(n): rt = [] f = 2 if n == 1: rt.append(1); else: while 1: if 0 == ( n % f ): rt.append(f); n //= f if n == 1: return rt else: f += 1 return rt     def sum_digits(n): sum = 0 while n > 0: m = n % 10 sum += m n -= m n //= 10   return sum     def add_all_digits(lst): sum = 0 for i in range (len(lst)): sum += sum_digits(lst[i])   return sum     def list_smith_numbers(cnt): for i in range(4, cnt): fac = factors(i) if len(fac) > 1: if sum_digits(i) == add_all_digits(fac): stdout.write("{0} ".format(i) )   # entry point list_smith_numbers(10_000)
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.
#Seed7
Seed7
$ include "seed7_05.s7i";   const type: pair is new struct var string: name is ""; var string: value is ""; end struct;   const func integer: compare (in pair: pair1, in pair: pair2) is return compare(pair1.name, pair2.name);   const func string: str (in pair: aPair) is return "(" <& aPair.name <& ", " <& aPair.value <& ")";   enable_output(pair);   const func pair: pair (in string: name, in string: value) is func result var pair: newPair is pair.value; begin newPair.name := name; newPair.value := value; end func;   var array pair: data is [] ( pair("Joe", "5531"), pair("Adam", "2341"), pair("Bernie", "122"), pair("Walter", "1234"), pair("David", "19"));   const proc: main is func local var pair: aPair is pair.value; begin data := sort(data); for aPair range data do writeln(aPair); end for; end func;
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.
#Sidef
Sidef
# Declare an array of pairs var people = [['joe', 120], ['foo', 31], ['bar', 51]];   # Sort the array in-place by name people.sort! {|a,b| a[0] <=> b[0] };   # Alternatively, we can use the `.sort_by{}` method var sorted = people.sort_by { |item| item[0] };   # Display the sorted array say people;
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.
#Pop11
Pop11
lvars ar = {2 4 3 1 2}; ;;; Convert array to list. ;;; destvector leaves its results and on the pop11 stack + an integer saying how many there were destvector(ar); ;;; conslist uses the items left on the stack plus the integer, to make a list of those items. lvars ls = conslist(); ;;; Sort it sort(ls) -> ls; ;;; Convert list to array destlist(ls); consvector() -> ar;
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.
#Potion
Potion
(7, 5, 1, 2, 3, 8, 9) sort join(", ") print
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.
#N.2Ft.2Froff
N/t/roff
  .ig Bubble sort algorithm in Troff ==============================   :For: Rosetta Code :Author: Stephanie Björk (Katt) :Date: December 1, 2017 .. .ig Array implementation: \(*A --------------------------- This is an array implementation that takes advantage of Troff's numerical registers. Registers ``Ax``, where ``x`` is a base-10 Hindu-Arabic numeral and 0 < ``x`` < \(if, are used by array \(*A. The array counter which holds the number of items in the array is stored in register ``Ac``. This array implementation is one-indexed (array elements count from 1), though it could be hardcoded again to become zero-indexed depending on what the programmer favours. .. .nr Ac 0 1 \" Array counter . .de APUSH .nr A\\n+(Ac \\$1 .. \" de APUSH . .de AREADLN .APUSH \\$1 .if \\n(.$>1 \{ \ . shift . AREADLN \\$* \} \" if \\n(.$>1 .. \" de AREADLN . .de ASWAP .nr tmp \\n[A\\$1] .nr A\\$1 \\n[A\\$2] .nr A\\$2 \\n[tmp] .rm tmp .. \" de ASWAP . .de ASORT .nr swapped 1 .nr Ad \\n(Ac+1 .while \\n[swapped] \{ \ . nr swapped 0 . nr Ai 1 . nr Ad -1 . while \\n(Ai<\\n(Ad \{ \ . nr Aj \\n(Ai+1 . if \\n[A\\n(Ai]>\\n[A\\n(Aj] \{ \ . ASWAP \\n(Ai \\n(Aj . nr swapped 1 \} \" if \\n[A\\n(Ai]>\\n[A\\n(Aj] . nr Ai +1 \} \" while \\n(Ai<\\n(Ac \} \" while \\n[swapped] .. \" de ASORT . .ig Begin Program ------------- The program's procedural body. Here, we push all our potentially-unsorted integer tokens sequentially, call a subroutine to sort them, and print all the sorted items. .. .AREADLN 12 87 23 77 0 66 45 92 3 0 2 1 9 9 5 4 4 4 \" Our input items to sort. .ASORT \" Sort all items in the array. . .\" Output sorted items .nr Ai 0 1 .while \n(Ai<\n(Ac \n[A\n+[Ai]]  
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.
#zkl
zkl
fcn gnomeSort(a){ i,j,size := 1,2,a.len(); while(i < size){ if(a[i-1] > a[i]){ // for descending sort, use < for comparison a.swap(i-1,i); i = i - 1; if(i) continue; } i = j; j = j + 1; }//while a }
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
#Vlang
Vlang
fn cocktail(mut arr []int) { input := 'Input' output := 'Output' println('${input : -7s}: ${arr.str()}') for { mut swapped := false for i := 0; i < arr.len - 1; i++ { if arr[i] > arr[i + 1] { temp := arr[i] arr[i] = arr[i + 1] arr[i + 1] = temp swapped = true } } if !swapped { break } swapped = false for i := arr.len - 2; i >= 0; i-- { if arr[i] > arr[i + 1] { temp := arr[i] arr[i] = arr[i + 1] arr[i + 1] = temp swapped = true } } if !swapped { break } } println('${output : -7s}: ${arr.str()}') }   fn main() { mut arr := [6, 9, 1, 4] cocktail(mut arr) arr = [-8, 15, 1, 4, -3, 20] cocktail(mut arr) }
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#X86-64_Assembly
X86-64 Assembly
  option casemap:none option literals:on   ifndef __SOCKET_CLASS__ __SOCKET_CLASS__ equ 1   if @Platform eq windows64   WSADATA struct wVersion dw ? wHighVersion dw ? iMaxSockets dw ? iMaxUdpDg dw ? szDescription db 256 dup (?) szSystemStatus db 128 dup (?) lpVendorInfo dq ? WSADATA ends   option dllimport:<kernel32> ExitProcess proto :word HeapAlloc proto :qword, :dword, :qword HeapFree proto :qword, :dword, :qword GetProcessHeap proto   option dllimport:<ws2_32> WSAStartup proto :word, :qword WSACleanup proto :qword closesocket proto :dword   option dllimport:none exit equ ExitProcess close equ closesocket   elseif @Platform eq linux64 malloc proto SYSTEMV :qword free proto SYSTEMV :qword close proto SYSTEMV :dword exit proto SYSTEMV :dword   endif   memset proto :qword, :dword, :dword printf proto :qword, :vararg strlen proto :qword getaddrinfo proto :qword, :qword, :qword, :qword gai_strerror proto :dword send proto :dword, :qword, :qword, :dword socket proto :dword, :dword, :dword connect proto :dword, :qword, :dword freeaddrinfo proto :qword   CLASS socket_class CMETHOD conn CMETHOD write ENDMETHODS if @Platform eq windows64 wsa WSADATA <?> endif sock dd 0 pai dq 0 hostname dq ? port dq ? ENDCLASS   METHOD socket_class, Init, <VOIDARG>, <>, h:qword, p:qword mov rbx, thisPtr assume rbx:ptr socket_class mov rax, h mov [rbx].hostname, rax mov rax, p mov [rbx].port, rax mov rax, rbx assume rbx:nothing ret ENDMETHOD   METHOD socket_class, conn, <dword>, <> local ht:qword   mov rbx, thisPtr assume rbx:ptr socket_class invoke printf, CSTR("--> Attempting connection to %s on %s",10), [rbx].hostname ,[rbx].port if @Platform eq windows64 invoke WSAStartup, 202h, addr [rbx].wsa endif invoke memset, ht, 0, 0x30 ;; sizeof(struct addrinfo) mov rax, ht mov dword ptr [rax], 0 ;; ai_flags mov dword ptr [rax+4], AF_INET mov dword ptr [rax+8], SOCK_STREAM invoke getaddrinfo, [rbx].hostname, [rbx].port, ht, addr [rbx].pai .if rax != 0 invoke gai_strerror, eax invoke printf, CSTR("--> Gai_strerror returned: %s",10), rax mov rax, -1 jmp _exit .endif mov rax, [rbx].pai mov edx, dword ptr [rax + 0XC] ;; pai.ai_protocol mov ecx, dword ptr [rax + 8] ;; pai.ai_socktype mov eax, dword ptr [rax + 4] ;; pai.ai_family invoke socket, eax, ecx, edx .if rax == -1 mov rax, -1 jmp _exit .endif mov [rbx].sock, eax invoke printf, CSTR("--> Socket created as: %d",10), [rbx].sock mov rax, [rbx].pai mov edx, dword ptr [rax + 0x10] ;; pai.ai_addrlen mov rcx, qword ptr [rax + 0x18] ;; pai.ai_addr invoke connect, [rbx].sock, rcx, edx .if rax == -1 invoke printf, CSTR("--> connect failed.. %i",10), rax mov rax, -1 jmp _exit .endif mov rax, 0   _exit: assume rbx:nothing ret ENDMETHOD   METHOD socket_class, write, <dword>, <>, b:qword local tmp:qword   mov rbx, thisPtr assume rbx:ptr socket_class mov rax, b mov tmp, rax invoke strlen, tmp invoke send, [rbx].sock, tmp, rax, 0 .if eax == -1 invoke printf, CSTR("--> Error in send..%d",10), rax ret .endif assume rbx:nothing ret ENDMETHOD   METHOD socket_class, Destroy, <VOIDARG>, <> mov rbx, thisPtr assume rbx:ptr socket_class invoke close, [rbx].sock if @Platform eq windows64 invoke WSACleanup, addr [rbx].wsa endif .if [rbx].pai != 0 invoke freeaddrinfo, [rbx].pai .endif assume rbx:nothing ret ENDMETHOD endif ;; __SOCKET_CLASS__   .code main proc local lpSocket:ptr socket_class   mov lpSocket, _NEW(socket_class, CSTR("localhost"), CSTR("256")) lpSocket->conn() .if rax == -1 invoke exit, 0 ret .endif invoke printf, CSTR("-> Connected, sending data.",10) lpSocket->write(CSTR("Goodbye, socket world!",10)) _DELETE(lpSocket) invoke exit, 0 ret main endp   end    
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers. Example Using the number 166 Find the prime factors of 166 which are: 2 x 83 Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13 Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13 Therefore, the number 166 is a Smith number. Task Write a program to find all Smith numbers below 10000. See also from Wikipedia:   [Smith number]. from MathWorld:   [Smith number]. from OEIS A6753:   [OEIS sequence A6753]. from OEIS A104170:   [Number of Smith numbers below 10^n]. from The Prime pages:   [Smith numbers].
#Racket
Racket
#lang racket (require math/number-theory)   (define (sum-of-digits n) (let inr ((n n) (s 0)) (if (zero? n) s (let-values (([q r] (quotient/remainder n 10))) (inr q (+ s r))))))   (define (smith-number? n) (and (not (prime? n)) (= (sum-of-digits n) (for/sum ((pe (in-list (factorize n)))) (* (cadr pe) (sum-of-digits (car pe)))))))   (module+ test (require rackunit) (check-equal? (sum-of-digits 0) 0) (check-equal? (sum-of-digits 33) 6) (check-equal? (sum-of-digits 30) 3)   (check-true (smith-number? 166)))   (module+ main (let loop ((ns (filter smith-number? (range 1 (add1 10000))))) (unless (null? ns) (let-values (([l r] (split-at ns (min (length ns) 15)))) (displayln l) (loop r)))))
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].
#Raku
Raku
constant @primes = 2, |(3, 5, 7 ... *).grep: *.is-prime;   multi factors ( 1 ) { 1 } multi factors ( Int $remainder is copy ) { gather for @primes -> $factor {   # if remainder < factor², we're done if $factor * $factor > $remainder { take $remainder if $remainder > 1; last; }   # How many times can we divide by this prime? while $remainder %% $factor { take $factor; last if ($remainder div= $factor) === 1; } } } # Code above here is verbatim from RC:Count_in_factors#Raku   sub is_smith_number ( Int $n ) { (!$n.is-prime) and ( [+] $n.comb ) == ( [+] factors($n).join.comb ); }   my @s = grep &is_smith_number, 2 ..^ 10_000; say "{@s.elems} Smith numbers below 10_000"; say 'First 10: ', @s[ ^10 ]; say 'Last 10: ', @s[ *-10 .. * ];
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.
#Simula
Simula
BEGIN   CLASS COMPARABLE;;   COMPARABLE CLASS PAIR(N,V); TEXT N,V;;   CLASS COMPARATOR; VIRTUAL: PROCEDURE COMPARE IS INTEGER PROCEDURE COMPARE(A, B); REF(COMPARABLE) A, B;; BEGIN END**OF**COMPARATOR;   COMPARATOR CLASS PAIRBYNAME; BEGIN INTEGER PROCEDURE COMPARE(A, B); REF(COMPARABLE) A, B; BEGIN COMPARE := IF A QUA PAIR.N < B QUA PAIR.N THEN -1 ELSE IF A QUA PAIR.N > B QUA PAIR.N THEN +1 ELSE 0; END; END**OF**PAIRBYNAME;   PROCEDURE BUBBLESORT(A, C); NAME A; REF(COMPARABLE) ARRAY A; REF(COMPARATOR) C; BEGIN INTEGER LOW, HIGH, I; BOOLEAN SWAPPED;   PROCEDURE SWAP(I, J); INTEGER I, J; BEGIN REF(COMPARABLE) TEMP; TEMP :- A(I); A(I) :- A(J); A(J) :- TEMP; END**OF**SWAP;   LOW := LOWERBOUND(A, 1); HIGH := UPPERBOUND(A, 1); SWAPPED := TRUE; WHILE SWAPPED DO BEGIN SWAPPED := FALSE; FOR I := LOW + 1 STEP 1 UNTIL HIGH DO BEGIN COMMENT IF THIS PAIR IS OUT OF ORDER ; IF C.COMPARE(A(I - 1), A(I)) > 0 THEN BEGIN COMMENT SWAP THEM AND REMEMBER SOMETHING CHANGED ; SWAP(I - 1, I); SWAPPED := TRUE; END; END; END; END**OF**BUBBLESORT;   COMMENT ** MAIN PROGRAM **; REF(PAIR) ARRAY A(1:5); INTEGER I;   A(1) :- NEW PAIR( "JOE", "5531" ); A(2) :- NEW PAIR( "ADAM", "2341" ); A(3) :- NEW PAIR( "BERNIE", "122" ); A(4) :- NEW PAIR( "WALTER", "1234" ); A(5) :- NEW PAIR( "DAVID", "19" );   BUBBLESORT(A, NEW PAIRBYNAME);   FOR I:= 1 STEP 1 UNTIL 5 DO BEGIN OUTTEXT(A(I).N); OUTCHAR(' '); OUTTEXT(A(I).V); OUTIMAGE; END; OUTIMAGE;   END.
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Sort an array of composite structures by a key. For example, if you define a composite structure that presents a name-value pair (in pseudo-code): Define structure pair such that: name as a string value as a string and an array of such pairs: x: array of pairs then define a sort routine that sorts the array x by the key name. This task can always be accomplished with Sorting Using a Custom Comparator. If your language is not listed here, please see the other article.
#SQL
SQL
-- setup CREATE TABLE pairs (name VARCHAR(16), VALUE VARCHAR(16)); INSERT INTO pairs VALUES ('Fluffy', 'cat'); INSERT INTO pairs VALUES ('Fido', 'dog'); INSERT INTO pairs VALUES ('Francis', 'fish'); -- order them by name SELECT * FROM pairs ORDER BY name;
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.
#PowerBASIC
PowerBASIC
ARRAY SORT x()
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.
#PowerShell
PowerShell
34,12,23,56,1,129,4,2,73 | Sort-Object
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.
#Nanoquery
Nanoquery
def bubble_sort(seq) changed = true   while changed changed = false for i in range(0, len(seq) - 2) if seq[i] > seq[i + 1] temp = seq[i] seq[i] = seq[i + 1] seq[i + 1] = temp changed = true end end end   return seq end   if main import Nanoquery.Util; random = new(Random)   testset = list(range(0, 99)) testset = random.shuffle(testset) println testset + "\n"   testset = bubble_sort(testset) println testset 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
#Wren
Wren
var cocktailSort = Fn.new { |a| var last = a.count - 1 while (true) { var swapped = false for (i in 0...last) { if (a[i] > a[i+1]) { var t = a[i] a[i] = a[i+1] a[i+1] = t swapped = true } } if (!swapped) return swapped = false if (last >= 1) { for (i in last-1..0) { if (a[i] > a[i+1]) { var t = a[i] a[i] = a[i+1] a[i+1] = t swapped = true } } } if (!swapped) return } }   var a = [170, 45, 75, -90, -802, 24, 2, 66] System.print("Before: %(a)") cocktailSort.call(a) System.print("After : %(a)")
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#zkl
zkl
var s=Network.TCPClientSocket.connectTo("localhost",256); s.write("hello socket world"); //-->18 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.
#Zsh
Zsh
zmodload zsh/net/tcp ztcp localhost 256 print hello socket world >&$REPLY
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].
#REXX
REXX
/*REXX program finds (and maybe displays) Smith (or joke) numbers up to a given N.*/ parse arg N . /*obtain optional argument from the CL.*/ if N=='' | N=="," then N=10000 /*Not specified? Then use the default.*/ tell= (N>0); N=abs(N) - 1 /*use the │N│ for computing (below).*/ w=length(N) /*W: used for aligning Smith numbers. */ #=0 /*#: Smith numbers found (so far). */ @=; do j=4 to N; /*process almost all numbers up to N. */ if sumD(j) \== sumfactr(j) then iterate /*Not a Smith number? Then ignore it.*/ #=#+1 /*bump the Smith number counter. */ if \tell then iterate /*Not showing the numbers? Keep looking*/ @=@ right(j, w); if length(@)>199 then do; say substr(@, 2); @=; end end /*j*/ /* [↑] if N>0, then display Smith #s.*/   if @\=='' then say substr(@, 2) /*if any residual Smith #s, display 'em*/ say /* [↓] display the number of Smith #s.*/ say # ' Smith numbers found ≤ ' N"." /*display number of Smith numbers found*/ exit /*stick a fork in it, we're all done. */ /*──────────────────────────────────────────────────────────────────────────────────────*/ sumD: parse arg x 1 s 2; do d=2 for length(x)-1; s=s+substr(x,d,1); end; return s /*──────────────────────────────────────────────────────────────────────────────────────*/ sumFactr: procedure; parse arg z; $=0; f=0 /*obtain the Z number. */ do while z//2==0; $=$+2; f=f+1; z=z% 2; end /*maybe add factor of 2*/ do while z//3==0; $=$+3; f=f+1; z=z% 3; end /* " " " " 3*/ /* ___*/ do j=5 by 2 while j<=z & j*j<=n /*minimum of Z or √ N */ if j//3==0 then iterate /*skip factors that ÷ 3*/ do while z//j==0; f=f+1; $=$+sumD(j); z=z%j; end /*maybe reduce Z by J */ end /*j*/ /* [↓] Z: what's left*/ if z\==1 then do; f=f+1; $=$+sumD(z); end /*Residual? Then add Z*/ if f<2 then return 0 /*Prime? Not a Smith#*/ return $ /*else return sum digs.*/
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.
#Swift
Swift
extension Sequence { func sorted<Value>( on: KeyPath<Element, Value>, using: (Value, Value) -> Bool ) -> [Element] where Value: Comparable { return withoutActuallyEscaping(using, do: {using -> [Element] in return self.sorted(by: { using($0[keyPath: on], $1[keyPath: on]) }) }) } }   struct Person { var name: String var role: String }   let a = Person(name: "alice", role: "manager") let b = Person(name: "bob", role: "worker") let c = Person(name: "charlie", role: "driver")   print([c, b, a].sorted(on: \.name, using: <))
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.
#Prolog
Prolog
 ?- msort([10,5,13,3, 85,3,1], L). L = [1,3,3,5,10,13,85].
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.
#PureBasic
PureBasic
Dim numbers(20) For i = 0 To 20 numbers(i) = Random(1000) Next   SortArray(numbers(), #PB_Sort_Ascending)
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.
#Nemerle
Nemerle
using System; using System.Console;   module Bubblesort { Bubblesort[T] (x : list[T]) : list[T] where T : IComparable { def isSorted(y) { |[_] => true |y1::y2::ys => (y1.CompareTo(y2) < 0) && isSorted(y2::ys) }   def sort(y) { |[y] => [y] |y1::y2::ys => if (y1.CompareTo(y2) < 0) y1::sort(y2::ys) else y2::sort(y1::ys) }   def loop(y) { if (isSorted(y)) y else {def z = sort(y); loop(z)} }   match(x) { |[] => [] |_ => loop(x) } }   Main() : void { def empty = []; def single = [2]; def several = [2, 6, 1, 7, 3, 9, 4]; WriteLine(Bubblesort(empty)); WriteLine(Bubblesort(single)); WriteLine(Bubblesort(several)); } }
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
#XPL0
XPL0
code ChOut=8, IntOut=11;   proc CocktailSort(A, L); \Sort array A of length L int A, L; int Swapped, I, T; [loop [Swapped:= false; for I:= 0 to L-2 do if A(I) > A(I+1) then \test if elements are in wrong order [T:= A(I); A(I):= A(I+1); A(I+1):= T; \elements change places Swapped:= true; ]; if Swapped = false then quit; \exit outer loop if no swaps occurred Swapped:= false; for I:= L-2 downto 0 do if A(I) > A(I+1) then [T:= A(I); A(I):= A(I+1); A(I+1):= T; Swapped:= true; ]; \if no elements have been swapped then the list is sorted if not Swapped then quit; ]; ];   int A, I; [A:= [3, 1, 4, 1, -5, 9, 2, 6, 5, 4]; CocktailSort(A, 10); for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )]; ]
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers. Example Using the number 166 Find the prime factors of 166 which are: 2 x 83 Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13 Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13 Therefore, the number 166 is a Smith number. Task Write a program to find all Smith numbers below 10000. See also from Wikipedia:   [Smith number]. from MathWorld:   [Smith number]. from OEIS A6753:   [OEIS sequence A6753]. from OEIS A104170:   [Number of Smith numbers below 10^n]. from The Prime pages:   [Smith numbers].
#Ring
Ring
  # Project : Smith numbers   see "All the Smith Numbers < 1000 are:" + nl   for prime = 1 to 1000 decmp = [] sum1 = sumDigits(prime) decomp(prime) sum2 = 0 if len(decmp)>1 for n=1 to len(decmp) cstr = string(decmp[n]) for m= 1 to len(cstr) sum2 = sum2 + number(cstr[m]) next next ok if sum1 = sum2 see "" + prime + " " ok next   func decomp nr for i = 1 to nr if isPrime(i) and nr % i = 0 add(decmp, i) pr = i while true pr = pr * i if nr%pr = 0 add(decmp, i) else exit ok end ok next   func isPrime num if (num <= 1) return 0 ok if (num % 2 = 0 and num != 2) return 0 ok for i = 3 to floor(num / 2) -1 step 2 if (num % i = 0) return 0 ok next return 1   func sumDigits n sum = 0 while n > 0.5 m = floor(n / 10) digit = n - m * 10 sum = sum + digit n = m end return sum  
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].
#Ruby
Ruby
require "prime"   class Integer   def smith? return false if prime? digits.sum == prime_division.map{|pr,n| pr.digits.sum * n}.sum end   end   n = 10_000 res = 1.upto(n).select(&:smith?)   puts "#{res.size} smith numbers below #{n}: #{res.first(5).join(", ")},... #{res.last(5).join(", ")}"
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.
#Tcl
Tcl
set people {{joe 120} {foo 31} {bar 51}} # sort by the first element of each pair lsort -index 0 $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.
#UNIX_Shell
UNIX Shell
list="namez:order! name space:in name1:sort name:Please"   newline=" "   dumplist() { ( IFS=$newline for pair in $list; do ( IFS=: set -- $pair echo " $1 => $2" ) done ) }   echo "Original list:" dumplist   list=`IFS=$newline; printf %s "$list" | sort -t: -k1,1`   echo "Sorted list:" dumplist
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.
#Python
Python
nums = [2,4,3,1,2] nums.sort()
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort O(n2) sorts Bubble sort | Cocktail sort | Cocktail sort with shifting bounds | Comb sort | Cycle sort | Gnome sort | Insertion sort | Selection sort | Strand sort other sorts Bead sort | Bogo sort | Common sorted list | Composite structures sort | Custom comparator sort | Counting sort | Disjoint sublist sort | External sort | Jort sort | Lexicographical sort | Natural sorting | Order by pair comparisons | Order disjoint list items | Order two numerical lists | Object identifier (OID) sort | Pancake sort | Quickselect | Permutation sort | Radix sort | Ranking methods | Remove duplicate elements | Sleep sort | Stooge sort | [Sort letters of a string] | Three variable sort | Topological sort | Tree sort Task Sort an array (or list) of integers in ascending numerical order. Use a sorting facility provided by the language/library if possible.
#Quackery
Quackery
/O> [] 20 times [ 10 random join ] ... dup echo cr ... sort ... echo cr ... [ 5 2 5 0 4 5 1 5 1 1 0 3 7 2 0 9 6 1 8 7 ] [ 0 0 0 1 1 1 1 2 2 3 4 5 5 5 5 6 7 7 8 9 ]
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.
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref savelog symbols binary   placesList = [String - "UK London", "US New York" - , "US Boston", "US Washington" - , "UK Washington", "US Birmingham" - , "UK Birmingham", "UK Boston" - ] sortedList = bubbleSort(String[] Arrays.copyOf(placesList, placesList.length))   lists = [placesList, sortedList] loop ln = 0 to lists.length - 1 cl = lists[ln] loop ct = 0 to cl.length - 1 say cl[ct] end ct say end ln   return   method bubbleSort(list = String[]) public constant binary returns String[]   listLen = list.length loop i_ = 0 to listLen - 1 loop j_ = i_ + 1 to listLen - 1 if list[i_].compareTo(list[j_]) > 0 then do tmpstor = list[j_] list[j_] = list[i_] list[i_] = tmpstor end end j_ end i_   return list  
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
#zkl
zkl
fcn cocktailSort(a){ swapped,begin,end:=False,-1,a.len() - 2; do{ swapped,begin=False,begin + 1; foreach i in ([begin .. end]){ if(a[i]>a[i+1]){ a.swap(i,i+1); swapped=True; } } if(not swapped) break; swapped,end=False,end - 1; foreach i in ([end..begin,-1]){ if(a[i]>a[i+1]){ a.swap(i,i+1); swapped=True; } } }while(swapped); a }
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].
#Rust
Rust
fn main () { //We just need the primes below 100 let primes = vec![2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]; let mut solution = Vec::new(); let mut number; for i in 4..10000 { //Factorize each number below 10.000 let mut prime_factors = Vec::new(); number = i; for j in &primes { while number % j == 0 { number = number / j; prime_factors.push(j); } if number == 1 { break; } } //Number is 1 (not a prime factor) if the factorization is complete or a prime bigger than 100 if number != 1 { prime_factors.push(&number); } //Avoid the prime numbers if prime_factors.len() < 2 { continue; } //Check the smith number definition if prime_factors.iter().fold(0, |n,x| n + x.to_string().chars().map(|d| d.to_digit(10).unwrap()).fold(0, |n,x| n + x)) == i.to_string().chars().map(|d| d.to_digit(10).unwrap()).fold(0, |n,x| n + x) { solution.push(i); } } println!("Smith numbers below 10000 ({}) : {:?}",solution.len(), solution); }
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].
#Scala
Scala
object SmithNumbers extends App {   def sumDigits(_n: Int): Int = { var n = _n var sum = 0 while (n > 0) { sum += (n % 10) n /= 10 } sum }   def primeFactors(_n: Int): List[Int] = { var n = _n val result = new collection.mutable.ListBuffer[Int] val i = 2 while (n % i == 0) { result += i n /= i } var j = 3 while (j * j <= n) { while (n % j == 0) { result += i n /= j } j += 2 } if (n != 1) result += n result.toList }   for (n <- 1 until 10000) { val factors = primeFactors(n) if (factors.size > 1) { var sum = sumDigits(n) for (f <- factors) sum -= sumDigits(f) if (sum == 0) println(n) } }   }
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.
#Ursala
Ursala
#import std   #cast %sWLW   examples =   ( -<&l <('z','a'),('x','c'),('y','b')>, # sorted by the left -<&r <('z','a'),('x','c'),('y','b')>) # sorted by the right