task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle
Solve a Hidato puzzle
The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always connected. The number “1” is always ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
ClearAll[NeighbourQ, CellDistance, VisualizeHidato, HiddenSingle, \ NakedN, HiddenN, ChainSearch, HidatoSolve, Cornering, ValidPuzzle, \ GapSearch, ReachDelete, GrowNeighbours] NeighbourQ[cell1_, cell2_] := (CellDistance[cell1, cell2] === 1) ValidPuzzle[cells_List, cands_List] := MemberQ[cands, {1}] \[And] MemberQ[ca...
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 ...
#Lua
Lua
function sorting( a, b ) return a[1] < b[1] end   tab = { {"C++", 1979}, {"Ada", 1983}, {"Ruby", 1995}, {"Eiffel", 1985} }   table.sort( tab, sorting ) for _, v in ipairs( tab ) do print( unpack(v) ) end
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You ar...
#XPL0
XPL0
include c:\cxpl\codes;   int Hole, Max, I; char Box(8), Str; def A, B, C, D, E, F, G, H; [for Hole:= 0 to 7 do Box(Hole):= Hole+1; Max:= 7; while abs(Box(D)-Box(A)) < 2 or abs(Box(D)-Box(C)) < 2 or abs(Box(D)-Box(G)) < 2 or abs(Box(D)-Box(E)) < 2 or abs(Box(A)-Box(C)) < 2 or abs(Box...
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You ar...
#zkl
zkl
const PegA=0, PegB=1, PegC=2, PegD=3, PegE=4, PegF=5, PegG=6, PegH=7; connections:=T( T(PegA, PegC), T(PegA, PegD), T(PegA, PegE), T(PegB, PegD), T(PegB, PegE), T(PegB, PegF), T(PegC, PegD), T(PegD, PegE), T(PegE, PegF), T(PegG, PegC), T(PegG, PegD), T(PegG, PegE), T(PegH, PegD), T(PegH, PegE), T(PegH, ...
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 ...
#Lasso
Lasso
local(array) = array(5,20,3,2,6,1,4) #array->sort #array // 1, 2, 3, 4, 5, 6, 20   // Reverse the sort order #array->sort(false) #array // 20, 6, 5, 4, 3, 2, 1
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Liberty_BASIC
Liberty BASIC
N =20 dim IntArray( N)   print "Original order" for i =1 to N t =int( 1000 *rnd( 1)) IntArray( i) =t print t next i   sort IntArray(), 1, N   print "Sorted oprder" for i =1 to N print IntArray( i) next i
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#PureBasic
PureBasic
Procedure Bubble_sort(Array idx(1), n, Array buf(1)) Protected i, j SortArray(idx(),#PB_Sort_Ascending) For i=0 To n For j=i+1 To n If buf(idx(j)) < buf(idx(i)) Swap buf(idx(j)), buf(idx(i)) EndIf Next Next EndProcedure   Procedure main() DataSection values: Data.i 7, 6, 5, 4,...
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#REXX
REXX
/*REXX program sorts a (stemmed) array using the merge-sort method. */ /* using mycmp function for the sort order */ /********************************************************************** * mergesort taken from REXX (adapted for ooRexx (and all other REXXes)) * 28.07.2013 Walter Pachl ******...
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 ...
#Janet
Janet
  (defn bubble-sort! [arr] (def arr-len (length arr)) (when (< arr-len 2) (break arr)) # at this point there are two or more elements (loop [i :down-to [(dec arr-len) 0]] (for j 0 i (def left-elt (get arr j)) (def right-elt (get arr (inc j))) (when (> left-elt right-elt) (put...
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 ...
#REXX
REXX
/*REXX program sorts an array using the gnome sort algorithm (elements contain blanks). */ call gen /*generate the @ stemmed array. */ call show 'before sort' /*display the before array elements.*/ say copies('▒', 60...
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 ...
#R
R
cocktailSort <- function(A) { repeat { swapped <- FALSE for(i in seq_len(length(A) - 1)) { if(A[i] > A[i + 1]) { A[c(i, i + 1)] <- A[c(i + 1, i)]#The cool trick mentioned above. swapped <- TRUE } } if(!swapped) break swapped <- FALSE for(i in (length(A...
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Nim
Nim
import net   var s = newSocket() s.connect("localhost", Port(256)) s.send("Hello Socket World") s.close()
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Objeck
Objeck
  use Net;   bundle Default { class Socket { function : Main(args : String[]) ~ Nil { socket := TCPSocket->New("localhost", 256); if(socket->IsOpen()) { socket->WriteString("hello socket world"); socket->Close(); } } } }  
http://rosettacode.org/wiki/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Snake is a game where the player maneuvers a line which grows i...
#Nim
Nim
import macros, os, random import ncurses   when defined(Linux): proc positional_putch(x, y: int; ch: char) = mvaddch(x.cint, y.cint, ch.chtype) proc updateScreen = refresh() proc nonBlockingGetch(): char = let c = getch() result = if c in 0..255: char(c) else: '\0' proc closeScreen = endwin()   else: ...
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....
#Factor
Factor
USING: formatting grouping io kernel math.primes.factors math.ranges math.text.utils sequences sequences.deep ;   : (smith?) ( n factors -- ? ) [ 1 digit-groups sum ] [ [ 1 digit-groups ] map flatten sum = ] bi* ; inline   : smith? ( n -- ? ) dup factors dup length 1 = [ 2drop f ] [ (smith?) ] if ;   10,000...
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....
#Fortran
Fortran
MODULE FACTORISE !Produce a little list... USE PRIMEBAG !This is a common need. INTEGER LASTP !Some size allowances. PARAMETER (LASTP = 9) !2*3*5*7*11*13*17*19*23*29 = 6,469,693,230, > 2,147,483,647. TYPE FACTORED !Represent a number fully factored. INTEGER PVAL(0:LASTP) !As...
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 ...
#Nim
Nim
import strutils, algorithm, sequtils, strformat   type Hidato = object board: seq[seq[int]] given: seq[int] start: (int, int)   proc initHidato(s: string): Hidato = var lines = s.splitLines() let cols = lines[0].splitWhitespace().len() let rows = lines.len() result.board = newSeqWith(rows +...
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 ...
#M2000_Interpreter
M2000 Interpreter
  Module CheckIt { Flush ' empty stack of values Class Quick { Private: partition=lambda-> { Read &A(), p, r : i = p-1 : x=A(r) For j=p to r-1 {If .LE(A(j), x) Then i++:Swap A(i),A(j) } : Swap A(i+1), A(r) : Push i+2, i }...
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
events = {{"2009-12-25", "Christmas Day"}, {"2009-04-22", "Earth Day"}, {"2009-09-07", "Labor Day"}, {"2009-07-04", "Independence Day"}, {"2009-10-31", "Halloween"}, {"2009-05-25", "Memorial Day"}, {"2009-03-14", "PI Day"}, {"2009-01-01", "New Year's Day"}, {"2009-12-31", "New Year's Eve"}, {"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 ...
#Lingo
Lingo
l = [7, 4, 23] l.sort() put l -- [4, 7, 23]
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#LiveCode
LiveCode
put "3,2,5,4,1" into X sort items of X numeric put X -- outputs "1,2,3,4,5"
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Python
Python
>>> def sort_disjoint_sublist(data, indices): indices = sorted(indices) values = sorted(data[i] for i in indices) for index, value in zip(indices, values): data[index] = value     >>> d = [7, 6, 5, 4, 3, 2, 1, 0] >>> i = set([6, 1, 7]) >>> sort_disjoint_sublist(d, i) >>> d [7, 0, 5, 4, 3, 2, 1, 6] >>> # Which cou...
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Ring
Ring
  load "stdlib.ring"   sList = newlist(8, 2) aList = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"] ind = len(aList)   for n = 1 to ind sList[n] [1] = aList[n] sList[n] [2] = len(aList[n]) next   nList = sortFirstSecond(sList, 2) oList = newlist(8, 2) count = 0   for n = len(nList) to 1 step...
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Ruby
Ruby
words = %w(Here are some sample strings to be sorted) p words.sort_by {|word| [-word.size, word.downcase]}
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Java
Java
public static <E extends Comparable<? super E>> void bubbleSort(E[] comparable) { boolean changed = false; do { changed = false; for (int a = 0; a < comparable.length - 1; a++) { if (comparable[a].compareTo(comparable[a + 1]) > 0) { E tmp = comparable[a]; ...
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 ...
#Ring
Ring
  aList = [ 5, 6, 1, 2, 9, 14, 15, 7, 8, 97] gnomeSort(aList) for i=1 to len(aList) see "" + aList[i] + " " next   func gnomeSort a i = 2 j = 3 while i < len(a) if a[i-1] <= a[i] i = j j = j + 1 else temp = a[i-1] a[i-1] =...
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 ...
#Racket
Racket
  #lang racket (require (only-in srfi/43 vector-swap!))   (define (cocktail-sort! xs) (define (ref i) (vector-ref xs i)) (define (swap i j) (vector-swap! xs i j)) (define len (vector-length xs)) (define (bubble from to delta) (for/fold ([swaps 0]) ([i (in-range from to delta)]) (cond [(> (ref i) (ref ...
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Objective-C
Objective-C
// declare the class to conform to NSStreamDelegate protocol   // in some method NSOutputStream *oStream; [NSStream getStreamsToHost:[NSHost hostWithName:@"localhost"] port:256 inputStream:NULL outputStream:&oStream]; [oStream setDelegate:self]; [oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRun...
http://rosettacode.org/wiki/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Snake is a game where the player maneuvers a line which grows i...
#OCaml
OCaml
(* A simple Snake Game *) open Sdl   let width, height = (640, 480)   type pos = int * int   type game_state = { pos_snake: pos; seg_snake: pos list; dir_snake: [`left | `right | `up | `down]; pos_fruit: pos; sleep_time: int; game_over: bool; }   let red = (255, 0, 0) let blue = (0, 0, 255) let green = (...
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....
#FreeBASIC
FreeBASIC
' FB 1.05.0 Win64   Sub getPrimeFactors(factors() As UInteger, n As UInteger) If n < 2 Then Return Dim factor As UInteger = 2 Do If n Mod factor = 0 Then Redim Preserve factors(0 To UBound(factors) + 1) factors(UBound(factors)) = factor n \= factor If n = 1 Then Return Else '...
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 ...
#Perl
Perl
use strict; use List::Util 'max';   our (@grid, @known, $n);   sub show_board { for my $r (@grid) { print map(!defined($_) ? ' ' : $_ ? sprintf("%3d", $_) : ' __' , @$r), "\n" } }   sub parse_board { @grid = map{[map(/^_/ ? 0 : /^\./ ? undef: $_, split ' ')]} split "\n", shift(); for my $y (0 .....
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 ...
#MAXScript
MAXScript
fn keyCmp comp1 comp2 = ( case of ( (comp1[1] > comp2[1]): 1 (comp1[1] < comp2[1]): -1 default: 0 ) )   people = #(#("joe", 39), #("dave", 37), #("bob", 42)) qsort people keyCmp print people
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#NetRexx
NetRexx
/* NetRexx */ options replace format comments java crossref symbols nobinary   -- ============================================================================= class RSortCompsiteStructure public   -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method main(args = String[]) public sta...
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 ...
#Lua
Lua
t = {4, 5, 2} table.sort(t) print(unpack(t))
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Maple
Maple
sort([5,7,8,3,6,1]); sort(Array([5,7,8,3,6,1]))
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#R
R
values=c(7,6,5,4,3,2,1,0) indices=c(7,2,8) values[sort(indices)]=sort(values[indices]) print(values)
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Racket
Racket
  #lang racket   (define (sort-disjoint l is) (define xs (sort (for/list ([x l] [i (in-naturals)] #:when (memq i is)) x) <)) (let loop ([l l] [i 0] [xs xs]) (cond [(null? l) l] [(memq i is) (cons (car xs) (loop (cdr l) (add1 i) (cdr xs)))] [else (cons (car l) (loop (cdr l) (add1 ...
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Rust
Rust
  fn main() { let mut words = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]; words.sort_by(|l, r| Ord::cmp(&r.len(), &l.len()).then(Ord::cmp(l, r))); println!("{:?}", words); }  
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Sather
Sather
class MAIN is   custom_comp(a, b:STR):BOOL is l ::= a.length - b.length; if l = 0 then return a.lower < b.lower; end; return l > 0; end;   main is s:ARRAY{STR} := |"this", "is", "an", "array", "of", "strings", "to", "sort"|;   s.insertion_sort_by(bind(custom_comp(_,_))); loop #OUT + s.elt!...
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 ...
#JavaScript
JavaScript
Array.prototype.bubblesort = function() { var done = false; while (!done) { done = true; for (var i = 1; i<this.length; i++) { if (this[i-1] > this[i]) { done = false; [this[i-1], this[i]] = [this[i], this[i-1]] } } } return...
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 ...
#Ruby
Ruby
class Array def gnomesort! i, j = 1, 2 while i < length if self[i-1] <= self[i] i, j = j, j+1 else self[i-1], self[i] = self[i], self[i-1] i -= 1 if i == 0 i, j = j, j+1 end end end self end end ary = [7,6,5,9,8,4,3,1,2,0] ary.gnome...
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 ...
#Raku
Raku
sub cocktail_sort ( @a ) { my $range = 0 ..^ @a.end; loop { my $swapped_forward = 0; for $range.list -> $i { if @a[$i] > @a[$i+1] { @a[ $i, $i+1 ] .= reverse; $swapped_forward = 1; } } last if not $swapped_forward;   ...
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#OCaml
OCaml
open Unix   let init_socket addr port = let inet_addr = (gethostbyname addr).h_addr_list.(0) in let sockaddr = ADDR_INET (inet_addr, port) in let sock = socket PF_INET SOCK_STREAM 0 in connect sock sockaddr; (* convert the file descriptor into high-level channels: *) let outchan = out_channel_of_descr sock ...
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Oz
Oz
declare Socket = {New Open.socket init} in {Socket connect(port:256)} {Socket write(vs:"hello socket world")} {Socket close}
http://rosettacode.org/wiki/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Snake is a game where the player maneuvers a line which grows i...
#Perl
Perl
use utf8; use Time::HiRes qw(sleep); use Term::ANSIColor qw(colored); use Term::ReadKey qw(ReadMode ReadLine);   binmode(STDOUT, ':utf8');   use constant { VOID => 0, HEAD => 1, BODY => 2, TAIL => 3, FOOD => 4, };   use constant { ...
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....
#F.C5.8Drmul.C3.A6
Fōrmulæ
  package main   import "fmt"   func numPrimeFactors(x uint) int { var p uint = 2 var pf int if x == 1 { return 1 } for { if (x % p) == 0 { pf++ x /= p if x == 1 { return pf } } else { p++ } } }   func primeFactors(x uint, arr []uint) { var p uint = 2 var pf int if x == 1 { arr[pf]...
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 ...
#Phix
Phix
with javascript_semantics sequence board, warnsdorffs, knownx, knowny integer width, height, limit, nchars, tries string fmt, blank constant ROW = 1, COL = 2 constant moves = {{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}} function onboard(integer row, integer col) return row>=1 and row<=height and co...
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 ...
#Nim
Nim
import algorithm, sugar   var people = @{"joe": 120, "foo": 31, "bar": 51} sort(people, (x,y) => cmp(x[0], y[0])) echo people
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Objeck
Objeck
  use Collection;   class Entry implements Compare { @name : String; @value : Float;   New(name : String, value : Float) { @name := name; @value := value; }   method : public : Compare(rhs : Compare) ~ Int { return @name->Compare(rhs->As(Entry)->GetName()); }   method : public : GetName() ~ S...
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 ...
#Mathematica.2FWolfram_Language
Mathematica/Wolfram Language
numbers=Sort[{2,4,3,1,2}]
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#MATLAB
MATLAB
a = [4,3,7,-2,9,1]; b = sort(a) % b contains elements of a in ascending order [b,idx] = sort(a) % b contains a(idx)
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Raku
Raku
my @values = 7, 6, 5, 4, 3, 2, 1, 0; my @indices = 6, 1, 7;   @values[ @indices.sort ] .= sort;   say @values;
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Scala
Scala
List("Here", "are", "some", "sample", "strings", "to", "be", "sorted").sortWith{(a,b) => val cmp=a.size-b.size (if (cmp==0) -a.compareTo(b) else cmp) > 0 }
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Scheme
Scheme
(use srfi-13);;Syntax for module inclusion depends on implementation, ;;a sort function may be predefined, or available through srfi 95 (define (mypred? a b) (let ((len-a (string-length a)) (len-b (string-length b))) (if (= len-a len-b) (string>? (string-downcase b) (string-downcase a)) (> len-a len-b)...
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 ...
#jq
jq
def bubble_sort: def swap(i;j): .[i] as $x | .[i]=.[j] | .[j]=$x;   # input/output: [changed, list] reduce range(0; length) as $i ( [false, .]; if $i > 0 and (.[0]|not) then . else reduce range(0; (.[1]|length) - $i - 1) as $j (.[0] = false; .[1] as $list | if $list[$j] > $...
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 ...
#Rust
Rust
fn gnome_sort<T: PartialOrd>(a: &mut [T]) { let len = a.len(); let mut i: usize = 1; let mut j: usize = 2; while i < len { if a[i - 1] <= a[i] { // for descending sort, use >= for comparison i = j; j += 1; } else { a.swap(i - 1, i); ...
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 ...
#REXX
REXX
/*REXX program sorts an array using the cocktail─sort method, A.K.A.: happy hour sort,*/ /* bidirectional bubble sort, */ /* cocktail shaker sort, ripple sort,*/ ...
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Pascal
Pascal
Program Sockets_ExampleA;   Uses { Free Pascal RTL sockets unit } sockets;   Var TCP_Sock: integer; Remote_Addr: TSockAddr;   Message: string; PMessage: Pchar; Message_Len: integer;     Begin { Fill the record (struct) with the server's address information } With Remote_Addr do begin S...
http://rosettacode.org/wiki/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Snake is a game where the player maneuvers a line which grows i...
#Phix
Phix
constant W = 60, H = 30, MAX_LEN = 600 enum NORTH, EAST, SOUTH, WEST   sequence board, snake bool alive integer tailIdx, headIdx, hdX, hdY, d, points   procedure createField() clear_screen() board = repeat("+"&repeat(' ',W-2)&'+',H) for x=1 to W do board[1,x] = '+' end for board[H] = board[1...
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....
#Go
Go
  package main   import "fmt"   func numPrimeFactors(x uint) int { var p uint = 2 var pf int if x == 1 { return 1 } for { if (x % p) == 0 { pf++ x /= p if x == 1 { return pf } } else { p++ } } }   func primeFactors(x uint, arr []uint) { var p uint = 2 var pf int if x == 1 { arr[pf]...
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 ...
#Picat
Picat
import sat.   main => M = {{ _,33,35, _, _, 0, 0, 0}, { _, _,24,22, _, 0, 0, 0}, { _, _, _,21, _, _, 0, 0}, { _,26, _,13,40,11, 0, 0}, {27, _, _, _, 9, _, 1, 0}, { 0, 0, _, _,18, _, _, 0}, { 0, 0, 0, 0, _, 7, _, _}, { 0, 0, 0, 0, 0, 0, 5, _}}, ...
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 ...
#Objective-C
Objective-C
@interface Pair : NSObject { NSString *name; NSString *value; } +(instancetype)pairWithName:(NSString *)n value:(NSString *)v; -(instancetype)initWithName:(NSString *)n value:(NSString *)v; -(NSString *)name; -(NSString *)value; @end   @implementation Pair +(instancetype)pairWithName:(NSString *)n value:(NSStri...
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 ...
#Maxima
Maxima
sort([9, 4, 3, 7, 6, 1, 10, 2, 8, 5]);
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#MAXScript
MAXScript
arr = #(5, 4, 3, 2, 1) arr = sort arr
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#REXX
REXX
/*REXX program uses a disjointed sublist to sort a random list of values. */ parse arg old ',' idx /*obtain the optional lists from the CL*/ if old='' then old= 7 6 5 4 3 2 1 0 /*Not specified: Then use the default.*/ if idx='' then idx= 7 2 8 ...
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Sidef
Sidef
func mycmp(a, b) { (b.len <=> a.len) || (a.lc <=> b.lc) }; var strings = %w(Here are some sample strings to be sorted); var sorted = strings.sort(mycmp);
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Slate
Slate
define: #words -> #('here' 'are' 'some' 'sample' 'strings' 'to' 'sort' 'since' 'this' 'exercise' 'is' 'not' 'really' 'all' 'that' 'dumb' '(sorry)'). words sortBy: [| :first :second | (first lexicographicallyCompare: second) isNegative]
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
Sorting algorithms/Bubble sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Julia
Julia
function bubblesort!(arr::AbstractVector) for _ in 2:length(arr), j in 1:length(arr)-1 if arr[j] > arr[j+1] arr[j], arr[j+1] = arr[j+1], arr[j] end end return arr end   v = rand(-10:10, 10) println("# unordered: $v\n -> ordered: ", bubblesort!(v))
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
Sorting algorithms/Gnome sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Scala
Scala
object GnomeSort { def gnomeSort(a: Array[Int]): Unit = { var (i, j) = (1, 2) while ( i < a.length) if (a(i - 1) <= a(i)) { i = j; j += 1 } else { val tmp = a(i - 1) a(i - 1) = a(i) a({i -= 1; i + 1}) = tmp i = if (i == 0) {j += 1; j - 1} else i } } }
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort
Sorting algorithms/Cocktail sort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Ring
Ring
  aList = [ 5, 6, 1, 2, 9, 14, 2, 15, 6, 7, 8, 97] flag = 0 cocktailSort(aList) for i=1 to len(aList) see "" + aList[i] + " " next   func cocktailSort A n = len(A) while flag = 0 flag = 1 for i = 1 to n-1 if A[i] > A[i+1] temp = A[i] ...
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Perl
Perl
use Socket;   $host = gethostbyname('localhost'); $in = sockaddr_in(256, $host); $proto = getprotobyname('tcp'); socket(Socket_Handle, AF_INET, SOCK_STREAM, $proto); connect(Socket_Handle, $in); send(Socket_Handle, 'hello socket world', 0, $in); close(Socket_Handle);
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Phix
Phix
without js -- (sockets) include builtins\sockets.e constant msg = "hello socket world" atom sock = socket(AF_INET, SOCK_STREAM) if sock>=0 then atom pSockAddr = sockaddr_in(AF_INET, "localhost", 256) integer res = connect(sock, pSockAddr) if res=SOCKET_ERROR then crash("connect (%v)",{get_socket_err...
http://rosettacode.org/wiki/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Snake is a game where the player maneuvers a line which grows i...
#Python
Python
from __future__ import annotations   import itertools import random   from enum import Enum   from typing import Any from typing import Tuple   import pygame as pg   from pygame import Color from pygame import Rect   from pygame.surface import Surface   from pygame.sprite import AbstractGroup from pygame.sprite import ...
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....
#Haskell
Haskell
import Data.Numbers.Primes (primeFactors) import Data.List (unfoldr) import Data.Tuple (swap) import Data.Bool (bool)   isSmith :: Int -> Bool isSmith n = pfs /= [n] && sumDigits n == foldr ((+) . sumDigits) 0 pfs where sumDigits = sum . baseDigits 10 pfs = primeFactors n   baseDigits :: Int -> Int -> [Int] b...
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 ...
#PicoLisp
PicoLisp
(load "@lib/simul.l")   (de hidato (Lst) (let Grid (grid (length (maxi length Lst)) (length Lst)) (mapc '((G L) (mapc '((This Val) (nond (Val (with (: 0 1 1) (con (: 0 1))) # Cut off west ...
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 ...
#OCaml
OCaml
# let people = [("Joe", 12); ("Bob", 8); ("Alice", 9); ("Harry", 2)];; val people : (string * int) list = [("Joe", 12); ("Bob", 8); ("Alice", 9); ("Harry", 2)] # let sortedPeopleByVal = List.sort (fun (_, v1) (_, v2) -> compare v1 v2) people;; val sortedPeopleByVal : (string * int) list = [("Harry", 2); ("Bob", 8);...
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 ...
#Mercury
Mercury
:- module sort_int_list. :- interface. :- import_module io.   :- pred main(io::di, uo::uo) is det.   :- implementation. :- import_module list.   main(!IO) :- Nums = [2, 4, 0, 3, 1, 2], list.sort(Nums, Sorted), io.write(Sorted, !IO), io.nl(!IO).
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#min
min
(5 2 1 3 4) '> sort print
http://rosettacode.org/wiki/Sort_disjoint_sublist
Sort disjoint sublist
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Ring
Ring
  aList = [7, 6, 5, 4, 3, 2, 1, 0] indList = [7, 2, 8] bList = [] for n = 1 to len(indList) add(bList,[indList[n],aList[indList[n]]]) next bList1 = sort(bList,1) bList2 = sort(bList,2) for n = 1 to len(bList) aList[bList1[n][1]] = bList2[n][2] next showarray(aList)   func showarray vect svect = "" for...
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 ...
#Ruby
Ruby
def sort_disjoint_sublist!(ar, indices) values = ar.values_at(*indices).sort indices.sort.zip(values).each{ |i,v| ar[i] = v } ar end   values = [7, 6, 5, 4, 3, 2, 1, 0] indices = [6, 1, 7] p sort_disjoint_sublist!(values, indices)
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Smalltalk
Smalltalk
#('here' 'are' 'some' 'sample' 'strings' 'to' 'sort' 'since' 'this' 'exercise' 'is' 'not' 'really' 'all' 'that' 'dumb' '(sorry)' ) asSortedCollection sortBlock: [:first :second | (second size = first size) ifFalse: [second size < first size] ...
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 ...
#Kotlin
Kotlin
import java.util.Comparator   fun <T> bubbleSort(a: Array<T>, c: Comparator<T>) { var changed: Boolean do { changed = false for (i in 0..a.size - 2) { if (c.compare(a[i], a[i + 1]) > 0) { val tmp = a[i] a[i] = a[i + 1] a[i + 1] = tmp ...
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 ...
#Scheme
Scheme
; supply comparison function, which returns true if first and second ; arguments are in order or equal. (define (gnome-sort-compar in-order input-list) (let gnome ((p (list (car input-list))) (n (cdr input-list))) (if (null? n) ; no more flowerpots? p ; we're done (let ((prev-pot (ca...
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 ...
#Ruby
Ruby
class Array def cocktailsort! begin swapped = false 0.upto(length - 2) do |i| if self[i] > self[i + 1] self[i], self[i + 1] = self[i + 1], self[i] swapped = true end end break unless swapped   swapped = false (length - 2).downto(0) do |i| ...
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#PHP
PHP
$socket = fsockopen('localhost', 256); fputs($socket, 'hello socket world'); fclose($socket);
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#PicoLisp
PicoLisp
(when (connect "localhost" 256) (out @ (prinl "hello socket world")) (close @) )
http://rosettacode.org/wiki/Snake
Snake
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance) Snake is a game where the player maneuvers a line which grows i...
#Raku
Raku
use SDL2::Raw; use Cairo;   constant W = 1280; constant H = 960;   constant FIELDW = W div 32; constant FIELDH = H div 32;   SDL_Init(VIDEO);   my $window = SDL_CreateWindow( 'Snake', SDL_WINDOWPOS_CENTERED_MASK, SDL_WINDOWPOS_CENTERED_MASK, W, H, OPENGL );   my $render = SDL_CreateRenderer($window,...
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....
#J
J
digits=: 10&#.inv sumdig=: +/@,@digits notprime=: -.@(1&p:) smith=: #~ notprime * (=&sumdig q:)every
http://rosettacode.org/wiki/Smith_numbers
Smith numbers
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1. By definition, all primes are excluded as they (naturally) satisfy this condition! Smith numbers are also known as   joke   numbers....
#Java
Java
import java.util.*;   public class SmithNumbers {   public static void main(String[] args) { for (int n = 1; n < 10_000; n++) { List<Integer> factors = primeFactors(n); if (factors.size() > 1) { int sum = sumDigits(n); for (int f : factors) ...
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 ...
#Prolog
Prolog
:- use_module(library(clpfd)).   hidato :- init1(Li), % skip first blank line init2(1, 1, 10, Li), my_write(Li).     init1(Li) :- Li = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, A, 33, 35, B, C, 0, 0, 0, 0, 0, D, E, 24, 22, F, 0, 0, 0, 0, 0, G, H, I, 21, J, K, 0, 0, 0, ...
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 ...
#Oforth
Oforth
[["Joe",5531], ["Adam",2341], ["Bernie",122], ["David",19]] sortBy(#first) println
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
Sort an array of composite structures
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Ol
Ol
  (import (scheme char))   (define (comp a b) (string-ci<? (a 'name #f) (b 'name #f)))   (for-each print (sort comp (list { 'name "David" 'value "Manager" } { 'name "Alice" 'value "Sales" } { 'name "Joanna" 'value "Director" } { 'name "Henry" 'value "Admin" ...
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 ...
#Modula-3
Modula-3
MODULE ArraySort EXPORTS Main;   IMPORT IntArraySort;   VAR arr := ARRAY [1..10] OF INTEGER{3, 6, 1, 2, 10, 7, 9, 4, 8, 5};   BEGIN IntArraySort.Sort(arr); END ArraySort.
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#MUMPS
MUMPS
SORTARRAY(X,SEP)  ;X is the list of items to sort  ;X1 is the temporary array  ;SEP is the separator string between items in the list X  ;Y is the returned list  ;This routine uses the inherent sorting of the arrays NEW I,X1,Y SET Y="" FOR I=1:1:$LENGTH(X,SEP) SET X1($PIECE(X,SEP,I))="" SET I="" FOR SET I=$O(X1(I)...
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 ...
#Run_BASIC
Run BASIC
sortData$ = "7, 6, 5, 4, 3, 2, 1, 0" sortIdx$ = "7, 2, 8"   numSort = 8 dim sortData(numSort) for i = 1 to numSort sortData(i) = val(word$(sortData$,i,",")) next i   while word$(sortIdx$,s + 1) <> "" s = s + 1 idx = val(word$(sortIdx$,s)) gosub [bubbleSort] wend end   [bubbleSort] sortSw = 1 while sortSw = ...
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 ...
#Rust
Rust
use std::collections::BTreeSet;   fn disjoint_sort(array: &mut [impl Ord], indices: &[usize]) { let mut sorted = indices.to_owned(); sorted.sort_unstable_by_key(|k| &array[*k]); indices .iter() .zip(sorted.iter()) .map(|(&a, &b)| if a > b { (b, a) } else { (a, b) }) .collect:...
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Standard_ML
Standard ML
fun mygt (s1, s2) = if size s1 <> size s2 then size s2 > size s1 else String.map Char.toLower s1 > String.map Char.toLower s2
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Swift
Swift
import Foundation   var list = ["this", "is", "a", "set", "of", "strings", "to", "sort", "This", "Is", "A", "Set", "Of", "Strings", "To", "Sort"]   list.sortInPlace {lhs, rhs in let lhsCount = lhs.characters.count let rhsCount = rhs.characters.count let result = rhsCount - lhsCount  ...
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 ...
#Lambdatalk
Lambdatalk
  {def bubblesort {def bubblesort.swap! {lambda {:a :n :i} {if {> :i :n} then :a else {bubblesort.swap! {if {> {A.get :i :a} {A.get {+ :i 1} :a}} then {A.set! :i {A.get {+ :i 1} :a} {A.set! {+ :i 1} {A.get :i :a} :a}} ...
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 ...
#Sidef
Sidef
class Array { method gnomesort { var (i=1, j=2); var len = self.len; while (i < len) { if (self[i-1] <= self[i]) { (i, j) = (j, j+1); } else { self[i-1, i] = self[i, i-1]; if (--i == 0) { ...