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/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.2B.2B | C++ |
#include <iostream>
#include <vector>
#include <iomanip>
void primeFactors( unsigned n, std::vector<unsigned>& r ) {
int f = 2; if( n == 1 ) r.push_back( 1 );
else {
while( true ) {
if( !( n % f ) ) {
r.push_back( f );
n /= f; if( n == 1 ) return;
... |
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 ... | #Icon_and_Unicon | Icon and Unicon | global nCells, cMap, best
record Pos(r,c)
procedure main(A)
puzzle := showPuzzle("Input",readPuzzle())
QMouse(puzzle,findStart(puzzle),&null,0)
showPuzzle("Output", solvePuzzle(puzzle)) | write("No solution!")
end
procedure readPuzzle()
# Start with a reduced puzzle space
p := [[-1]]
nCells ... |
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... | #Tcl | Tcl | package require Tcl 8.5
proc solveSokoban b {
set cols [string length [lindex $b 0]]
set dxes [list [expr {-$cols}] $cols -1 1]
set i 0
foreach c [split [join $b ""] ""] {
switch $c {
" " {lappend bdc " "}
"#" {lappend bdc "#"}
"@" {lappend bdc " ";set startplayer $i }
"$" {lappen... |
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 ... | #REXX | REXX | /*REXX program solves the holy knight's tour problem for a (general) NxN chessboard.*/
blank=pos('//', space(arg(1), 0))\==0 /*see if the pennies are to be shown. */
parse arg ops '/' cent /*obtain the options and the pennies. */
parse var ops N sRank sFile . ... |
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
... | #Java | Java | import java.util.Arrays;
import java.util.Comparator;
public class SortComp {
public static class Pair {
public String name;
public String value;
public Pair(String n, String v) {
name = n;
value = v;
}
}
public static void main(String[] args) {
... |
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... | #Red | Red | Red ["Solve the no connection puzzle"]
points: [a b c d e f g h]
; 'links' series will be scanned by pairs: [a c], [a d] etc.
links: [a c a d a e b d b e b f c d c g d e d g d h e f e g e h f h]
allpegs: [1 2 3 4 5 6 7 8]
; check if two points are connected (then game is lost) i.e.
; both are have a value (not z... |
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... | #REXX | REXX | /*REXX program solves the "no─connection" puzzle (the puzzle has eight pegs). */
parse arg limit . /*number of solutions wanted.*/ /* ╔═══════════════════════════╗ */
if limit=='' | limit=="," then limit= 1 /* ║ A B ║ */
... |
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
... | #Io | Io | mums := list(2,4,3,1,2)
sorted := nums sort # returns a new sorted array. 'nums' is unchanged
nums sortInPlace # sort 'nums' "in-place" |
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
... | #J | J | /:~ |
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
... | #pascal | pascal |
program disjointsort;
procedure swap(var a, b: Integer);
var
temp: Integer;
begin
temp := a;
a := b;
b := temp;
end;
procedure d_sort(var index,arr:array of integer);
var
n,i,j,num:integer;
begin
num:=length(index);
for n:=1 to 2 do
begin
for i... |
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
... | #Pop11 | Pop11 | lvars ls = ['Here' 'are' 'some' 'sample' 'strings' 'to' 'be' 'sorted'];
define compare(s1, s2);
lvars k = length(s2) - length(s1);
if k < 0 then
return(true);
elseif k > 0 then
return(false);
else
return (alphabefore(uppertolower(s1), uppertolower(s2)));
endif;
enddefine;
syssort(ls, compare) -> ls;
NOT... |
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
... | #PowerBASIC | PowerBASIC | FUNCTION Sorter(p1 AS STRING, p2 AS STRING) AS LONG
'if p1 should be first, returns -1
'if p2 should be first, returns 1
' if they're equal, returns 0
IF LEN(p1) > LEN(p2) THEN
FUNCTION = -1
ELSEIF LEN(p2) > LEN(p1) THEN
FUNCTION = 1
ELSEIF UCASE$(p1) > UCASE$(p2) THEN
... |
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
... | #Haxe | Haxe | class BubbleSort {
@:generic
public static function sort<T>(arr:Array<T>) {
var madeChanges = false;
var itemCount = arr.length;
do {
madeChanges = false;
itemCount--;
for (i in 0...itemCount) {
if (Reflect.compare(arr[i], arr[i + 1]) > 0) {
var temp = arr[i + 1];
... |
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort | Sorting algorithms/Gnome sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Quackery | Quackery | [ dup size times
[ i^ 0 > if
[ dup i^ 1 - peek
over i^ peek
2dup > iff
[ dip [ swap i^ poke ]
swap i^ 1 - poke
-1 step ]
else 2drop ] ] ] is gnomesort ( [ --> [ ) |
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
... | #PL.2FI | PL/I | cocktail: procedure (A);
declare A(*) fixed;
declare t fixed;
declare stable bit (1);
declare (i, n) fixed binary (31);
n = hbound(A,1);
do until (stable);
stable = '1'b;
do i = 1 to n-1, n-1 to 1 by -1;
if A(i) > A(i+1) then
do; stable = '0'b; /* still unsorted, so ... |
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.
| #Lasso | Lasso | local(net) = net_tcp
#net->connect('127.0.0.1',256)
#net->dowithclose => {
#net->writestring('Hello 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.
| #Lua | Lua | socket = require "socket"
host, port = "127.0.0.1", 256
sid = socket.udp()
sid:sendto( "hello socket world", host, port )
sid:close() |
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
... | #Quackery | Quackery | [ true swap
[ 10 /mod
[ table 1 1 0 0 1 0 1 0 1 1 ]
iff [ dip not ] done
dup 0 = until ]
drop ] is digitsprime ( n --> b )
[ temp put [] 0
[ dup digitsprime if
[ dup isprime if
[ dup dip join ] ]
1+
over size temp share = unti... |
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
... | #Raku | Raku | use Lingua::EN::Numbers;
use ntheory:from<Perl5> <:all>;
# Implemented as a lazy, extendable list
my $spds = grep { .&is_prime }, flat [2,3,5,7], [23,27,33,37,53,57,73,77], -> $p
{ state $o++; my $oom = 10**(1+$o); [ flat (2,3,5,7).map: -> $l { (|$p).map: $l×$oom + * } ] } … *;
say 'Smarandache prime-digitals:';
... |
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... | #Java | Java |
const L = 1, R = 2, D = 4, U = 8;
var block = 24, wid = 30, hei = 20, frameR = 7, fruit, snake;
function Snake() {
this.length = 1;
this.alive = true;
this.pos = createVector( 1, 1 );
this.posArray = [];
this.posArray.push( createVector( 1, 1 ) );
this.dir = R;
this.draw = function() {
... |
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.... | #Clojure | Clojure | (defn divisible? [a b]
(zero? (mod a b)))
(defn prime? [n]
(and (> n 1) (not-any? (partial divisible? n) (range 2 n))))
(defn prime-factors
([n] (prime-factors n 2 '()))
([n candidate acc]
(cond
(<= n 1) (reverse acc)
(zero? (rem n candidate)) (recur
(/ n ca... |
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 ... | #Java | Java | import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Hidato {
private static int[][] board;
private static int[] given, start;
public static void main(String[] args) {
String[] input = {"_ 33 35 _ _ . . .",
"_ _ 24 22 _ . . .",
"... |
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... | #Wren | Wren | import "/dynamic" for Tuple
import "/llist" for DLinkedList
import "/set" for Set
var Board = Tuple.create("Board", ["cur", "sol", "x", "y"])
class Sokoban {
construct new(board) {
_destBoard = ""
_currBoard = ""
_nCols = board[0].count
_playerX = 0
_playerY = 0
f... |
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 ... | #Ruby | Ruby | require 'HLPsolver'
ADJACENT = [[-1,-2],[-2,-1],[-2,1],[-1,2],[1,2],[2,1],[2,-1],[1,-2]]
boardy = <<EOS
. . 0 0 0
. . 0 . 0 0
. 0 0 0 0 0 0 0
0 0 0 . . 0 . 0
0 . 0 . . 0 0 0
1 0 0 0 0 0 0
. . 0 0 . 0
. . . 0 0 0
EOS
t0 = Time.now
HLPsolver.new(boardy).solve
puts " #{Time.now - t0} sec" |
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
... | #JavaScript | JavaScript | var arr = [
{id: 3, value: "foo"},
{id: 2, value: "bar"},
{id: 4, value: "baz"},
{id: 1, value: 42},
{id: 5, something: "another string"} // Works with any object declaring 'id' as a number.
];
arr = arr.sort(function(a, b) {return a.id - b.id}); // Sort with comparator checking the id.
|
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
... | #jq | jq | def example:
[
{"name": "Joe", "value": 3},
{"name": "Bill", "value": 4},
{"name": "Alice", "value": 20},
{"name": "Harry", "value": 3}
]; |
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... | #Ruby | Ruby |
# Solve No Connection Puzzle
#
# Nigel_Galloway
# October 6th., 2014
require 'HLPSolver'
ADJACENT = [[0,0]]
A,B,C,D,E,F,G,H = [0,1],[0,2],[1,0],[1,1],[1,2],[1,3],[2,1],[2,2]
board1 = <<EOS
. 0 0 .
0 0 1 0
. 0 0 .
EOS
g = HLPsolver.new(board1)
g.board[A[0]][A[1]].adj = [B,G,H,F]
g.board[B[0]]... |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Java | Java | import java.util.Arrays;
public class Example {
public static void main(String[] args)
{
int[] nums = {2,4,3,1,2};
Arrays.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
... | #JavaScript | JavaScript | function int_arr(a, b) {
return a - b;
}
var numbers = [20, 7, 65, 10, 3, 0, 8, -60];
numbers.sort(int_arr);
document.write(numbers); |
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
... | #Perl | Perl | #!/usr/bin/perl -w
use strict ;
# this function sorts the array in place
sub disjointSort {
my ( $values , @indices ) = @_ ;
@{$values}[ sort @indices ] = sort @{$values}[ @indices ] ;
}
my @values = ( 7 , 6 , 5 , 4 , 3 , 2 , 1 , 0 ) ;
my @indices = ( 6 , 1 , 7 ) ;
disjointSort( \@values , @indices ) ;
pri... |
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
... | #PowerShell | PowerShell | $list = "Here", "are", "some", "sample", "strings", "to", "be", "sorted"
$list | Sort-Object {-$_.Length},{$_} |
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
... | #Prolog | Prolog | rosetta_sort :-
L = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted" ],
predsort(my_comp, L, L1),
writeln('Input list :'),
maplist(my_write, L), nl,nl,
writeln('Sorted list :'),
maplist(my_write, L1).
my_comp(Comp, W1, W2) :-
string_length(W1,L1),
string_length(W2, L2),
( L1 < L2 -> Comp... |
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
... | #HicEst | HicEst | SUBROUTINE Bubble_Sort(a)
REAL :: a(1)
DO j = LEN(a)-1, 1, -1
swapped = 0
DO i = 1, j
IF (a(i) > a(i+1)) THEN
temp = a(i)
a(i) = a(i+1)
a(i+1) = temp
swapped = 1
ENDIF
ENDDO
IF (swapped == 0) RETURN
ENDDO
END |
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
... | #R | R | gnomesort <- function(x)
{
i <- 1
j <- 1
while(i < length(x))
{
if(x[i] <= x[i+1])
{
i <- j
j <- j+1
} else
{
temp <- x[i]
x[i] <- x[i+1]
x[i+1] <- temp
i <- i - 1
if(i == 0)
{
i <- j
j <... |
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort | Sorting algorithms/Cocktail sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #PowerShell | PowerShell | function CocktailSort ($a) {
$l = $a.Length
$m = 0
if( $l -gt 1 )
{
$hasChanged = $true
:outer while ($hasChanged) {
$hasChanged = $false
$l--
for ($i = $m; $i -lt $l; $i++) {
if ($a[$i] -gt $a[$i+1]) {
$a[$i], $a[$i+1] = $a[$i+1], $a[$i]
$hasChanged = $true
}
}
if(-not $hasC... |
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.
| #MACRO-10 | MACRO-10 |
TITLE SOCKET
COMMENT !
Socket Example ** PDP-10 Assembly Language (KJX 2022)
Assembler: MACRO-10 Operating System: TOPS-20 V7
On TOPS-20, TCP-connections are made by opening a special
file on the "TCP:" device (in this case "TCP:256"). Apart
from the funky filename, there is virtual... |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | socket = SocketConnect["localhost:256", "TCP"];
WriteString[socket, "hello socket world"];
Close[socket]; |
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
... | #REXX | REXX | /*REXX program lists a sequence of SPDS (Smarandache prime-digital sequence) primes.*/
parse arg n q /*get optional number of primes to find*/
if n=='' | n=="," then n= 25 /*Not specified? Then use the default.*/
if q='' then q= 100 1000 ... |
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
... | #Ring | Ring |
load "stdlib.ring"
see "First 25 Smarandache primes:" + nl + nl
num = 0
limit = 26
limit100 = 100
for n = 1 to 34000
flag = 0
nStr = string(n)
for x = 1 to len(nStr)
nx = number(nStr[x])
if isprime(n) and isprime(nx)
flag = flag + 1
else
exit
ok
... |
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... | #JavaScript | JavaScript |
const L = 1, R = 2, D = 4, U = 8;
var block = 24, wid = 30, hei = 20, frameR = 7, fruit, snake;
function Snake() {
this.length = 1;
this.alive = true;
this.pos = createVector( 1, 1 );
this.posArray = [];
this.posArray.push( createVector( 1, 1 ) );
this.dir = R;
this.draw = function() {
... |
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.... | #CLU | CLU | % Get all digits of a number
digits = iter (n: int) yields (int)
while n > 0 do
yield(n // 10)
n := n / 10
end
end digits
% Get all prime factors of a number
prime_factors = iter (n: int) yields (int)
% Take factors of 2 out first (the compiler should optimize)
while n // 2 = 0 do yiel... |
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.... | #Cowgol | Cowgol | include "cowgol.coh";
typedef N is uint16; # 16-bit math is good enough
# Print a value right-justified in a field of length N
sub print_right(n: N, width: uint8) is
var arr: uint8[16];
var buf := &arr[0];
var nxt := UIToA(n as uint32, 10, buf);
var len := (nxt - buf) as uint8;
while len < width... |
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 ... | #Julia | Julia | module Hidato
export hidatosolve, printboard, hidatoconfigure
function hidatoconfigure(str)
lines = split(str, "\n")
nrows, ncols = length(lines), length(split(lines[1], r"\s+"))
board = fill(-1, (nrows, ncols))
presets = Vector{Int}()
starts = Vector{CartesianIndex{2}}()
maxmoves = 0
fo... |
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 ... | #Tcl | Tcl | package require Tcl 8.6
oo::class create HKTSolver {
variable grid start limit
constructor {puzzle} {
set grid $puzzle
for {set y 0} {$y < [llength $grid]} {incr y} {
for {set x 0} {$x < [llength [lindex $grid $y]]} {incr x} {
if {[set cell [lindex $grid $y $x]] == 1} {
set start [list $y $x]
... |
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Julia | Julia | lst = Pair[Pair("gold", "shiny"),
Pair("neon", "inert"),
Pair("sulphur", "yellow"),
Pair("iron", "magnetic"),
Pair("zebra", "striped"),
Pair("star", "brilliant"),
Pair("apple", "tasty"),
Pair("ruby", "red"),
Pair("dice", "random"),
... |
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
... | #Kotlin | Kotlin | // version 1.1
data class Employee(val name: String, var category: String) : Comparable<Employee> {
override fun compareTo(other: Employee) = this.name.compareTo(other.name)
}
fun main(args: Array<String>) {
val employees = arrayOf(
Employee("David", "Manager"),
Employee("Alice", "Sales"),
... |
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... | #Scala | Scala | object NoConnection extends App {
private def links = Seq(
Seq(2, 3, 4), // A to C,D,E
Seq(3, 4, 5), // B to D,E,F
Seq(2, 4), // D to C, E
Seq(5), // E to F
Seq(2, 3, 4), // G to C,D,E
Seq(3, 4, 5)) // H to D,E,F
private def genRandom: LazyList[Seq[Int]] = util.Random.shuffle((1 to 8).to... |
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
... | #Jinja | Jinja |
from jinja2 import Template
print(Template("{{ [53, 17, 42, 61, 35] | sort }}").render())
|
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
... | #jq | jq | [2,1,3] | sort # => [1,2,3] |
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
... | #Phix | Phix | with javascript_semantics
function disjoint_sort(sequence s, sequence idx)
idx = unique(idx)
integer l = length(idx)
sequence copies = repeat(0, l)
for i=1 to l do
copies[i] = s[idx[i]]
end for
copies = sort(copies)
for i=1 to l do
s[idx[i]] = copies[i]
end for
return... |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Python | Python | strings = "here are Some sample strings to be sorted".split()
def mykey(x):
return -len(x), x.upper()
print sorted(strings, key=mykey) |
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
... | #Icon_and_Unicon | Icon and Unicon | procedure main() #: demonstrate various ways to sort a list and string
demosort(bubblesort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
end
procedure bubblesort(X,op) #: return sorted list
local i,swapped
op := sortop(op,X) # select how and what we sort
swapped := 1
... |
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort | Sorting algorithms/Gnome sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Racket | Racket |
#lang racket
;; Translation of the pseudo code
(define (gnome-sort1 a <=?)
(define size (vector-length a))
(define (swap i j)
(define t (vector-ref a i))
(vector-set! a i (vector-ref a j))
(vector-set! a j t))
(let loop ([i 1] [j 2])
(when (< i size)
(if (<=? (vector-ref a (sub1 i)) (vec... |
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
... | #Prolog | Prolog | ctail(_, [], Rev, Rev, sorted) :- write(Rev), nl.
ctail(fwrd, [A,B|T], In, Rev, unsorted) :- A > B, !,
ctail(fwrd, [B,A|T], In, Rev, _).
ctail(bkwd, [A,B|T], In, Rev, unsorted) :- A < B, !,
ctail(bkwd, [B,A|T], In, Rev, _).
ctail(D,[A|T], In, Rev, Ch) :- !, ctail(D, T, [A|In], Rev, Ch).
cocktail([], []).
cocktail(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.
| #Myrddin | Myrddin | use std
const main = {
match std.dial("tcp!localhost!256")
| `std.Ok fd:
std.write(fd, "hello socket world")
std.close(fd)
| `std.Err err:
std.fatal("could not open fd: {}\n", 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.
| #Nanoquery | Nanoquery | import Nanoquery.Net
p = new(Port)
p.connect("localhost", 256)
p.write("hello socket world")
p.close() |
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
... | #Rust | Rust | fn is_prime(n: u32) -> bool {
if n < 2 {
return false;
}
if n % 2 == 0 {
return n == 2;
}
if n % 3 == 0 {
return n == 3;
}
if n % 5 == 0 {
return n == 5;
}
let mut p = 7;
const WHEEL: [u32; 8] = [4, 2, 4, 2, 4, 6, 2, 6];
loop {
for w in... |
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
... | #Ruby | Ruby | require "prime"
smarandache = Enumerator.new do|y|
prime_digits = [2,3,5,7]
prime_digits.each{|pr| y << pr} # yield the below-tens
(1..).each do |n|
prime_digits.repeated_permutation(n).each do |perm|
c = perm.join.to_i * 10
y << c + 3 if (c+3).prime?
y << c + 7 if (c+7).prime?
end
... |
http://rosettacode.org/wiki/Snake | Snake |
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Snake is a game where the player maneuvers a line which grows i... | #Julia | Julia | using Makie
mutable struct SnakeGame
height
width
snake
food
end
function SnakeGame(;height=6, width=8)
snake = [rand(CartesianIndices((height, width)))]
food = rand(CartesianIndices((height, width)))
while food == snake[1]
food = rand(CartesianIndices((height, width)))
end
... |
http://rosettacode.org/wiki/Smith_numbers | Smith numbers | Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers are also known as joke numbers.... | #D | D | import std.stdio;
void main() {
int cnt;
for (int n=1; n<10_000; n++) {
auto factors = primeFactors(n);
if (factors.length > 1) {
int sum = sumDigits(n);
foreach (f; factors) {
sum -= sumDigits(f);
}
if (sum==0) {
... |
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle | Solve a Hidato puzzle | The task is to write a program which solves Hidato (aka Hidoku) puzzles.
The rules are:
You are given a grid with some numbers placed in it. The other squares in the grid will be blank.
The grid is not necessarily rectangular.
The grid may have holes in it.
The grid is always connected.
The number “1” is always ... | #Kotlin | Kotlin | // version 1.2.0
lateinit var board: List<IntArray>
lateinit var given: IntArray
lateinit var start: IntArray
fun setUp(input: List<String>) {
val nRows = input.size
val puzzle = List(nRows) { input[it].split(" ") }
val nCols = puzzle[0].size
val list = mutableListOf<Int>()
board = List(nRows + ... |
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 ... | #Wren | Wren | import "/fmt" for Fmt
var moves = [ [-1, -2], [1, -2], [-1, 2], [1, 2], [-2, -1], [-2, 1], [2, -1], [2, 1] ]
var board1 =
" xxx " +
" x xx " +
" xxxxxxx" +
"xxx x x" +
"x x xxx" +
"sxxxxxx " +
" xx x " +
" xxx "
var board2 =
".....s.x....." +
".....x.x....." +... |
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Lambdatalk | Lambdatalk |
{def H.sort
{def H.sort.i
{lambda {:f :x :a}
{if {A.empty? :a}
then {A.new :x}
else {if {:f :x {A.first :a}}
then {A.addfirst! :x :a}
else {A.addfirst! {A.first :a} {H.sort.i :f :x {A.rest :a}}} }}}}
{def H.sort.r
{lambda {:f :a1 :a2}
{if {A.empty? :a1}
then :a2
else {H.sort.r :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... | #Tcl | Tcl | package require Tcl 8.6
package require struct::list
proc haveAdjacent {a b c d e f g h} {
expr {
[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... |
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
... | #Julia | Julia | julia> a = [4,2,3,1]
4-element Int32 Array:
4
2
3
1
julia> sort(a) #out-of-place/non-mutating sort
4-element Int32 Array:
1
2
3
4
julia> a
4-element Int32 Array:
4
2
3
1
julia> sort!(a) # in-place/mutating sort
4-element Int32 Array:
1
2
3
4
julia> a
4-element Int32 Array:
1
2
3
4 |
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
... | #K | K | num: -10?10 / Integers from 0 to 9 in random order
5 9 4 2 0 3 6 1 8 7
srt: {x@<x} / Generalized sort ascending
srt num
0 1 2 3 4 5 6 7 8 9 |
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
... | #PicoLisp | PicoLisp | (let (Values (7 6 5 4 3 2 1 0) Indices (7 2 8))
(mapc
'((V I) (set (nth Values I) V))
(sort (mapcar '((N) (get Values N)) Indices))
(sort Indices) )
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
... | #Prolog | Prolog |
% ===
% Problem description
% ===
% http://rosettacode.org/wiki/Sort_disjoint_sublist
%
% Given a list of values and a set of integer indices into that value list,
% the task is to sort the values at the given indices, while preserving the
% values at indices outside the set of those to be sorted.
%
% Make your exam... |
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
... | #Quackery | Quackery | [ $ "" swap
witheach
[ upper join ] ] is upper$ ( $ --> )
[ over size over size
2dup = iff
[ 2drop upper$
swap upper$ $< ]
else
[ 2swap 2drop < ] ] is comparator ( $ $ -- b )
$ ‘here are Some sample strings to be sorted’
nest$ sortwith comparator
witheac... |
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
... | #R | R | v = c("Here", "are", "some", "sample", "strings", "to", "be", "sorted")
print(v[order(-nchar(v), tolower(v))]) |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Io | Io |
List do(
bubblesort := method(
t := true
while( t,
t := false
for( j, 0, self size - 2,
if( self at( j ) start > self at( j+1 ) start,
self swapIndices( j,j+1 )
t := true
)
)
)
return( self )
)
)
|
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
... | #Raku | Raku | sub gnome_sort (@a) {
my ($i, $j) = 1, 2;
while $i < @a {
if @a[$i - 1] <= @a[$i] {
($i, $j) = $j, $j + 1;
}
else {
(@a[$i - 1], @a[$i]) = @a[$i], @a[$i - 1];
$i--;
($i, $j) = $j, $j + 1 if $i == 0;
}
}
} |
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort | Sorting algorithms/Cocktail sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #PureBasic | PureBasic | ;sorts an array of integers
Procedure cocktailSort(Array a(1))
Protected index, hasChanged, low, high
low = 0
high = ArraySize(a()) - 1
Repeat
hasChanged = #False
For index = low To high
If a(index) > a(index + 1)
Swap a(index), a(index + 1)
hasChanged = #True
EndIf
N... |
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.
| #Neko | Neko | /**
Sockets in Neko
Tectonics:
nekoc sockets.neko
sudo nc -vulp 256 & sudo neko sockets
*/
var socket_init = $loader.loadprim("std@socket_init", 0);
var socket_new = $loader.loadprim("std@socket_new", 1);
var host_resolve = $loader.loadprim("std@host_resolve", 1);
var socket_connect = $loader.loadprim("std@so... |
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.
| #Nemerle | Nemerle | using System.Text;
using System.Net.Sockets;
module Program
{
Main() : void
{
def sock = Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Connect("127.0.0.1", 1000);
_ = sock.Send(Encoding.ASCII.GetBytes("Hell, world!"));
sock.Close();
}
} |
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
... | #Sidef | Sidef | func is_prime_digital(n) {
n.is_prime && n.digits.all { .is_prime }
}
say is_prime_digital.first(25).join(',')
say is_prime_digital.nth(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
... | #Swift | Swift | func isPrime(number: Int) -> Bool {
if number < 2 {
return false
}
if number % 2 == 0 {
return number == 2
}
if number % 3 == 0 {
return number == 3
}
if number % 5 == 0 {
return number == 5
}
var p = 7
let wheel = [4,2,4,2,4,6,2,6]
while true ... |
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
... | #Wren | Wren | import "/math" for Int
var limit = 1000
var spds = List.filled(limit, 0)
spds[0] = 2
var i = 3
var count = 1
while (count < limit) {
if (Int.isPrime(i)) {
var digits = i.toString
if (digits.all { |d| "2357".contains(d) }) {
spds[count] = i
count = count + 1
}
}
... |
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... | #Kotlin | Kotlin | // Kotlin Native v0.5
import kotlinx.cinterop.*
import platform.posix.*
import platform.windows.*
const val WID = 60
const val HEI = 30
const val MAX_LEN = 600
const val NUL = '\u0000'
enum class Dir { NORTH, EAST, SOUTH, WEST }
class Snake {
val console: HANDLE
var alive = false
val brd = CharArray... |
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.... | #Delphi | Delphi | /* Find the sum of the digits of a number */
proc nonrec digitsum(word n) word:
word sum;
sum := 0;
while n ~= 0 do
sum := sum + n % 10;
n := n / 10
od;
sum
corp
/* Find all prime factors and write them into the given array
(which is assumed to be big enough); return the amount ... |
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.... | #Draco | Draco | /* Find the sum of the digits of a number */
proc nonrec digitsum(word n) word:
word sum;
sum := 0;
while n ~= 0 do
sum := sum + n % 10;
n := n / 10
od;
sum
corp
/* Find all prime factors and write them into the given array
(which is assumed to be big enough); return the amount ... |
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 ... | #Mathprog | Mathprog | /*Hidato.mathprog, part of KuKu by Nigel Galloway
Find a solution to a Hidato problem
Nigel_Galloway@operamail.com
April 1st., 2011
*/
param ZBLS;
param ROWS;
param COLS;
param D := 1;
set ROWSR := 1..ROWS;
set COLSR := 1..COLS;
set ROWSV := (1-D)..(ROWS+D);
set COLSV := (1-D)..(COLS+D);
param Iz{ROWSR,COLS... |
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
... | #Liberty_BASIC | Liberty BASIC |
N =20
dim IntArray$( N, 2)
print "Original order"
for i =1 to N
name$ =mid$( "SortArrayOfCompositeStructures", int( 25 *rnd( 1)), 1 +int( 4 *rnd( 1)))
IntArray$( i, 1) =name$
print name$,
t$ =str$( int( 1000 *rnd( 1)))
IntArray$( i, 2) =t$
print t$
next i
sort IntArray$(), 1, N, 1
print "S... |
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... | #Wren | Wren | import "/dynamic" for Tuple
var Solution = Tuple.create("Solution", ["p", "tests", "swaps"])
// Holes A=0, B=1, …, H=7
// With connections:
var conn = "
A B
/|\\ /|\\
/ | X | \\
/ |/ \\| \\
C - D - E - F
\\ |\\ /| /
\\ | X | /
\\|/ \\|/
G H
"
var connections ... |
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
... | #Kotlin | Kotlin | // version 1.0.6
fun main(args: Array<String>) {
val ints = intArrayOf(6, 2, 7, 8, 3, 1, 10, 5, 4, 9)
ints.sort()
println(ints.joinToString(prefix = "[", postfix = "]"))
} |
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
... | #Lambdatalk | Lambdatalk |
1) sorting digits in a number returns a new number of ordered digits
{W.sort < 51324}
-> 12345
2) sorting a sequence of numbers returns a new ordered sequence of these numbers
{S.sort < 51 111 33 2 41}
-> 2 33 41 51 111
3) sorting an array of numbers returns the same array ordered
{A.sort! < {A.new 51 111 33 2 41... |
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
... | #PowerShell | PowerShell |
function sublistsort($values, $indices) {
$indices = $indices | sort
$sub, $i = ($values[$indices] | sort), 0
$indices | foreach { $values[$_] = $sub[$i++] }
$values
}
$values = 7, 6, 5, 4, 3, 2, 1, 0
$indices = 6, 1, 7
"$(sublistsort $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
... | #Racket | Racket |
#lang racket
;; Using a combination of the two comparisons
(define (sort1 words)
(sort words (λ(x y)
(define xl (string-length x)) (define yl (string-length y))
(or (> xl yl) (and (= xl yl) (string-ci<? x y))))))
(sort1 '("Some" "pile" "of" "words"))
;; -> '("words" "pile" "Some" "... |
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
... | #Raku | Raku | my @strings = <Here are some sample strings to be sorted>;
put @strings.sort:{.chars, .lc};
put sort -> $x { $x.chars, $x.lc }, @strings; |
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
... | #J | J | bubbleSort=: (([ (<. , >.) {.@]) , }.@])/^:_ |
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort | Sorting algorithms/Gnome sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Rascal | Rascal | import List;
public list[int] gnomeSort(a){
i = 1;
j = 2;
while(i < size(a)){
if(a[i-1] <= a[i]){
i = j;
j += 1;}
else{
temp = a[i-1];
a[i-1] = a[i];
a[i] = temp;
i = i - 1;
if(i == 0){
i = j;
j += 1;}}}
return a;
} |
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort | Sorting algorithms/Cocktail sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Python | Python | def cocktailSort(A):
up = range(len(A)-1)
while True:
for indices in (up, reversed(up)):
swapped = False
for i in indices:
if A[i] > A[i+1]:
A[i], A[i+1] = A[i+1], A[i]
swapped = True
if not swapped:
... |
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.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
import java.net.
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
parse arg host':'port':'message
if host = '' then host = 'localhost'
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.
| #NewLISP | NewLISP |
(set 'socket (net-connect "localhost" 256))
(net-send socket "hello socket world")
(net-close socket)
(exit)
|
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
... | #XPL0 | XPL0 | func IsPrime(N); \Return 'true' if N is prime
int N, I;
[if N <= 2 then return N = 2;
if (N&1) = 0 then \even >2\ return false;
for I:= 3 to sqrt(N) do
[if rem(N/I) = 0 then return false;
I:= I+1;
];
return true;
];
func PrimeDigits(N); \Return 'true' if all digits are prime
int N;
[repeat N:=... |
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence | Smarandache prime-digital sequence | The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime.
For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime.
Task
Show the first 25 SPDS primes.
Show the hundredth SPDS prime.
See also
... | #Yabasic | Yabasic | num = 0
limit = 26
limit100 = 100
print "First 25 Smarandache primes:\n"
for n = 1 to 34000
flag = 0
nStr$ = str$(n)
for x = 1 to len(nStr$)
nx = val(mid$(nStr$,x,1))
if isPrime(n) and isPrime(nx) then
flag = flag + 1
else
break
end if
next
i... |
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
... | #zkl | zkl | var [const] BI=Import("zklBigNum"); // libGMP
spds:=Walker.zero().tweak(fcn(ps){
var [const] nps=T(0,0,1,1,0,1,0,1,0,0); // 2,3,5,7
p:=ps.nextPrime().toInt();
if(p.split().filter( fcn(n){ 0==nps[n] }) ) return(Void.Skip);
p // 733 --> (7,3,3) --> () --> good, 29 --> (2,9) --> (9) --> bad
}.fp(B... |
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... | #Lua | Lua | UP, RIGHT, DOWN, LEFT = 1, 2, 3, 4
UpdateTime=0.200
Timer = 0
GridSize = 30
GridWidth, GridHeight = 20, 10
local directions = {
[UP] = {x= 0, y=-1},
[RIGHT] = {x= 1, y= 0},
[DOWN] = {x= 0, y= 1},
[LEFT] = {x=-1, y= 0},
}
local function isPositionInBody(x, y)
for i = 1, #Body-3, 2 do -- skip tail, it moves... |
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.... | #Elixir | Elixir | defmodule Smith do
def number?(n) do
d = decomposition(n)
length(d)>1 and sum_digits(n) == Enum.map(d, &sum_digits/1) |> Enum.sum
end
defp sum_digits(n) do
Integer.digits(n) |> Enum.sum
end
defp decomposition(n, k\\2, acc\\[])
defp decomposition(n, k, acc) when n < k*k, do: [n | acc]
def... |
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.23 | F# |
// Generate Smith Numbers. Nigel Galloway: November 6th., 2020
let fN g=Seq.unfold(fun n->match n with 0->None |_->Some(n%10,n/10)) g |> Seq.sum
let rec fG(n,g) p=match g%p with 0->fG (n+fN p,g/p) p |_->(n,g)
primes32()|>Seq.pairwise|>Seq.collect(fun(n,g)->[n+1..g-1])|>Seq.takeWhile(fun n->n<10000)
|>Seq.filter(fun g... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.