task_url
stringlengths
30
116
task_name
stringlengths
2
86
task_description
stringlengths
0
14.4k
language_url
stringlengths
2
53
language_name
stringlengths
1
52
code
stringlengths
0
61.9k
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Vlang
Vlang
import rand   fn shuffle_array(mut arr []int) { for i := arr.len - 1; i >= 0; i-- { j := rand.intn(i + 1) arr[i], arr[j] = arr[j], arr[i] } }   fn is_sorted(arr []int) bool { for i := 0; i < arr.len - 1; i++ { if arr[i] > arr[i + 1] { return false } } retu...
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 ...
#g-fu
g-fu
  (fun bubbles (vs) (let done? F n (len vs))   (while (not done?) (set done? T n (- n 1))   (for (n i) (let x (# vs i) j (+ i 1) y (# vs j)) (if (> x y) (set done? F (# vs i) y (# vs j) x))))   vs)   (bubbles '(2 1 3)) --- (1 2 3)  
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 ...
#PL.2FI
PL/I
SORT: PROCEDURE OPTIONS (MAIN); DECLARE A(0:9) FIXED STATIC INITIAL (5, 2, 7, 1, 9, 8, 6, 3, 4, 0);   CALL GNOME_SORT (A); put skip edit (A) (f(7));   GNOME_SORT: PROCEDURE (A) OPTIONS (REORDER); /* 9 September 2015 */ declare A(*) fixed; declare t fixed; declare (i, j) fixed;   i = 1; j = 2; do...
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 ...
#Pascal
Pascal
use strict; use warnings; use feature 'say';   sub cocktail_sort { my @a = @_; while (1) { my $swapped_forward = 0; for my $i (0..$#a-1) { if ($a[$i] gt $a[$i+1]) { @a[$i, $i+1] = @a[$i+1, $i]; $swapped_forward = 1; } } last...
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.
#Go
Go
package main   import ( "fmt" "net" )   func main() { conn, err := net.Dial("tcp", "localhost:256") if err != nil { fmt.Println(err) return } defer conn.Close() _, err = conn.Write([]byte("hello socket world")) if err != nil { fmt.Println(err) } }
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.
#Groovy
Groovy
s = new java.net.Socket("localhost", 256) s << "hello socket world" s.close()
http://rosettacode.org/wiki/Sleeping_Beauty_problem
Sleeping Beauty problem
Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin...
#Swift
Swift
let experiments = 1000000 var heads = 0 var wakenings = 0 for _ in (1...experiments) { wakenings += 1 switch (Int.random(in: 0...1)) { case 0: heads += 1 default: wakenings += 1 } } print("Wakenings over \(experiments) experiments: \(wakenings)") print("Sleeping Beauty should estimat...
http://rosettacode.org/wiki/Sleeping_Beauty_problem
Sleeping Beauty problem
Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin...
#Vlang
Vlang
import rand import rand.seed   fn sleeping_beauty(reps int) f64 { mut wakings := 0 mut heads := 0 for _ in 0..reps { coin := rand.intn(2) or {0} // heads = 0, tails = 1 say wakings++ if coin == 0 { heads++ } else { wakings++ } } println...
http://rosettacode.org/wiki/Sleeping_Beauty_problem
Sleeping Beauty problem
Background on the task In decision theory, The Sleeping Beauty Problem is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental subject, named Sleeping Beauty, agrees to an experiment as follows: Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin...
#Wren
Wren
import "random" for Random import "/fmt" for Fmt   var rand = Random.new()   var sleepingBeauty = Fn.new { |reps| var wakings = 0 var heads = 0 for (i in 0...reps) { var coin = rand.int(2) // heads = 0, tails = 1 say wakings = wakings + 1 if (coin == 0) { heads = heads + ...
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also ...
#jq
jq
def Smarandache_primes: # Output: a naively constructed stream of candidate strings of length >= 1 def Smarandache_candidates: def unconstrained($length): if $length==1 then "2", "3", "5", "7" else ("2", "3", "5", "7") as $n | $n + unconstrained($length -1 ) end; unconstrained(. - 1)...
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also ...
#Julia
Julia
  using Combinatorics, Primes   combodigits(len) = sort!(unique(map(y -> join(y, ""), with_replacement_combinations("2357", len))))   function getprimes(N, maxdigits=9) ret = [2, 3, 5, 7] perms = Int[] for i in 1:maxdigits-1, combo in combodigits(i), perm in permutations(combo) n = parse(Int64, Stri...
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also ...
#Lua
Lua
-- FUNCS: local function T(t) return setmetatable(t, {__index=table}) end table.firstn = function(t,n) local s=T{} n=n>#t and #t or n for i = 1,n do s[i]=t[i] end return s end   -- SIEVE: local sieve, S = {}, 50000 for i = 2,S do sieve[i]=true end for i = 2,S do if sieve[i] then for j=i*i,S,i do sieve[j]=nil end end en...
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...
#C.2B.2B
C++
  #include <windows.h> #include <ctime> #include <iostream> #include <string>   const int WID = 60, HEI = 30, MAX_LEN = 600; enum DIR { NORTH, EAST, SOUTH, WEST };   class snake { public: snake() { console = GetStdHandle( STD_OUTPUT_HANDLE ); SetConsoleTitle( "Snake" ); COORD coord = { WID + 1, HEI...
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....
#AWK
AWK
  # syntax: GAWK -f SMITH_NUMBERS.AWK # converted from C BEGIN { limit = 10000 printf("Smith Numbers < %d:\n",limit) for (a=4; a<limit; a++) { num_factors = num_prime_factors(a) if (num_factors < 2) { continue } prime_factors(a) if (sum_digits(a) == sum_factors(num_fact...
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 ...
#Elixir
Elixir
# Solve a Hidato Like Puzzle with Warnsdorff like logic applied # defmodule HLPsolver do defmodule Cell do defstruct value: -1, used: false, adj: [] end   def solve(str, adjacent, print_out\\true) do board = setup(str) if print_out, do: print(board, "Problem:") {start, _} = Enum.find(board, fn {_,...
http://rosettacode.org/wiki/Sokoban
Sokoban
Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character array where space is an empty...
#Python
Python
from array import array from collections import deque import psyco   data = [] nrows = 0 px = py = 0 sdata = "" ddata = ""   def init(board): global data, nrows, sdata, ddata, px, py data = filter(None, board.splitlines()) nrows = max(len(r) for r in data)   maps = {' ':' ', '.': '.', '@':' ', '#':'#', ...
http://rosettacode.org/wiki/Solve_a_Holy_Knight%27s_tour
Solve a Holy Knight's tour
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. This kind of knight's tour puzzle is similar to   Hidato. The present task is to produce a solution ...
#Phix
Phix
with javascript_semantics sequence board, warnsdorffs integer size, limit, nchars string fmt, blank constant ROW = 1, COL = 2, moves = {{-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2}} function onboard(integer row, integer col) return row>=1 and row<=size and col>=nchars and col<=nchars*size ...
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 ...
#Go
Go
package main   import ( "fmt" "sort" )   type pair struct { name, value string } type csArray []pair   // three methods satisfy sort.Interface func (a csArray) Less(i, j int) bool { return a[i].name < a[j].name } func (a csArray) Len() int { return len(a) } func (a csArray) Swap(i, j int) { a...
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle
Solve the no connection puzzle
You are given a box with eight holes labelled   A-to-H,   connected by fifteen straight lines in the pattern as shown below: A B /│\ /│\ / │ X │ \ / │/ \│ \ C───D───E───F \ │\ /│ / \ │ X │ / \│/ \│/ G H You ar...
#Phix
Phix
with javascript_semantics constant txt = """ A B /|\ /|\ / | X | \ / |/ \| \ C - D - E - F \ |\ /| / \ | X | / \|/ \|/ G H """ --constant links = "CA DA DB DC EA EB ED FB FE GC GD GE HD HE HF" constant links = {"","","A","ABC","ABD","BE","CDE","DEF"} fun...
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 ...
#Golfscript
Golfscript
[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 ...
#Groovy
Groovy
println ([2,4,0,3,1,2,-12].sort())
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Tcl
Tcl
  # Example input data: set oid_list [list \ 1.3.6.1.4.1.11.2.17.19.3.4.0.10 \ 1.3.6.1.4.1.11.2.17.5.2.0.79 \ 1.3.6.1.4.1.11.2.17.19.3.4.0.4 \ 1.3.6.1.4.1.11150.3.4.0.1 \ 1.3.6.1.4.1.11.2.17.19.3.4.0.1 \ 1.3.6.1....
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 ...
#Objective-C
Objective-C
#import <Foundation/Foundation.h>   @interface DisjointSublistView : NSMutableArray { NSMutableArray *array; int *indexes; int num_indexes; } - (instancetype)initWithArray:(NSMutableArray *)a andIndexes:(NSIndexSet *)ind; @end   @implementation DisjointSublistView - (instancetype)initWithArray:(NSMutableArray *)a...
http://rosettacode.org/wiki/Sort_three_variables
Sort three variables
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#zkl
zkl
x,y,z := "lions, tigers, and", "bears, oh my!", 0'|(from the "Wizard of OZ")|; x,y,z = List(x,y,z).sort(); println(x," | ",y," | ",z);   x,y,z := 77444, -12, 0; x,y,z = List(x,y,z).sort(); println(x," ",y," ",z);
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Perl
Perl
use feature 'say';   @strings = qw/Here are some sample strings to be sorted/;   # with a subroutine: sub mycmp { length $b <=> length $a || lc $a cmp lc $b } say join ' ', sort mycmp @strings;   # inline: say join ' ', sort {length $b <=> length $a || lc $a cmp lc $b} @strings   # for large inputs, can be faster with ...
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Wren
Wren
import "random" for Random import "/sort" for Sort   var bogoSort = Fn.new { |a| var rand = Random.new() while (!Sort.isSorted(a)) rand.shuffle(a) }   var a = [31, 41, 59, 26, 53, 58, 97, 93, 23, 84] System.print("Before: %(a)") bogoSort.call(a) System.print("After : %(a)")
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 ...
#Gambas
Gambas
Public Sub Main() Dim byToSort As Byte[] = [249, 28, 111, 36, 171, 98, 29, 448, 44, 147, 154, 46, 102, 183, 24, 120, 19, 123, 2, 17, 226, 11, 211, 25, 191, 205, 77] Dim byCount As Byte Dim bSorting As Boolean   Print "To sort: -" ShowWorking(byToSort) Print Repeat bSorting = False For byC...
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 ...
#PowerBASIC
PowerBASIC
SUB gnomeSort (a() AS LONG) DIM i AS LONG, j AS LONG i = 1 j = 2 WHILE (i < UBOUND(a) + 1) IF (a(i - 1) <= a(i)) THEN i = j INCR j ELSE SWAP a(i - 1), a(i) DECR i IF 0 = i THEN i = j INCR 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 ...
#Perl
Perl
use strict; use warnings; use feature 'say';   sub cocktail_sort { my @a = @_; while (1) { my $swapped_forward = 0; for my $i (0..$#a-1) { if ($a[$i] gt $a[$i+1]) { @a[$i, $i+1] = @a[$i+1, $i]; $swapped_forward = 1; } } last...
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.
#Haskell
Haskell
import Network   main = withSocketsDo $ sendTo "localhost" (PortNumber $ toEnum 256) "hello socket world"
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Icon_and_Unicon
Icon and Unicon
link cfunc procedure main () hello("localhost", 1024) end   procedure hello (host, port) write(tconnect(host, port) | stop("unable to connect to", host, ":", port) , "hello socket world") end
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also ...
#Mathematica_.2F_Wolfram_Language
Mathematica / Wolfram Language
ClearAll[SmarandachePrimeQ] SmarandachePrimeQ[n_Integer] := MatchQ[IntegerDigits[n], {(2 | 3 | 5 | 7) ..}] \[And] PrimeQ[n] s = Select[Range[10^5], SmarandachePrimeQ]; Take[s, UpTo[25]] s[[100]]
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also ...
#Nim
Nim
import math, strformat, strutils   const N = 35_000   # Sieve. var composite: array[0..N, bool] # Default is false and means prime. composite[0] = true composite[1] = true for n in 2..sqrt(N.toFloat).int: if not composite[n]: for k in countup(n * n, N, n): composite[k] = true     func digits(n: Positive): ...
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also ...
#Pascal
Pascal
program Smarandache;   uses sysutils,primsieve;// http://rosettacode.org/wiki/Extensible_prime_generator#Pascal const Digits : array[0..3] of Uint32 = (2,3,5,7); var i,j,pot10,DgtLimit,n,DgtCnt,v,cnt,LastPrime,Limit : NativeUint;   procedure Check(n:NativeUint); var p : NativeUint; Begin p := LastPrime; whi...
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...
#Delphi
Delphi
  unit SnakeGame;   interface   uses Winapi.Windows, System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Forms, Vcl.Dialogs, System.Generics.Collections, Vcl.ExtCtrls;   type TSnakeApp = class(TForm) procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FormPaint(Sender: TO...
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....
#BASIC
BASIC
10 DEFINT A-Z 20 DIM F(32) 30 FOR I=2 TO 9999 40 F=0: N=I 50 IF N>0 AND (N AND 1)=0 THEN N=N\2: F(F)=2: F=F+1: GOTO 50 60 P=3 70 GOTO 100 80 IF N MOD P=0 THEN N=N\P: F(F)=P: F=F+1: GOTO 80 90 P=P+2 100 IF P<=N GOTO 80 110 IF F<=1 GOTO 190 120 N=I: S=0 130 IF N>0 THEN S=S+N MOD 10: N=N\10: GOTO 130 140 FOR J=0 TO F-1 15...
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 ...
#Erlang
Erlang
  -module( solve_hidato_puzzle ).   -export( [create/2, solve/1, task/0] ).   -compile({no_auto_import,[max/2]}).   create( Grid_list, Number_list ) -> Squares = lists:flatten( [create_column(X, Y) || {X, Y} <- Grid_list] ), lists:foldl( fun store/2, dict:from_list(Squares), Number_list ).   print( Grid_list )...
http://rosettacode.org/wiki/Sokoban
Sokoban
Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character array where space is an empty...
#Racket
Racket
  #lang racket (require data/heap "../lib/vector2.rkt" "../lib/queue.rkt" (only-in "../lib/util.rkt" push! tstruct ret awhen))   (define level (list "#######" "# #" "# #" "#. # #" "#. $$ #" "#.$$ #" ...
http://rosettacode.org/wiki/Sokoban
Sokoban
Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character array where space is an empty...
#Raku
Raku
sub MAIN() { my $level = q:to//; ####### # # # # #. # # #. $$ # #.$$ # #.# @# #######   say 'level:'; print $level; say 'solution:'; say solve($level); }   class State { has Str $.board; has Str $.sol; has Int $.pos;   method move(Int $delta --> Str) { my $new =...
http://rosettacode.org/wiki/Solve_a_Holy_Knight%27s_tour
Solve a Holy Knight's tour
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. This kind of knight's tour puzzle is similar to   Hidato. The present task is to produce a solution ...
#Picat
Picat
import sat.   main => S = {".000....", ".0.00...", ".0000000", "000..0.0", "0.0..000", "1000000.", "..00.0..", "...000.."}, MaxR = len(S), MaxC = len(S[1]), M = new_array(MaxR,MaxC), StartR = _,  % make StartR and StartC global Sta...
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 ...
#Groovy
Groovy
class Holiday { def date def name Holiday(dateStr, name) { this.name = name; this.date = format.parse(dateStr) } String toString() { "${format.format date}: ${name}" } static format = new java.text.SimpleDateFormat("yyyy-MM-dd") }   def holidays = [ new Holiday("2009-12-25", "Christmas Day"), ...
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...
#Picat
Picat
import cp.   no_connection_puzzle(X) => N = 8, X = new_list(N), X :: 1..N, Graph = {{1,3}, {1,4}, {1,5}, {2,4}, {2,5}, {2,6}, {3,1}, {3,4}, {3,7}, {4,1}, {4,2}, {4,3}, {4,5}, {4,7}, {4,8}, {5,1}, {5,2}, {5,4}, {5,6}, {5,7}, {5,8}, {6,2}, {6,5}, {6,8}, {7,3}, {7,4}, {7,5}, ...
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...
#Prolog
Prolog
:- use_module(library(clpfd)).   edge(a, c). edge(a, d). edge(a, e). edge(b, d). edge(b, e). edge(b, f). edge(c, d). edge(c, g). edge(d, e). edge(d, g). edge(d, h). edge(e, f). edge(e, g). edge(e, h). edge(f, h).   connected(A, B) :- ( edge(A,B); edge(B, A)).   no_connection_puzzle(Vs) :- % construct the arranged l...
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 ...
#Haskell
Haskell
nums = [2,4,3,1,2] :: [Int] sorted = List.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 ...
#HicEst
HicEst
DIMENSION array(100)   array = INT( RAN(100) ) SORT(Vector=array, Sorted=array)
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#VBScript
VBScript
' Sort a list of object identifiers - VBScript function myCompare(x,y) dim i,b sx=split(x,".") sy=split(y,".") b=false for i=0 to ubound(sx) if i > ubound(sy) then b=true: exit for select case sgn(int(sx(i))-int(sy(i))) case 1: b=true: exit for case -1: b=false: exit for end select next myCompare=b...
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Wren
Wren
import "/fmt" for Fmt import "/sort" for Sort   var oids = [ "1.3.6.1.4.1.11.2.17.19.3.4.0.10", "1.3.6.1.4.1.11.2.17.5.2.0.79", "1.3.6.1.4.1.11.2.17.19.3.4.0.4", "1.3.6.1.4.1.11150.3.4.0.1", "1.3.6.1.4.1.11.2.17.19.3.4.0.1", "1.3.6.1.4.1.11150.3.4.0" ]   oids = oids.map { |oid| Fmt.v("s", 5, oid...
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 ...
#OCaml
OCaml
let disjoint_sort cmp values indices = let temp = Array.map (Array.get values) indices in Array.sort cmp temp; Array.sort compare indices; Array.iteri (fun i j -> values.(j) <- temp.(i)) indices   let () = let values = [| 7; 6; 5; 4; 3; 2; 1; 0 |] and indices = [| 6; 1; 7 |] in disjoint_sort compare value...
http://rosettacode.org/wiki/Sort_using_a_custom_comparator
Sort using a custom comparator
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Phix
Phix
function my_compare(sequence a, b) integer c = -compare(length(a),length(b)) -- descending length if c=0 then c = compare(lower(a),lower(b)) -- ascending lexical within same length end if return c end function ?custom_sort(my_compare,{"Here", "are", "some", "sample", "strings", "to", "b...
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#XPL0
XPL0
code Ran=1, ChOut=8, IntOut=11;   proc BogoSort(A, L); \Sort array A of length L int A, L; int I, J, T; [loop [I:= 0; loop [if A(I) > A(I+1) then quit; I:= I+1; if I >= L-1 then return; ]; I:= Ran(L); J:= Ran(L); T:= A(I); A(I):= A(J); ...
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#Yabasic
Yabasic
  sub shuffle(a()) n = arraysize(a(),1) m = arraysize(a(),1)*2   for k = 1 to m i = int(Ran(n)) j = int(Ran(n)) tmp = a(i) //swap a(i), a(j) a(i) = a(j) a(j) = tmp next k end sub   sub inorder(a()) n = arraysize(a(),1)   for i = 0 to n-2 if a(...
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 ...
#Go
Go
package main   import "fmt"   func main() { list := []int{31, 41, 59, 26, 53, 58, 97, 93, 23, 84} fmt.Println("unsorted:", list)   bubblesort(list) fmt.Println("sorted! ", list) }   func bubblesort(a []int) { for itemCount := len(a) - 1; ; itemCount-- { hasChanged := false for index...
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 ...
#PowerShell
PowerShell
  function gnomesort($a) { $size, $i, $j = $a.Count, 1, 2 while($i -lt $size) { if ($a[$i-1] -le $a[$i]) { $i = $j $j++ } else { $a[$i-1], $a[$i] = $a[$i], $a[$i-1] $i-- if($i -eq 0) { $i = $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 ...
#Phix
Phix
with javascript_semantics function cocktail_sort(sequence s) s = deep_copy(s) integer swapped = 1, f = 1, t = length(s)-1, d = 1 while swapped do swapped = 0 for i=f to t by d do object si = s[i], sn = s[i+1] if si>sn then s[i] = sn...
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.
#IDL
IDL
socket, unit, 'localhost',256,/get_lun printf,unit,"hello socket world" close, unit
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.
#J
J
coinsert'jsocket' [ require 'socket' NB. Sockets library socket =. >{.sdcheck sdsocket'' NB. Open a socket host =. sdcheck sdgethostbyname 'localhost' NB. Resolve host sdcheck sdconnect socket ; host ,< 256 NB. Create connection to port 256 sdcheck 'hello s...
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also ...
#Perl
Perl
use strict; use warnings; use feature 'say'; use feature 'state'; use ntheory qw<is_prime>; use Lingua::EN::Numbers qw(num2en_ordinal);   my @prime_digits = <2 3 5 7>; my @spds = grep { is_prime($_) && /^[@{[join '',@prime_digits]}]+$/ } 1..100; my @p = map { $_+3, $_+7 } map { 10*$_ } @prime_digits;   while ($#spds...
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...
#Go
Go
package main   import ( "errors" "fmt" "log" "math/rand" "time"   termbox "github.com/nsf/termbox-go" )   func main() { rand.Seed(time.Now().UnixNano()) score, err := playSnake() if err != nil { log.Fatal(err) } fmt.Println("Final score:", score) }   type snake struct { body []position // tail to...
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....
#BCPL
BCPL
get "libhdr"   // Find the sum of the digits of N let digsum(n) = n<10 -> n, n rem 10 + digsum(n/10)   // Factorize N let factors(n, facs) = valof $( let count = 0 and fac = 3   // Powers of 2 while n>0 & (n & 1)=0 $( n := n >> 1 facs!count := 2 count := count + 1 $)   // O...
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....
#C
C
  #include <stdlib.h> #include <stdio.h> #include <stdbool.h>   int numPrimeFactors(unsigned x) { unsigned p = 2; int pf = 0; if (x == 1) return 1; else { while (true) { if (!(x % p)) { pf++; x /= p; if (x == 1) ...
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 ...
#Go
Go
package main   import ( "fmt" "sort" "strconv" "strings" )   var board [][]int var start, given []int   func setup(input []string) { /* This task is not about input validation, so we're going to trust the input to be valid */ puzzle := make([][]string, len(input)) for i := 0; i < len(...
http://rosettacode.org/wiki/Sokoban
Sokoban
Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character array where space is an empty...
#Ring
Ring
  #--------------------------------------------------# # Sokoban Game # #--------------------------------------------------#   # Game Data   aPlayer = [ :Row = 3, :Col = 4 ]   aLevel1 = [ [1,1,1,2,2,2,2,2,1,1,1,1,1,1], [1,2,2,2,1,1,1,2,1,1,1,1,1,1], [1,2,4,3,5,1,1,2,1,1,1,1,1,1], [1,2,2,2,1,5,4,2,1,1...
http://rosettacode.org/wiki/Solve_a_Holy_Knight%27s_tour
Solve a Holy Knight's tour
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. This kind of knight's tour puzzle is similar to   Hidato. The present task is to produce a solution ...
#Python
Python
  from sys import stdout moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ]     def solve(pz, sz, sx, sy, idx, cnt): if idx > cnt: return 1   for i in range(len(moves)): x = sx + moves[i][0] y = sy + moves[i][1] if sz > x > -1 and sz > y > ...
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 ...
#Haskell
Haskell
import Data.List import Data.Function (on)   data Person = P String Int deriving (Eq)   instance Show Person where show (P name val) = "Person " ++ name ++ " with value " ++ show val   instance Ord Person where compare (P a _) (P b _) = compare a b   pVal :: Person -> Int pVal (P _ x) = x   people :: [Perso...
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...
#Python
Python
from __future__ import print_function from itertools import permutations from enum import Enum   A, B, C, D, E, F, G, H = Enum('Peg', 'A, B, C, D, E, F, G, H')   connections = ((A, C), (A, D), (A, E), (B, D), (B, E), (B, F), (G, C), (G, D), (G, E), (H, D), (H, E), (H, F), ...
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 ...
#Huginn
Huginn
main() { 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 ...
#Icon_and_Unicon
Icon and Unicon
S := sort(L:= [63, 92, 51, 92, 39, 15, 43, 89, 36, 69]) # will sort a list
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers
Sort a list of object identifiers
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#zkl
zkl
fcn sortOIDS(oids){ // oids is not modified, a new list is created // pad each oid with a terminal (-1) so zip won't short cut oids=oids.pump(List(),fcn(oid){ (oid + ".-1").split(".").apply("toInt") }); oids.sort( // in place sort fcn(a,b){ // a & b are (x,y,z,...-1), eg (0,4,2,54,-1), (4,6,-1) a.zip...
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 ...
#ooRexx
ooRexx
data = .array~of(7, 6, 5, 4, 3, 2, 1, 0) -- this could be a list, array, or queue as well because of polymorphism -- also, ooRexx arrays are 1-based, so using the alternate index set for the -- problem. indexes = .set~of(7, 2, 8) call disjointSorter data, indexes   say "Sorted data is: ["data~toString("l", ", ")"]"   :...
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 ...
#PHP
PHP
<?php function mycmp($s1, $s2) { if ($d = strlen($s2) - strlen($s1)) return $d; return strcasecmp($s1, $s2); }   $strings = array("Here", "are", "some", "sample", "strings", "to", "be", "sorted"); usort($strings, "mycmp"); ?>
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort
Sorting algorithms/Bogosort
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#zkl
zkl
fcn increasing(list){ list.len()<2 or list.reduce(fcn(a,b){ if(b<a) return(Void.Stop,False); b }).toBool() }   ns:=L(5,23,1,6,123,7,23); while(not increasing(ns)){ ns=ns.shuffle() } ns.println();
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 ...
#Groovy
Groovy
def makeSwap = { a, i, j = i+1 -> print "."; a[[i,j]] = a[[j,i]] }   def checkSwap = { a, i, j = i+1 -> [(a[i] > a[j])].find { it }.each { makeSwap(a, i, j) } }   def bubbleSort = { list -> boolean swapped = true while (swapped) { swapped = (1..<list.size()).any { checkSwap(list, it-1) } } list }
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 ...
#PureBasic
PureBasic
Procedure GnomeSort(Array a(1)) Protected Size = ArraySize(a()) + 1 Protected i = 1, j = 2   While i < Size If a(i - 1) <= a(i) ;for descending SORT, use >= for comparison i = j j + 1 Else Swap a(i - 1), a(i) i - 1 If i = 0 i = j j + 1 EndIf E...
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 ...
#PHP
PHP
function cocktailSort($arr){ if (is_string($arr)) $arr = str_split(preg_replace('/\s+/','',$arr));   do{ $swapped = false; for($i=0;$i<count($arr);$i++){ if(isset($arr[$i+1])){ if($arr[$i] > $arr[$i+1]){ list($arr[$i], $arr[$i+1]) = array($arr[$i+1], $arr[$i]); $swapped = true; } } } ...
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Java
Java
import java.io.IOException; import java.net.*; public class SocketSend { public static void main(String args[]) throws IOException { sendData("localhost", "hello socket world"); }   public static void sendData(String host, String msg) throws IOException { Socket sock = new Socket( host, 256 ); sock.ge...
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.
#Jsish
Jsish
#!/usr/bin/env jsish function sockets() { var sock = new Socket({client:true, port:256, noAsync:true, udp:true}); sock.send(-1, 'hello socket world'); sock.close(); }   ;sockets();   /* =!EXPECTSTART!= sockets() ==> undefined =!EXPECTEND!= */
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also ...
#Phix
Phix
with javascript_semantics atom t0 = time() sequence spds = {2,3,5,7} atom nxt_candidate = 23 sequence adj = {{4,-4},sq_mul({1,2,2,-5},10)}, adjn = {1,1} include mpfr.e mpz zprime = mpz_init() procedure populate_spds(integer n) while length(spds)<n do mpz_set_d(zprime,nxt_candidate) if m...
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...
#Haskell
Haskell
{-# LANGUAGE TemplateHaskell #-} import Control.Monad.Random (getRandomRs) import Graphics.Gloss.Interface.Pure.Game import Lens.Micro ((%~), (^.), (&), set) import Lens.Micro.TH (makeLenses)   -------------------------------------------------------------------------------- -- all data types   data Snake = Snake { _bod...
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....
#C.23
C#
using System; using System.Collections.Generic;   namespace SmithNumbers { class Program { static int SumDigits(int n) { int sum = 0; while (n > 0) { n = Math.DivRem(n, 10, out int rem); sum += rem; } return sum; }   ...
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle
Solve a Hidato puzzle
The task is to write a program which solves Hidato (aka Hidoku) puzzles. The rules are: You are given a grid with some numbers placed in it. The other squares in the grid will be blank. The grid is not necessarily rectangular. The grid may have holes in it. The grid is always connected. The number “1” is always ...
#Haskell
Haskell
{-# LANGUAGE TupleSections #-} {-# LANGUAGE Rank2Types #-}   import qualified Data.IntMap as I import Data.IntMap (IntMap) import Data.List import Data.Maybe import Data.Time.Clock   data BoardProblem = Board { cells :: IntMap (IntMap Int) , endVal :: Int , onePos :: (Int, Int) , givens :: [Int] } deriving (S...
http://rosettacode.org/wiki/Sokoban
Sokoban
Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred. Sokoban levels are usually stored as a character array where space is an empty...
#Ruby
Ruby
require 'set'   class Sokoban def initialize(level) board = level.each_line.map(&:rstrip) @nrows = board.map(&:size).max board.map!{|line| line.ljust(@nrows)} board.each_with_index do |row, r| row.each_char.with_index do |ch, c| @px, @py = c, r if ch == '@' or ch == '+' end en...
http://rosettacode.org/wiki/Solve_a_Holy_Knight%27s_tour
Solve a Holy Knight's tour
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. This kind of knight's tour puzzle is similar to   Hidato. The present task is to produce a solution ...
#Racket
Racket
#lang racket (require "hidato-family-solver.rkt")   (define knights-neighbour-offsets '((+1 +2) (-1 +2) (+1 -2) (-1 -2) (+2 +1) (-2 +1) (+2 -1) (-2 -1)))   (define solve-a-knights-tour (solve-hidato-family knights-neighbour-offsets))   (displayln (puzzle->string (solve-a-knights-tour #(#(_ 0 0 0 _ _ _ _) #...
http://rosettacode.org/wiki/Solve_a_Holy_Knight%27s_tour
Solve a Holy Knight's tour
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies. This kind of knight's tour puzzle is similar to   Hidato. The present task is to produce a solution ...
#Raku
Raku
my @adjacent = [ -2, -1], [ -2, 1], [-1,-2], [-1,+2], [+1,-2], [+1,+2], [ +2, -1], [ +2, 1];   put "\n" xx 60;   solveboard q:to/END/; . 0 0 0 . 0 . 0 0 . 0 0 0 0 0 0 0 0 0 0 . . 0 . 0 0 . 0 . . 0 0 0 1 0 0 0...
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 ...
#Icon_and_Unicon
Icon and Unicon
record star(name,HIP)   procedure main()   Ori := [ star("Betelgeuse",27989), star("Rigel",24436), star("Belatrix", 25336), star("Alnilam",26311) ]   write("Some Orion stars by HIP#") every write( (x := !sortf(Ori,2)).name, " HIP ",x.HIP) 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 ...
#J
J
names =: ;: 'Perlis Wilkes Hamming Minsky Wilkinson McCarthy' values=: ;: 'Alan Maurice Richard Marvin James John' pairs =: values ,. names pairs /: names +-------+---------+ |Richard|Hamming | +-------+---------+ |John |McCarthy | +-------+---------+ |Marvin |Minsky | +-------+---------+ |Alan |Perl...
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...
#Racket
Racket
#lang racket ;; Solve the no connection puzzle. Tim Brown Oct. 2014   ;; absolute difference of a and b if they are both true (define (and- a b) (and a b (abs (- a b))))   ;; Finds the differences of all established connections in the network (define (network-diffs (A #f) (B #f) (C #f) (D #f) (E #f) (F #f) (G #f) (H #f...
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...
#Raku
Raku
my @adjacent = gather -> $y, $x { take [$y,$x] if abs($x|$y) > 2; } for flat -5 .. 5 X -5 .. 5;   solveboard q:to/END/; . _ . . _ . . . . . . . _ . _ 1 . _ . . . . . . . _ . . _ . END   sub solveboard($board) { my $max = +$board.comb(/\w+/); my $width = $max.chars;   my @grid; ...
http://rosettacode.org/wiki/Sort_an_integer_array
Sort an integer array
Sorting Algorithm This is a sorting algorithm.   It may be applied to a set of data in order to sort it.     For comparing various sorts, see compare sorts.   For other sorting algorithms,   see sorting algorithms,   or: O(n logn) sorts Heap sort | Merge sort | Patience sort | Quick sort O(n log2n) sorts Shell Sort ...
#IDL
IDL
result = array[sort(array)]
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 ...
#Inform_7
Inform 7
let L be {5, 4, 7, 1, 18}; sort L;
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 ...
#Order
Order
#include <order/interpreter.h>   #define ORDER_PP_DEF_8sort_disjoint_sublist ORDER_PP_FN( \ 8fn(8L, 8I, \ 8lets((8I, 8seq_sort(8less, 8tuple_to_seq(8I))) \ (8J, \...
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 ...
#PARI.2FGP
PARI/GP
sortsome(v,which)={ my(x=sum(i=1,#which,1<<(which[i]-1)),u=vecextract(v,x)); u=vecsort(u); which=vecsort(which); for(i=1,#which,v[which[i]]=u[i]); v };
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 ...
#PicoLisp
PicoLisp
: (sort '("def" "abc" "ghi") >) -> ("ghi" "def" "abc")
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 ...
#PL.2FI
PL/I
MRGEPKG: package exports(MERGESORT,MERGE,RMERGE);   DCL (T(4)) CHAR(20) VAR; /* scratch space of length N/2 */   MERGE: PROCEDURE (A,LA,B,LB,C,CMPFN); DECLARE (A(*),B(*),C(*)) CHAR(*) VAR; DECLARE (LA,LB) FIXED BIN(31) NONASGN; DECLARE (I,J,K) FIXED BIN(31); DECLARE CMPFN ENTRY( NONASGN CHAR(*) VA...
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 ...
#Haskell
Haskell
bsort :: Ord a => [a] -> [a] bsort s = case _bsort s of t | t == s -> t | otherwise -> bsort t where _bsort (x:x2:xs) | x > x2 = x2:(_bsort (x:xs)) | otherwise = x:(_bsort (x2:xs)) _bsort s = s
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 ...
#Python
Python
>>> def gnomesort(a): i,j,size = 1,2,len(a) while i < size: if a[i-1] <= a[i]: i,j = j, j+1 else: a[i-1],a[i] = a[i],a[i-1] i -= 1 if i == 0: i,j = j, j+1 return a   >>> gnomesort([3,4,2,5,1,6]) [1, 2, 3, 4, 5, 6] >>>
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 ...
#PicoLisp
PicoLisp
(de cocktailSort (Lst) (use (Swapped L) (loop (off Swapped) (setq L Lst) (while (cdr L) (when (> (car L) (cadr L)) (xchg L (cdr L)) (on Swapped) ) (pop 'L) ) (NIL Swapped Lst) (off Swapped) (loop ...
http://rosettacode.org/wiki/Sockets
Sockets
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket. Catching any exceptions or errors is not required.
#Julia
Julia
  socket = connect("localhost",256) write(socket, "hello socket world") 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.
#Kotlin
Kotlin
// version 1.2.21   import java.net.Socket   fun main(args: Array<String>) { val sock = Socket("localhost", 256) sock.use { it.outputStream.write("hello socket world".toByteArray()) } }
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence
Smarandache prime-digital sequence
The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime. For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime. Task Show the first 25 SPDS primes. Show the hundredth SPDS prime. See also ...
#Python
Python
  def divisors(n): divs = [1] for ii in range(2, int(n ** 0.5) + 3): if n % ii == 0: divs.append(ii) divs.append(int(n / ii)) divs.append(n) return list(set(divs))     def is_prime(n): return len(divisors(n)) == 2     def digit_check(n): if len(str(n))<2: ...
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...
#J
J
require'ide/qt/gl2' coinsert 'jgl2'   open=: wd@{{)n pc s closeok; cc n isidraw; set n wh 400 400; pshow; }}   start=: {{ speed=: {.y,200 open'' snake=: 10 10,10 11,:10 12 newdot'' draw'' }}   newdot=: {{ dot=: ({~ ?@#) snake -.~ ,/(#: i.)40 40 }}   s_n_char=: {{ select. {.toupper sysdata case....