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.
Example
Using the number 166
Find the prime factors of 166 which are: 2 x 83
Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13
Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13
Therefore, the number 166 is a Smith number.
Task
Write a program to find all Smith numbers below 10000.
See also
from Wikipedia: [Smith number].
from MathWorld: [Smith number].
from OEIS A6753: [OEIS sequence A6753].
from OEIS A104170: [Number of Smith numbers below 10^n].
from The Prime pages: [Smith numbers].
| #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;
}
else f++;
}
}
}
unsigned sumDigits( unsigned n ) {
unsigned sum = 0, m;
while( n ) {
m = n % 10; sum += m;
n -= m; n /= 10;
}
return sum;
}
unsigned sumDigits( std::vector<unsigned>& v ) {
unsigned sum = 0;
for( std::vector<unsigned>::iterator i = v.begin(); i != v.end(); i++ ) {
sum += sumDigits( *i );
}
return sum;
}
void listAllSmithNumbers( unsigned n ) {
std::vector<unsigned> pf;
for( unsigned i = 4; i < n; i++ ) {
primeFactors( i, pf ); if( pf.size() < 2 ) continue;
if( sumDigits( i ) == sumDigits( pf ) )
std::cout << std::setw( 4 ) << i << " ";
pf.clear();
}
std::cout << "\n\n";
}
int main( int argc, char* argv[] ) {
listAllSmithNumbers( 10000 );
return 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 present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique.
It may be assumed that the difference between numbers present on the grid is not greater than lucky 13.
The aim is to place a natural number in each blank square so that in the sequence of numbered squares from “1” upwards, each square is in the wp:Moore neighborhood of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints).
Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order.
A square may only contain one number.
In a proper Hidato puzzle, the solution is unique.
For example the following problem
has the following solution, with path marked on it:
Related tasks
A* search algorithm
N-queens problem
Solve a Holy Knight's tour
Solve a Knight's tour
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle;
| #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 := maxCols := 0
every line := !&input do {
put(p,[: -1 | gencells(line) | -1 :])
maxCols <:= *p[-1]
}
put(p, [-1])
# Now normalize all rows to the same length
every i := 1 to *p do p[i] := [: !p[i] | (|-1\(maxCols - *p[i])) :]
return p
end
procedure gencells(s)
static WS, NWS
initial {
NWS := ~(WS := " \t")
cMap := table() # Map to/from internal model
cMap["#"] := -1; cMap["_"] := 0
cMap[-1] := " "; cMap[0] := "_"
}
s ? while not pos(0) do {
w := (tab(many(WS))|"", tab(many(NWS))) | break
w := numeric(\cMap[w]|w)
if -1 ~= w then nCells +:= 1
suspend w
}
end
procedure showPuzzle(label, p)
write(label," with ",nCells," cells:")
every r := !p do {
every c := !r do writes(right((\cMap[c]|c),*nCells+1))
write()
}
return p
end
procedure findStart(p)
if \p[r := !*p][c := !*p[r]] = 1 then return Pos(r,c)
end
procedure solvePuzzle(puzzle)
if path := \best then {
repeat {
loc := path.getLoc()
puzzle[loc.r][loc.c] := path.getVal()
path := \path.getParent() | break
}
return puzzle
}
end
class QMouse(puzzle, loc, parent, val)
method getVal(); return val; end
method getLoc(); return loc; end
method getParent(); return parent; end
method atEnd(); return (nCells = val) = puzzle[loc.r][loc.c]; end
method goNorth(); return visit(loc.r-1,loc.c); end
method goNE(); return visit(loc.r-1,loc.c+1); end
method goEast(); return visit(loc.r, loc.c+1); end
method goSE(); return visit(loc.r+1,loc.c+1); end
method goSouth(); return visit(loc.r+1,loc.c); end
method goSW(); return visit(loc.r+1,loc.c-1); end
method goWest(); return visit(loc.r, loc.c-1); end
method goNW(); return visit(loc.r-1,loc.c-1); end
method visit(r,c)
if /best & validPos(r,c) then return Pos(r,c)
end
method validPos(r,c)
xv := puzzle[r][c]
if xv = (val+1) then return
if xv = 0 then { # make sure this path hasn't already gone there
ancestor := self
while xl := (ancestor := \ancestor.getParent()).getLoc() do
if (xl.r = r) & (xl.c = c) then fail
return
}
end
initially
val +:= 1
if atEnd() then return best := self
QMouse(puzzle, goNorth(), self, val)
QMouse(puzzle, goNE(), self, val)
QMouse(puzzle, goEast(), self, val)
QMouse(puzzle, goSE(), self, val)
QMouse(puzzle, goSouth(), self, val)
QMouse(puzzle, goSW(), self, val)
QMouse(puzzle, goWest(), self, val)
QMouse(puzzle, goNW(), self, val)
end |
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 square
# is a wall
@ is the player
$ is a box
. is a goal
+ is the player on a goal
* is a box on a goal
#######
# #
# #
#. # #
#. $$ #
#.$$ #
#.# @#
#######
Sokoban solutions are usually stored in the LURD format, where lowercase l, u, r and d represent a move in that (left, up, right, down) direction and capital LURD represents a push.
Please state if you use some other format for either the input or output, and why.
For more information, see the Sokoban wiki.
| #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 }
"$" {lappend bdc " ";lappend startbox $i}
"." {lappend bdc " "; lappend targets $i}
"+" {lappend bdc " ";set startplayer $i; lappend targets $i}
"*" {lappend bdc " ";lappend startbox $i;lappend targets $i}
}
incr i
}
set q [list [list $startplayer $startbox] {}]
set store([lindex $q 0]) {}
for {set idx 0} {$idx < [llength $q]} {incr idx 2} {
lassign [lindex $q $idx] x boxes
foreach dir {U D L R} dx $dxes {
if {[set x1 [expr {$x + $dx}]] in $boxes} {
if {[lindex $bdc [incr x1 $dx]] ne " " || $x1 in $boxes} {
continue
}
set tmpboxes $boxes
set x1 [expr {$x + $dx}]
for {set i 0} {$i < [llength $boxes]} {incr i} {
if {[lindex $boxes $i] == $x1} {
lset tmpboxes $i [expr {$x1 + $dx}]
break
}
}
if {$dx == 1 || $dx == -1} {
set next [list $x1 $tmpboxes]
} else {
set next [list $x1 [lsort -integer $tmpboxes]]
}
if {![info exists store($next)]} {
if {$targets eq [lindex $next 1]} {
foreach c [lindex $q [expr {$idx + 1}]] {
lassign $c ispush olddir
if {$ispush} {
append solution $olddir
} else {
append solution [string tolower $olddir]
}
}
return [append solution $dir]
}
set store($next) {}
set nm [lindex $q [expr {$idx + 1}]]
lappend q $next
lappend q [lappend nm [list 1 $dir]]
}
} elseif {[lindex $bdc $x1] eq " "} {
set next [list [expr {$x + $dx}] $boxes]
if {![info exists store($next)]} {
set store($next) {}
set nm [lindex $q [expr {$idx + 1}]]
lappend q $next
lappend q [lappend nm [list 0 $dir]]
}
}
}
}
error "no solution"
} |
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 to such problems. At least demonstrate your program by solving the following:
Example
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
Note that the zeros represent the available squares, not the pennies.
Extra credit is available for other interesting examples.
Related tasks
A* search algorithm
Knight's tour
N-queens problem
Solve a Hidato puzzle
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #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 . /*boardsize, starting position, pennys.*/
if N=='' | N=="," then N=8 /*no boardsize specified? Use default.*/
if sRank=='' | sRank=="," then sRank=N /*starting rank given? " " */
if sFile=='' | sFile=="," then sFile=1 /* " file " " " */
NN=N**2; NxN='a ' N"x"N ' chessboard' /*file [↓] [↓] r=rank */
@.=; do r=1 for N; do f=1 for N; @.r.f=.; end /*f*/; end /*r*/
/*[↑] create an empty NxN chessboard.*/
cent=space( translate( cent, , ',') ) /*allow use of comma (,) for separater.*/
cents=0 /*number of pennies on the chessboard. */
do while cent\='' /* [↓] possibly place the pennies. */
parse var cent cr cf x '/' cent /*extract where to place the pennies. */
if x='' then x=1 /*if number not specified, use 1 penny.*/
if cr='' then iterate /*support the "blanking" option. */
do cf=cf for x /*now, place X pennies on chessboard.*/
@.cr.cf= '¢' /*mark chessboard position with a penny*/
end /*cf*/ /* [↑] places X pennies on chessboard.*/
end /*while*/ /* [↑] allows of the placing of X ¢s*/
/* [↓] traipse through the chessboard.*/
do r=1 for N; do f=1 for N; cents=cents + (@.r.f=='¢'); end /*f*/; end /*r*/
/* [↑] count the number of pennies. */
if cents\==0 then say cents 'pennies placed on chessboard.'
target=NN - cents /*use this as the number of moves left.*/
Kr = '2 1 -1 -2 -2 -1 1 2' /*the legal "rank" moves for a knight.*/
Kf = '1 2 2 1 -1 -2 -2 -1' /* " " "file" " " " " */
kr.M=words(Kr) /*number of possible moves for a Knight*/
parse var Kr Kr.1 Kr.2 Kr.3 Kr.4 Kr.5 Kr.6 Kr.7 Kr.8 /*parse the legal moves by hand.*/
parse var Kf Kf.1 Kf.2 Kf.3 Kf.4 Kf.5 Kf.6 Kf.7 Kf.8 /* " " " " " " */
beg= '-1-' /* [↑] create the NxN chessboard. */
if @.sRank.sFile ==. then @.sRank.sFile=beg /*the knight's starting position. */
if @.sRank.sFile\==beg then do sRank=1 for N /*find starting rank for the knight.*/
do sFile=1 for N /* " " file " " " */
if @.sRank.sFile\==. then iterate
@.sRank.sFile=beg /*the knight's starting position. */
leave sRank /*we have a spot, so leave all this.*/
end /*sFile*/
end /*sRank*/
@hkt= "holy knight's tour" /*a handy─dandy literal for the SAYs. */
if \move(2,sRank,sFile) & \(N==1) then say 'No' @hkt "solution for" NxN'.'
else say 'A solution for the' @hkt "on" NxN':'
/*show chessboard with moves and coins.*/
!=left('', 9 * (n<18) ); say /*used for indentation of chessboard. */
_=substr( copies("┼───", N), 2); say ! translate('┌'_"┐", '┬', "┼")
do r=N for N by -1; if r\==N then say ! '├'_"┤"; L=@.
do f=1 for N; [email protected]; if ?==target then ?='end'; L=L'│'center(?,3)
end /*f*/
if blank then L=translate(L,,'¢') /*blank out the pennies on chessboard ?*/
say ! translate(L'│', , .) /*display a rank of the chessboard. */
end /*r*/ /*19x19 chessboard can be shown 80 cols*/
say ! translate('└'_"┘", '┴', "┼") /*display the last rank of chessboard. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
move: procedure expose @. Kr. Kf. target; parse arg #,rank,file /*obtain move,rank,file.*/
do t=1 for Kr.M; nr=rank+Kr.t; nf=file+Kf.t /*position of the knight*/
if @.nr.nf==. then do; @.nr.nf=# /*Empty? Knight can move*/
if #==target then return 1 /*is this the last move?*/
if move(#+1,nr,nf) then return 1 /* " " " " " */
@.nr.nf=. /*undo the above move. */
end /*try a different move. */
end /*t*/ /* [↑] all moves tried.*/
return 0 /*tour isn't possible. */ |
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Sort an array of composite structures by a key.
For example, if you define a composite structure that presents a name-value pair (in pseudo-code):
Define structure pair such that:
name as a string
value as a string
and an array of such pairs:
x: array of pairs
then define a sort routine that sorts the array x by the key name.
This task can always be accomplished with Sorting Using a Custom Comparator.
If your language is not listed here, please see the other article.
| #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) {
Pair[] pairs = {new Pair("06-07", "Ducks"), new Pair("00-01", "Avalanche"),
new Pair("02-03", "Devils"), new Pair("01-02", "Red Wings"),
new Pair("03-04", "Lightning"), new Pair("04-05", "lockout"),
new Pair("05-06", "Hurricanes"), new Pair("99-00", "Devils"),
new Pair("07-08", "Red Wings"), new Pair("08-09", "Penguins")};
sortByName(pairs);
for (Pair p : pairs) {
System.out.println(p.name + " " + p.value);
}
}
public static void sortByName(Pair[] pairs) {
Arrays.sort(pairs, new Comparator<Pair>() {
public int compare(Pair p1, Pair p2) {
return p1.name.compareTo(p2.name);
}
});
}
} |
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle | Solve the no connection puzzle | You are given a box with eight holes labelled A-to-H, connected by fifteen straight lines in the pattern as shown below:
A B
/│\ /│\
/ │ X │ \
/ │/ \│ \
C───D───E───F
\ │\ /│ /
\ │ X │ /
\│/ \│/
G H
You are also given eight pegs numbered 1-to-8.
Objective
Place the eight pegs in the holes so that the (absolute) difference between any two numbers connected by any line is greater than one.
Example
In this attempt:
4 7
/│\ /│\
/ │ X │ \
/ │/ \│ \
8───1───6───2
\ │\ /│ /
\ │ X │ /
\│/ \│/
3 5
Note that 7 and 6 are connected and have a difference of 1, so it is not a solution.
Task
Produce and show here one solution to the puzzle.
Related tasks
A* search algorithm
Solve a Holy Knight's tour
Knight's tour
N-queens problem
Solve a Hidato puzzle
Solve a Holy Knight's tour
Solve a Hopido puzzle
Solve a Numbrix puzzle
4-rings or 4-squares puzzle
See also
No Connection Puzzle (youtube).
| #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 zero) and absolute difference is 1
connected: func [x y] [all [
x * y <> 0
1 = absolute (x - y)
]]
; a list of points is valid if no connexion is found
isvalid: function [pegs [block!]] [
; assign pegs values to points, or 0 for remaining points
set points append/dup copy pegs 0 8
foreach [x y] links [if connected get x get y [return false]]
true
]
; recursively build a list of up to 8 valid points
check: function [pegs [block!]] [
if isvalid pegs [
rest: difference allpegs pegs
either empty? rest [
print rejoin ["Here is a solution: " pegs]
halt ; comment this line to get all solutions
][
foreach peg rest [check append copy pegs peg]
]
]
]
; start with and empty list
check []
|
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle | Solve the no connection puzzle | You are given a box with eight holes labelled A-to-H, connected by fifteen straight lines in the pattern as shown below:
A B
/│\ /│\
/ │ X │ \
/ │/ \│ \
C───D───E───F
\ │\ /│ /
\ │ X │ /
\│/ \│/
G H
You are also given eight pegs numbered 1-to-8.
Objective
Place the eight pegs in the holes so that the (absolute) difference between any two numbers connected by any line is greater than one.
Example
In this attempt:
4 7
/│\ /│\
/ │ X │ \
/ │/ \│ \
8───1───6───2
\ │\ /│ /
\ │ X │ /
\│/ \│/
3 5
Note that 7 and 6 are connected and have a difference of 1, so it is not a solution.
Task
Produce and show here one solution to the puzzle.
Related tasks
A* search algorithm
Solve a Holy Knight's tour
Knight's tour
N-queens problem
Solve a Hidato puzzle
Solve a Holy Knight's tour
Solve a Hopido puzzle
Solve a Numbrix puzzle
4-rings or 4-squares puzzle
See also
No Connection Puzzle (youtube).
| #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 ║ */
/* ║ /│\ /│\ ║ */
@. = /* ║ / │ \/ │ \ ║ */
@.1 = 'A C D E' /* ║ / │ /\ │ \ ║ */
@.2 = 'B D E F' /* ║ / │/ \│ \ ║ */
@.3 = 'C A D G' /* ║ C────D────E────F ║ */
@.4 = 'D A B C E G' /* ║ \ │\ /│ / ║ */
@.5 = 'E A B D F H' /* ║ \ │ \/ │ / ║ */
@.6 = 'F B E H' /* ║ \ │ /\ │ / ║ */
@.7 = 'G C D E' /* ║ \│/ \│/ ║ */
@.8 = 'H D E F' /* ║ G H ║ */
cnt= 0 /* ╚═══════════════════════════╝ */
do pegs=1 while @.pegs\==''; _= word(@.pegs, 1)
subs= 0
do #=1 for words(@.pegs) -1 /*create list of node paths.*/
__= word(@.pegs, # + 1); if __>_ then iterate
subs= subs + 1; !._.subs= __
end /*#*/
!._.0= subs /*assign the number of the node paths. */
end /*pegs*/
pegs= pegs - 1 /*the number of pegs to be seated. */
_= ' ' /*_ is used for indenting the output.*/
do a=1 for pegs; if ?('A') then iterate
do b=1 for pegs; if ?('B') then iterate
do c=1 for pegs; if ?('C') then iterate
do d=1 for pegs; if ?('D') then iterate
do e=1 for pegs; if ?('E') then iterate
do f=1 for pegs; if ?('F') then iterate
do g=1 for pegs; if ?('G') then iterate
do h=1 for pegs; if ?('H') then iterate
say _ 'a='a _ "b="||b _ 'c='c _ "d="d _ 'e='e _ "f="f _ 'g='g _ "h="h
cnt= cnt + 1; if cnt==limit then leave a
end /*h*/
end /*g*/
end /*f*/
end /*e*/
end /*d*/
end /*c*/
end /*b*/
end /*a*/
say /*display a blank line to the terminal.*/
s= left('s', cnt\==1) /*handle the case of plurals (or not).*/
say 'found ' cnt " solution"s'.' /*display the number of solutions found*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
?: parse arg node; nn= value(node)
nH= nn+1
do cn=c2d('A') to c2d(node)-1; if value( d2c(cn) )==nn then return 1
end /*cn*/ /* [↑] see if there any are duplicates.*/
nL= nn-1
do ch=1 for !.node.0 /* [↓] see if there any ¬= ±1 values.*/
$= !.node.ch; fn= value($) /*the node name and its current peg #.*/
if nL==fn | nH==fn then return 1 /*if ≡ ±1, then the node can't be used.*/
end /*ch*/ /* [↑] looking for suitable number. */
return 0 /*the subroutine arg value passed is OK.*/ |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted.
Make your example work with the following list of values and set of indices:
Values: [7, 6, 5, 4, 3, 2, 1, 0]
Indices: {6, 1, 7}
Where the correct result would be:
[7, 0, 5, 4, 3, 2, 1, 6].
In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead.
The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given.
Cf.
Order disjoint list items
| #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:=0 to num-1 do
begin
for j:=i+1 to num-1 do
begin
if n=1 then if index[j]<index[i] then swap(index[j],index[i]);
if n=2 then if arr[index[j]]<arr[index[i]] then swap(arr[index[j]],arr[index[i]]);
end;
end;
end;
end;
var
i:integer;
arr :array[0 .. 7] of integer =(7, 6, 5, 4, 3, 2, 1, 0);
index:array[0 .. 2] of integer =(6, 1, 7);
begin
writeln('Before');
for i:=0 to 7 do write(arr[i],' ');
writeln;
d_sort(index,arr);
writeln('After');
for i:=0 to 7 do write(arr[i],' ');
writeln;
readln;
end.
|
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
Use a sorting facility provided by the language/library, combined with your own callback comparison function.
Note: Lexicographic order is case-insensitive.
| #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;
NOTE: The definition of compare can also be written thus:
define compare(s1, s2);
lvars
l1 = length(s1),
l2 = length(s2);
l1 > l2 or (l1 == l2 and alphabefore(uppertolower(s1), uppertolower(s2)))
enddefine; |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
Use a sorting facility provided by the language/library, combined with your own callback comparison function.
Note: Lexicographic order is case-insensitive.
| #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
'if we get here, they're of equal length,
'so now we're doing a "normal" string comparison
FUNCTION = -1
ELSEIF UCASE$(p2) > UCASE$(p1) THEN
FUNCTION = 1
ELSE
FUNCTION = 0
END IF
END FUNCTION
FUNCTION PBMAIN()
DIM x(7) AS STRING
ARRAY ASSIGN x() = "Here", "are", "some", "sample", "strings", "to", "be", "sorted"
'pb's built-in sorting; "USING" tells it to use our custom comparator
ARRAY SORT x(), USING Sorter()
END FUNCTION |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #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];
arr[i + 1] = arr[i];
arr[i] = temp;
madeChanges = true;
}
}
} while (madeChanges);
}
}
class Main {
static function main() {
var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0];
var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3,
3.5, 0.0, -4.1, -9.5];
var stringArray = ['We', 'hold', 'these', 'truths', 'to',
'be', 'self-evident', 'that', 'all',
'men', 'are', 'created', 'equal'];
Sys.println('Unsorted Integers: ' + integerArray);
BubbleSort.sort(integerArray);
Sys.println('Sorted Integers: ' + integerArray);
Sys.println('Unsorted Floats: ' + floatArray);
BubbleSort.sort(floatArray);
Sys.println('Sorted Floats: ' + floatArray);
Sys.println('Unsorted Strings: ' + stringArray);
BubbleSort.sort(stringArray);
Sys.println('Sorted Strings: ' + stringArray);
}
} |
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort | Sorting algorithms/Gnome sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort.
The pseudocode for the algorithm is:
function gnomeSort(a[0..size-1])
i := 1
j := 2
while i < size do
if a[i-1] <= a[i] then
// for descending sort, use >= for comparison
i := j
j := j + 1
else
swap a[i-1] and a[i]
i := i - 1
if i = 0 then
i := j
j := j + 1
endif
endif
done
Task
Implement the Gnome sort in your language to sort an array (or list) of numbers.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The cocktail shaker sort is an improvement on the Bubble Sort.
The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia):
function cocktailSort( A : list of sortable items )
do
swapped := false
for each i in 0 to length( A ) - 2 do
if A[ i ] > A[ i+1 ] then // test whether the two
// elements are in the wrong
// order
swap( A[ i ], A[ i+1 ] ) // let the two elements
// change places
swapped := true;
if swapped = false then
// we can exit the outer loop here if no swaps occurred.
break do-while loop;
swapped := false
for each i in length( A ) - 2 down to 0 do
if A[ i ] > A[ i+1 ] then
swap( A[ i ], A[ i+1 ] )
swapped := true;
while swapped; // if no elements have been swapped,
// then the list is sorted
Related task
cocktail sort with shifting bounds
| #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 set false. */
t = A(i); A(i) = A(i+1); A(i+1) = t;
end;
end;
end;
end cocktail; |
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
OEIS A019546: Primes whose digits are primes.
https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
| #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 = until ]
drop ] is spds ( n --> [ )
100 spds
25 split swap echo
cr cr
-1 peek echo |
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
OEIS A019546: Primes whose digits are primes.
https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
| #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:';
printf "%22s: %s\n", ordinal(1+$_).tclc, comma $spds[$_] for flat ^25, 99, 999, 9999, 99999; |
http://rosettacode.org/wiki/Snake | Snake |
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Snake is a game where the player maneuvers a line which grows in length every time the snake reaches a food source.
Task
Implement a variant of the Snake game, in any interactive environment, in which a sole player attempts to eat items by running into them with the head of the snake.
Each item eaten makes the snake longer and a new item is randomly generated somewhere else on the plane.
The game ends when the snake attempts to eat himself.
| #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() {
fill( 130, 190, 0 );
var pos, i = this.posArray.length - 1, l = this.length;
while( true ){
pos = this.posArray[i--];
rect( pos.x * block, pos.y * block, block, block );
if( --l == 0 ) break;
}
}
this.eat = function( frut ) {
var b = this.pos.x == frut.x && this.pos.y == frut.y;
if( b ) this.length++;
return b;
}
this.overlap = function() {
var len = this.posArray.length - 1;
for( var i = len; i > len - this.length; i-- ) {
tp = this.posArray[i];
if( tp.x === this.pos.x && tp.y === this.pos.y ) return true;
}
return false;
}
this.update = function() {
if( !this.alive ) return;
switch( this.dir ) {
case L:
this.pos.x--; if( this.pos.x < 1 ) this.pos.x = wid - 2;
break;
case R:
this.pos.x++; if( this.pos.x > wid - 2 ) this.pos.x = 1;
break;
case U:
this.pos.y--; if( this.pos.y < 1 ) this.pos.y = hei - 2;
break;
case D:
this.pos.y++; if( this.pos.y > hei - 2 ) this.pos.y = 1;
break;
}
if( this.overlap() ) { this.alive = false; } else {
this.posArray.push( createVector( this.pos.x, this.pos.y ) );
if( this.posArray.length > 5000 ) { this.posArray.splice( 0, 1 ); }
}
}
}
function Fruit() {
this.fruitTime = true;
this.pos = createVector();
this.draw = function() {
fill( 200, 50, 20 );
rect( this.pos.x * block, this.pos.y * block, block, block );
}
this.setFruit = function() {
this.pos.x = floor( random( 1, wid - 1 ) );
this.pos.y = floor( random( 1, hei - 1 ) );
this.fruitTime = false;
}
}
function setup() {
createCanvas( block * wid, block * hei );
noStroke(); frameRate( frameR );
snake = new Snake();fruit = new Fruit();
}
function keyPressed() {
switch( keyCode ) {
case LEFT_ARROW: snake.dir = L; break;
case RIGHT_ARROW: snake.dir = R; break;
case UP_ARROW: snake.dir = U; break;
case DOWN_ARROW: snake.dir = D;
}
}
function draw() {
background( color( 0, 0x22, 0 ) );
fill( 20, 50, 120 );
for( var i = 0; i < wid; i++ ) {
rect( i * block, 0, block, block );
rect( i * block, height - block, block, block );
}
for( var i = 1; i < hei - 1; i++ ) {
rect( 1, i * block, block, block );
rect( width - block, i * block, block, block );
}
if( fruit.fruitTime ) {
fruit.setFruit();
frameR += .2;
frameRate( frameR );
}
fruit.draw();
snake.update();
if( snake.eat( fruit.pos ) ) {
fruit.fruitTime = true;
}
snake.draw();
fill( 200 );
textStyle( BOLD ); textAlign( RIGHT ); textSize( 120 );
text( ""+( snake.length - 1 ), 690, 440 );
if( !snake.alive ) text( "THE END", 630, 250 );
}
|
http://rosettacode.org/wiki/Smith_numbers | Smith numbers | Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers are also known as joke numbers.
Example
Using the number 166
Find the prime factors of 166 which are: 2 x 83
Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13
Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13
Therefore, the number 166 is a Smith number.
Task
Write a program to find all Smith numbers below 10000.
See also
from Wikipedia: [Smith number].
from MathWorld: [Smith number].
from OEIS A6753: [OEIS sequence A6753].
from OEIS A104170: [Number of Smith numbers below 10^n].
from The Prime pages: [Smith numbers].
| #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 candidate)
candidate
(cons candidate acc))
:else (recur n (inc candidate) acc))))
(defn sum-digits [n]
(reduce + (map #(- (int %) (int \0)) (str n))))
(defn smith-number? [n]
(and (not (prime? n))
(= (sum-digits n)
(sum-digits (clojure.string/join "" (prime-factors n))))))
(filter smith-number? (range 1 10000)) |
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle | Solve a Hidato puzzle | The task is to write a program which solves Hidato (aka Hidoku) puzzles.
The rules are:
You are given a grid with some numbers placed in it. The other squares in the grid will be blank.
The grid is not necessarily rectangular.
The grid may have holes in it.
The grid is always connected.
The number “1” is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique.
It may be assumed that the difference between numbers present on the grid is not greater than lucky 13.
The aim is to place a natural number in each blank square so that in the sequence of numbered squares from “1” upwards, each square is in the wp:Moore neighborhood of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints).
Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order.
A square may only contain one number.
In a proper Hidato puzzle, the solution is unique.
For example the following problem
has the following solution, with path marked on it:
Related tasks
A* search algorithm
N-queens problem
Solve a Holy Knight's tour
Solve a Knight's tour
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle;
| #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 _ . . .",
"_ _ _ 21 _ _ . .",
"_ 26 _ 13 40 11 . .",
"27 _ _ _ 9 _ 1 .",
". . _ _ 18 _ _ .",
". . . . _ 7 _ _",
". . . . . . 5 _"};
setup(input);
printBoard();
System.out.println("\nFound:");
solve(start[0], start[1], 1, 0);
printBoard();
}
private static void setup(String[] input) {
/* This task is not about input validation, so
we're going to trust the input to be valid */
String[][] puzzle = new String[input.length][];
for (int i = 0; i < input.length; i++)
puzzle[i] = input[i].split(" ");
int nCols = puzzle[0].length;
int nRows = puzzle.length;
List<Integer> list = new ArrayList<>(nRows * nCols);
board = new int[nRows + 2][nCols + 2];
for (int[] row : board)
for (int c = 0; c < nCols + 2; c++)
row[c] = -1;
for (int r = 0; r < nRows; r++) {
String[] row = puzzle[r];
for (int c = 0; c < nCols; c++) {
String cell = row[c];
switch (cell) {
case "_":
board[r + 1][c + 1] = 0;
break;
case ".":
break;
default:
int val = Integer.parseInt(cell);
board[r + 1][c + 1] = val;
list.add(val);
if (val == 1)
start = new int[]{r + 1, c + 1};
}
}
}
Collections.sort(list);
given = new int[list.size()];
for (int i = 0; i < given.length; i++)
given[i] = list.get(i);
}
private static boolean solve(int r, int c, int n, int next) {
if (n > given[given.length - 1])
return true;
if (board[r][c] != 0 && board[r][c] != n)
return false;
if (board[r][c] == 0 && given[next] == n)
return false;
int back = board[r][c];
if (back == n)
next++;
board[r][c] = n;
for (int i = -1; i < 2; i++)
for (int j = -1; j < 2; j++)
if (solve(r + i, c + j, n + 1, next))
return true;
board[r][c] = back;
return false;
}
private static void printBoard() {
for (int[] row : board) {
for (int c : row) {
if (c == -1)
System.out.print(" . ");
else
System.out.printf(c > 0 ? "%2d " : "__ ", c);
}
System.out.println();
}
}
} |
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 square
# is a wall
@ is the player
$ is a box
. is a goal
+ is the player on a goal
* is a box on a goal
#######
# #
# #
#. # #
#. $$ #
#.$$ #
#.# @#
#######
Sokoban solutions are usually stored in the LURD format, where lowercase l, u, r and d represent a move in that (left, up, right, down) direction and capital LURD represents a push.
Please state if you use some other format for either the input or output, and why.
For more information, see the Sokoban wiki.
| #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
for (r in 0...board.count) {
for (c in 0..._nCols) {
var ch = board[r][c]
_destBoard = _destBoard + ((ch != "$" && ch != "@") ? ch : " ")
_currBoard = _currBoard + ((ch != ".") ? ch : " ")
if (ch == "@") {
_playerX = c
_playerY = r
}
}
}
}
move(x, y, dx, dy, trialBoard) {
var newPlayerPos = (y + dy) * _nCols + x + dx
if (trialBoard[newPlayerPos] != " ") return ""
var trial = trialBoard.toList
trial[y * _nCols + x] = " "
trial[newPlayerPos] = "@"
return trial.join()
}
push(x, y, dx, dy, trialBoard) {
var newBoxPos = (y + 2 * dy) * _nCols + x + 2 * dx
if (trialBoard[newBoxPos] != " ") return ""
var trial = trialBoard.toList
trial[y * _nCols + x] = " "
trial[(y + dy) * _nCols + x + dx] = "@"
trial[newBoxPos] = "$"
return trial.join("")
}
isSolved(trialBoard) {
for (i in 0...trialBoard.count) {
if ((_destBoard[i] == ".") != (trialBoard[i] == "$")) return false
}
return true
}
solve() {
var dirLabels = [ ["u", "U"], ["r", "R"], ["d", "D"], ["l", "L"] ]
var dirs = [ [0, -1], [1, 0], [0, 1], [-1, 0] ]
var history = Set.new()
history.add(_currBoard)
var open = DLinkedList.new()
open.add(Board.new(_currBoard, "", _playerX, _playerY))
while (!open.isEmpty) {
var b = open.removeAt(0)
for (i in 0...dirs.count) {
var trial = b.cur
var dx = dirs[i][0]
var dy = dirs[i][1]
// are we standing next to a box ?
if (trial[(b.y + dy) * _nCols + b.x + dx] == "$") {
// can we push it ?
trial = push(b.x, b.y, dx, dy, trial)
if (!trial.isEmpty) {
// or did we already try this one ?
if (!history.contains(trial)) {
var newSol = b.sol + dirLabels[i][1]
if (isSolved(trial)) return newSol
open.add(Board.new(trial, newSol, b.x + dx, b.y + dy))
history.add(trial)
}
}
} else { // otherwise try changing position
trial = move(b.x, b.y, dx, dy, trial)
if (!trial.isEmpty && !history.contains(trial)) {
var newSol = b.sol + dirLabels[i][0]
open.add(Board.new(trial, newSol, b.x + dx, b.y + dy))
history.add(trial)
}
}
}
}
return "No solution"
}
}
var level = [
"#######",
"# #",
"# #",
"#. # #",
"#. $$ #",
"#.$$ #",
"#.# @#",
"#######"
]
System.print(level.join("\n"))
System.print()
System.print(Sokoban.new(level).solve()) |
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 to such problems. At least demonstrate your program by solving the following:
Example
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
Note that the zeros represent the available squares, not the pennies.
Extra credit is available for other interesting examples.
Related tasks
A* search algorithm
Knight's tour
N-queens problem
Solve a Hidato puzzle
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Sort an array of composite structures by a key.
For example, if you define a composite structure that presents a name-value pair (in pseudo-code):
Define structure pair such that:
name as a string
value as a string
and an array of such pairs:
x: array of pairs
then define a sort routine that sorts the array x by the key name.
This task can always be accomplished with Sorting Using a Custom Comparator.
If your language is not listed here, please see the other article.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Sort an array of composite structures by a key.
For example, if you define a composite structure that presents a name-value pair (in pseudo-code):
Define structure pair such that:
name as a string
value as a string
and an array of such pairs:
x: array of pairs
then define a sort routine that sorts the array x by the key name.
This task can always be accomplished with Sorting Using a Custom Comparator.
If your language is not listed here, please see the other article.
| #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 are also given eight pegs numbered 1-to-8.
Objective
Place the eight pegs in the holes so that the (absolute) difference between any two numbers connected by any line is greater than one.
Example
In this attempt:
4 7
/│\ /│\
/ │ X │ \
/ │/ \│ \
8───1───6───2
\ │\ /│ /
\ │ X │ /
\│/ \│/
3 5
Note that 7 and 6 are connected and have a difference of 1, so it is not a solution.
Task
Produce and show here one solution to the puzzle.
Related tasks
A* search algorithm
Solve a Holy Knight's tour
Knight's tour
N-queens problem
Solve a Hidato puzzle
Solve a Holy Knight's tour
Solve a Hopido puzzle
Solve a Numbrix puzzle
4-rings or 4-squares puzzle
See also
No Connection Puzzle (youtube).
| #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]][B[1]].adj = [A,C,G,H]
g.board[C[0]][C[1]].adj = [B,E,F,H]
g.board[D[0]][D[1]].adj = [F]
g.board[E[0]][E[1]].adj = [C]
g.board[F[0]][F[1]].adj = [A,C,D,G]
g.board[G[0]][G[1]].adj = [A,B,F,H]
g.board[H[0]][H[1]].adj = [A,B,C,G]
g.solve
|
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted.
Make your example work with the following list of values and set of indices:
Values: [7, 6, 5, 4, 3, 2, 1, 0]
Indices: {6, 1, 7}
Where the correct result would be:
[7, 0, 5, 4, 3, 2, 1, 6].
In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead.
The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given.
Cf.
Order disjoint list items
| #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 ) ;
print "[@values]\n" ; |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
Use a sorting facility provided by the language/library, combined with your own callback comparison function.
Note: Lexicographic order is case-insensitive.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
Use a sorting facility provided by the language/library, combined with your own callback comparison function.
Note: Lexicographic order is case-insensitive.
| #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 = '>'
; L1 > L2 -> Comp = '<'
; compare(Comp, W1, W2)).
my_write(W) :-
format('~s ', [W]).
|
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort.
The pseudocode for the algorithm is:
function gnomeSort(a[0..size-1])
i := 1
j := 2
while i < size do
if a[i-1] <= a[i] then
// for descending sort, use >= for comparison
i := j
j := j + 1
else
swap a[i-1] and a[i]
i := i - 1
if i = 0 then
i := j
j := j + 1
endif
endif
done
Task
Implement the Gnome sort in your language to sort an array (or list) of numbers.
| #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 <- j+1
}
}
}
x
}
gnomesort(c(4, 65, 2, -31, 0, 99, 83, 782, 1)) # -31 0 1 2 4 65 83 99 782 |
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort | Sorting algorithms/Cocktail sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The cocktail shaker sort is an improvement on the Bubble Sort.
The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia):
function cocktailSort( A : list of sortable items )
do
swapped := false
for each i in 0 to length( A ) - 2 do
if A[ i ] > A[ i+1 ] then // test whether the two
// elements are in the wrong
// order
swap( A[ i ], A[ i+1 ] ) // let the two elements
// change places
swapped := true;
if swapped = false then
// we can exit the outer loop here if no swaps occurred.
break do-while loop;
swapped := false
for each i in length( A ) - 2 down to 0 do
if A[ i ] > A[ i+1 ] then
swap( A[ i ], A[ i+1 ] )
swapped := true;
while swapped; // if no elements have been swapped,
// then the list is sorted
Related task
cocktail sort with shifting bounds
| #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 $hasChanged) {
break outer
}
$hasChanged = $false
for ($i = $l; $i -gt $m; $i--) {
if ($a[$i-1] -gt $a[$i]) {
$a[$i-1], $a[$i] = $a[$i], $a[$i-1]
$hasChanged = $true
}
}
$m++
}
}
$a
}
$l = 10; CocktailSort ( 1..$l | ForEach-Object { $Rand = New-Object Random }{ $Rand.Next( -( $l - 1 ), $l - 1 ) } ) |
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 virtually no difference
between opening files on disk and creating TCP-connections
or endpoints, so we go through the usual sequence of GTJFN
(= get file-handle), OPENF (open file), finally followed
by CLOSF (close file).
!
SEARCH MONSYM,MACSYM ;Load symbolic names for syscalls.
.REQUIRE SYS:MACREL
STDAC. ;Define standard register names.
JFN: BLOCK 1 ;File handle for TCP connection.
TCPFN: ASCIZ /TCP:256/ ;TCP "filename"
STR: ASCIZ /Hello World!/ ;String to send.
STRLEN= <.-STR>*5 ;Length of string.
GO:: RESET% ;Initialize process.
;; Get a file-handle (JFN) for the TCP-connection:
MOVX T1,GJ%SHT ;Do "short" GTJFN% call.
HRROI T2,TCPFN ;TCP "filename" into T2.
GTJFN% ;Get file-handle.
ERJMPS ERROR ; Handle errors.
MOVEM T1,JFN ;Store JFN we got.
;; Open the "file":
HRRZ T1,JFN ;File-handle without flags into T1.
MOVX T2,FLD(8,OF%BSZ)!OF%RD!OF%WR ;8bit bytes, read+write.
OPENF% ;Open file.
ERJMPS ERROR ; Handle errors.
;; Write the string.
MOVE T1,JFN ;File-handle into T1.
HRROI T2,STR ;String-pointer into T2.
MOVEI T3,STRLEN ;Length of string into T3.
SOUT% ;Write string.
ERJMPS ERROR ; Handle errors.
;; Close file.
HRRZ T1,JFN ;Get file-handle into T1.
CLOSF% ;Close file.
ERJMPS ERROR ; Handle errors.
;; End program.
RESET% ;Reset, to release JFN.
HALTF% ;Halt program.
JRST GO ;Allow for continue-command.
;;
;; ERROR: Print standardized error-message by means of ERSTR.
;; This is similar to perror() in C.
;;
ERROR: MOVEI T1,.PRIOU ;Print on standard output.
MOVE T2,[.FHSLF,,-1] ;Own process, last error.
SETZ T3 ;No length-limit on error msg.
ERSTR% ;Print error-message.
JFCL ; Ignore errors from ERSTR%.
JFCL ; Dito.
RESET% ;Reset, to release JFN.
HALTF% ;Halt program.
JRST GO ;Allow for continue-command.
END GO
|
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
OEIS A019546: Primes whose digits are primes.
https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
| #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 /* " " " " " " */
say '═══listing the first' n "SPDS primes═══"
call spds n
do i=1 for words(q)+1; y=word(q, i); if y=='' | y=="," then iterate
say
say '═══listing the last of ' y "SPDS primes═══"
call spds -y
end /*i*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
spds: parse arg x 1 ox; x= abs(x) /*obtain the limit to be used for list.*/
c= 0 /*C number of SPDS primes found so far*/
#= 0 /*# number of primes found so far*/
do j=1 by 2 while c<x; z= j /*start: 1st even prime, then use odd. */
if z==1 then z= 2 /*handle the even prime (special case) */
/* [↓] divide by the primes. ___ */
do k=2 to # while k*k<=z /*divide Z with all primes ≤ √ Z */
if z//@.k==0 then iterate j /*÷ by prev. prime? ¬prime ___ */
end /*j*/ /* [↑] only divide up to √ Z */
#= # + 1; @.#= z /*bump the prime count; assign prime #*/
if verify(z, 2357)>0 then iterate j /*Digits ¬prime? Then skip this prime.*/
c= c + 1 /*bump the number of SPDS primes found.*/
if ox<0 then iterate /*don't display it, display the last #.*/
say right(z, 21) /*maybe display this prime ──► terminal*/
end /*j*/ /* [↑] only display N number of primes*/
if ox<0 then say right(z, 21) /*display one (the last) SPDS prime. */
return |
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
OEIS A019546: Primes whose digits are primes.
https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
| #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
next
if flag = len(nStr)
num = num + 1
if num < limit
see "" + n + " "
ok
if num = limit100
see nl + nl + "100th Smarandache prime: " + n + nl
ok
ok
next
|
http://rosettacode.org/wiki/Snake | Snake |
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Snake is a game where the player maneuvers a line which grows in length every time the snake reaches a food source.
Task
Implement a variant of the Snake game, in any interactive environment, in which a sole player attempts to eat items by running into them with the head of the snake.
Each item eaten makes the snake longer and a new item is randomly generated somewhere else on the plane.
The game ends when the snake attempts to eat himself.
| #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() {
fill( 130, 190, 0 );
var pos, i = this.posArray.length - 1, l = this.length;
while( true ){
pos = this.posArray[i--];
rect( pos.x * block, pos.y * block, block, block );
if( --l == 0 ) break;
}
}
this.eat = function( frut ) {
var b = this.pos.x == frut.x && this.pos.y == frut.y;
if( b ) this.length++;
return b;
}
this.overlap = function() {
var len = this.posArray.length - 1;
for( var i = len; i > len - this.length; i-- ) {
tp = this.posArray[i];
if( tp.x === this.pos.x && tp.y === this.pos.y ) return true;
}
return false;
}
this.update = function() {
if( !this.alive ) return;
switch( this.dir ) {
case L:
this.pos.x--; if( this.pos.x < 1 ) this.pos.x = wid - 2;
break;
case R:
this.pos.x++; if( this.pos.x > wid - 2 ) this.pos.x = 1;
break;
case U:
this.pos.y--; if( this.pos.y < 1 ) this.pos.y = hei - 2;
break;
case D:
this.pos.y++; if( this.pos.y > hei - 2 ) this.pos.y = 1;
break;
}
if( this.overlap() ) { this.alive = false; } else {
this.posArray.push( createVector( this.pos.x, this.pos.y ) );
if( this.posArray.length > 5000 ) { this.posArray.splice( 0, 1 ); }
}
}
}
function Fruit() {
this.fruitTime = true;
this.pos = createVector();
this.draw = function() {
fill( 200, 50, 20 );
rect( this.pos.x * block, this.pos.y * block, block, block );
}
this.setFruit = function() {
this.pos.x = floor( random( 1, wid - 1 ) );
this.pos.y = floor( random( 1, hei - 1 ) );
this.fruitTime = false;
}
}
function setup() {
createCanvas( block * wid, block * hei );
noStroke(); frameRate( frameR );
snake = new Snake();fruit = new Fruit();
}
function keyPressed() {
switch( keyCode ) {
case LEFT_ARROW: snake.dir = L; break;
case RIGHT_ARROW: snake.dir = R; break;
case UP_ARROW: snake.dir = U; break;
case DOWN_ARROW: snake.dir = D;
}
}
function draw() {
background( color( 0, 0x22, 0 ) );
fill( 20, 50, 120 );
for( var i = 0; i < wid; i++ ) {
rect( i * block, 0, block, block );
rect( i * block, height - block, block, block );
}
for( var i = 1; i < hei - 1; i++ ) {
rect( 1, i * block, block, block );
rect( width - block, i * block, block, block );
}
if( fruit.fruitTime ) {
fruit.setFruit();
frameR += .2;
frameRate( frameR );
}
fruit.draw();
snake.update();
if( snake.eat( fruit.pos ) ) {
fruit.fruitTime = true;
}
snake.draw();
fill( 200 );
textStyle( BOLD ); textAlign( RIGHT ); textSize( 120 );
text( ""+( snake.length - 1 ), 690, 440 );
if( !snake.alive ) text( "THE END", 630, 250 );
}
|
http://rosettacode.org/wiki/Smith_numbers | Smith numbers | Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers are also known as joke numbers.
Example
Using the number 166
Find the prime factors of 166 which are: 2 x 83
Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13
Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13
Therefore, the number 166 is a Smith number.
Task
Write a program to find all Smith numbers below 10000.
See also
from Wikipedia: [Smith number].
from MathWorld: [Smith number].
from OEIS A6753: [OEIS sequence A6753].
from OEIS A104170: [Number of Smith numbers below 10^n].
from The Prime pages: [Smith numbers].
| #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 yield(2) n := n/2 end
% Next try odd factors
fac: int := 3
while fac <= n do
while n // fac = 0 do
yield(fac)
n := n/fac
end
fac := fac + 2
end
end prime_factors
% See if a number is a Smith number
smith = proc (n: int) returns (bool)
dsum: int := 0
fac_dsum: int := 0
% Find the sum of the digits
for d: int in digits(n) do dsum := dsum + d end
% Find the sum of the digits of all factors
nfac: int := 0
for fac: int in prime_factors(n) do
nfac := nfac + 1
for d: int in digits(fac) do fac_dsum := fac_dsum + d end
end
% The number is a Smith number if these two are equal,
% and the number is not prime (has more than one factor)
return(fac_dsum = dsum cand nfac > 1)
end smith
% Yield all Smith numbers up to a limit
smiths = iter (max: int) yields (int)
for i: int in int$from_to(1, max-1) do
if smith(i) then yield(i) end
end
end smiths
% Display all Smith numbers below 10,000
start_up = proc ()
po: stream := stream$primary_output()
count: int := 0
for s: int in smiths(10000) do
stream$putright(po, int$unparse(s), 5)
count := count + 1
if count // 16 = 0 then stream$putl(po, "") end
end
stream$putl(po, "\nFound " || int$unparse(count) || " Smith numbers.")
end start_up |
http://rosettacode.org/wiki/Smith_numbers | Smith numbers | Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers are also known as joke numbers.
Example
Using the number 166
Find the prime factors of 166 which are: 2 x 83
Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13
Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13
Therefore, the number 166 is a Smith number.
Task
Write a program to find all Smith numbers below 10000.
See also
from Wikipedia: [Smith number].
from MathWorld: [Smith number].
from OEIS A6753: [OEIS sequence A6753].
from OEIS A104170: [Number of Smith numbers below 10^n].
from The Prime pages: [Smith numbers].
| #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 loop
print_char(' ');
len := len + 1;
end loop;
print(buf);
end sub;
# Find the sum of the digits of a number
sub digit_sum(n: N): (sum: N) is
sum := 0;
while n > 0 loop
sum := sum + n % 10;
n := n / 10;
end loop;
end sub;
# Factorize a number, write the factors into the buffer,
# return the amount of factors.
sub factorize(n: N, buf: [N]): (count: N) is
count := 0;
# Take care of the factors of 2 first
while n>0 and n & 1 == 0 loop
n := n >> 1;
count := count + 1;
[buf] := 2;
buf := @next buf;
end loop;
# Then do the odd factors
var fac: N := 3;
while n >= fac loop
while n % fac == 0 loop
n := n / fac;
count := count + 1;
[buf] := fac;
buf := @next buf;
end loop;
fac := fac + 2;
end loop;
end sub;
# See if a number is a Smith number
sub smith(n: N): (rslt: uint8) is
rslt := 0;
var facs: N[16];
var n_facs := factorize(n, &facs[0]) as @indexof facs;
if n_facs > 1 then
# Only composite numbers are Smith numbers
var dsum := digit_sum(n);
var facsum: N := 0;
var i: @indexof facs := 0;
while i < n_facs loop
facsum := facsum + digit_sum(facs[i]);
i := i + 1;
end loop;
if facsum == dsum then rslt := 1; end if;
end if;
end sub;
# Display all Smith numbers below 10000
var i: N := 2;
var count: N := 0;
while i < 10000 loop
if smith(i) != 0 then
count := count + 1;
print_right(i, 5);
if count & 0xF == 0 then print_nl(); end if;
end if;
i := i + 1;
end loop;
print_nl();
print("Found ");
print_i32(count as uint32);
print(" Smith numbers.\n"); |
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle | Solve a Hidato puzzle | The task is to write a program which solves Hidato (aka Hidoku) puzzles.
The rules are:
You are given a grid with some numbers placed in it. The other squares in the grid will be blank.
The grid is not necessarily rectangular.
The grid may have holes in it.
The grid is always connected.
The number “1” is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique.
It may be assumed that the difference between numbers present on the grid is not greater than lucky 13.
The aim is to place a natural number in each blank square so that in the sequence of numbered squares from “1” upwards, each square is in the wp:Moore neighborhood of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints).
Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order.
A square may only contain one number.
In a proper Hidato puzzle, the solution is unique.
For example the following problem
has the following solution, with path marked on it:
Related tasks
A* search algorithm
N-queens problem
Solve a Holy Knight's tour
Solve a Knight's tour
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle;
| #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
for (i, line) in enumerate(lines), (j, s) in enumerate(split(strip(line), r"\s+"))
c = s[1]
if c == '_' || (c == '0' && length(s) == 1)
board[i, j] = 0
maxmoves += 1
elseif c == '.'
continue
else # numeral, get 2 digits
board[i, j] = parse(Int, s)
push!(presets, board[i, j])
if board[i, j] == 1
push!(starts, CartesianIndex(i, j))
end
maxmoves += 1
end
end
board, maxmoves, sort!(presets), length(starts) == 1 ? starts : findall(x -> x == 0, board)
end
function hidatosolve(board, maxmoves, movematrix, fixed, row, col, sought)
if sought > maxmoves
return true
elseif (0 != board[row, col] != sought) || (board[row, col] == 0 && sought in fixed)
return false
end
backnum = board[row, col] == sought ? sought : 0
board[row, col] = sought # try board with this cell set to next number
for move in movematrix
i, j = row + move[1], col + move[2]
if (0 < i <= size(board)[1]) && (0 < j <= size(board)[2]) &&
hidatosolve(board, maxmoves, movematrix, fixed, i, j, sought + 1)
return true
end
end
board[row, col] = backnum # return board to original state
false
end
function printboard(board, emptysquare= "__ ", blocked = " ")
d = Dict(-1 => blocked, 0 => emptysquare, -2 => "\n")
map(x -> d[x] = rpad(lpad(string(x), 2), 3), 1:maximum(board))
println(join([d[i] for i in hcat(board, fill(-2, size(board)[1]))'], ""))
end
end # module
|
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 to such problems. At least demonstrate your program by solving the following:
Example
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
Note that the zeros represent the available squares, not the pennies.
Extra credit is available for other interesting examples.
Related tasks
A* search algorithm
Knight's tour
N-queens problem
Solve a Hidato puzzle
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #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]
}
incr limit [expr {$cell>=0}]
}
}
if {![info exist start]} {
return -code error "no starting position found"
}
}
method moves {} {
return {
-1 -2 1 -2
-2 -1 2 -1
-2 1 2 1
-1 2 1 2
}
}
method Moves {g r c} {
set valid {}
foreach {dr dc} [my moves] {
set R [expr {$r + $dr}]
set C [expr {$c + $dc}]
if {[lindex $g $R $C] == 0} {
lappend valid $R $C
}
}
return $valid
}
method Solve {g r c v} {
lset g $r $c [incr v]
if {$v >= $limit} {return $g}
foreach {r c} [my Moves $g $r $c] {
return [my Solve $g $r $c $v]
}
return -code continue
}
method solve {} {
while {[incr i]==1} {
set grid [my Solve $grid {*}$start 0]
return
}
return -code error "solution not possible"
}
method solution {} {return $grid}
}
proc parsePuzzle {str} {
foreach line [split $str "\n"] {
if {[string trim $line] eq ""} continue
lappend rows [lmap {- c} [regexp -all -inline {(.)\s?} $line] {
string map {" " -1} $c
}]
}
set len [tcl::mathfunc::max {*}[lmap r $rows {llength $r}]]
for {set i 0} {$i < [llength $rows]} {incr i} {
while {[llength [lindex $rows $i]] < $len} {
lset rows $i end+1 -1
}
}
return $rows
}
proc showPuzzle {grid name} {
foreach row $grid {foreach cell $row {incr c [expr {$cell>=0}]}}
set len [string length $c]
set u [string repeat "_" $len]
puts "$name with $c cells"
foreach row $grid {
puts [format " %s" [join [lmap c $row {
format "%*s" $len [if {$c==-1} list elseif {$c==0} {set u} {set c}]
}]]]
}
}
set puzzle [parsePuzzle {
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
}]
showPuzzle $puzzle "Input"
HKTSolver create hkt $puzzle
hkt solve
showPuzzle [hkt solution] "Output" |
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Sort an array of composite structures by a key.
For example, if you define a composite structure that presents a name-value pair (in pseudo-code):
Define structure pair such that:
name as a string
value as a string
and an array of such pairs:
x: array of pairs
then define a sort routine that sorts the array x by the key name.
This task can always be accomplished with Sorting Using a Custom Comparator.
If your language is not listed here, please see the other article.
| #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"),
Pair("coffee", "stimulating"),
Pair("book", "interesting")]
println("The original list: \n - ", join(lst, "\n - "))
sort!(lst; by=first)
println("\nThe list, sorted by name: \n - ", join(lst, "\n - "))
sort!(lst; by=last)
println("\nThe list, sorted by value: \n - ", join(lst, "\n - ")) |
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Sort an array of composite structures by a key.
For example, if you define a composite structure that presents a name-value pair (in pseudo-code):
Define structure pair such that:
name as a string
value as a string
and an array of such pairs:
x: array of pairs
then define a sort routine that sorts the array x by the key name.
This task can always be accomplished with Sorting Using a Custom Comparator.
If your language is not listed here, please see the other article.
| #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"),
Employee("Joanna", "Director"),
Employee("Henry", "Admin"),
Employee("Tim", "Sales"),
Employee("Juan", "Admin")
)
employees.sort()
for ((name, category) in employees) println("${name.padEnd(6)} : $category")
} |
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle | Solve the no connection puzzle | You are given a box with eight holes labelled A-to-H, connected by fifteen straight lines in the pattern as shown below:
A B
/│\ /│\
/ │ X │ \
/ │/ \│ \
C───D───E───F
\ │\ /│ /
\ │ X │ /
\│/ \│/
G H
You are also given eight pegs numbered 1-to-8.
Objective
Place the eight pegs in the holes so that the (absolute) difference between any two numbers connected by any line is greater than one.
Example
In this attempt:
4 7
/│\ /│\
/ │ X │ \
/ │/ \│ \
8───1───6───2
\ │\ /│ /
\ │ X │ /
\│/ \│/
3 5
Note that 7 and 6 are connected and have a difference of 1, so it is not a solution.
Task
Produce and show here one solution to the puzzle.
Related tasks
A* search algorithm
Solve a Holy Knight's tour
Knight's tour
N-queens problem
Solve a Hidato puzzle
Solve a Holy Knight's tour
Solve a Hopido puzzle
Solve a Numbrix puzzle
4-rings or 4-squares puzzle
See also
No Connection Puzzle (youtube).
| #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).toList) #:: genRandom
private def notSolved(links: Seq[Seq[Int]], pegs: Seq[Int]): Boolean =
links.indices.forall(
i => !links(i).forall(peg => math.abs(pegs(i) - peg) == 1))
private def printResult(pegs: Seq[Int]) = {
println(f"${pegs(0)}%3d${pegs(1)}%2d")
println(f"${pegs(2)}%1d${pegs(3)}%2d${pegs(4)}%2d${pegs(5)}%2d")
println(f"${pegs(6)}%3d${pegs(7)}%2d")
}
printResult(genRandom.dropWhile(!notSolved(links, _)).head)
} |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted.
Make your example work with the following list of values and set of indices:
Values: [7, 6, 5, 4, 3, 2, 1, 0]
Indices: {6, 1, 7}
Where the correct result would be:
[7, 0, 5, 4, 3, 2, 1, 6].
In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead.
The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given.
Cf.
Order disjoint list items
| #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 s
end function
?disjoint_sort({7,6,5,4,3,2,1,0},{7,2,8})
|
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
Use a sorting facility provided by the language/library, combined with your own callback comparison function.
Note: Lexicographic order is case-insensitive.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #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
while \swapped := &null do # the sort
every i := 2 to *X do
if op(X[i],X[i-1]) then
X[i-1] :=: X[swapped := i]
return X
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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort.
The pseudocode for the algorithm is:
function gnomeSort(a[0..size-1])
i := 1
j := 2
while i < size do
if a[i-1] <= a[i] then
// for descending sort, use >= for comparison
i := j
j := j + 1
else
swap a[i-1] and a[i]
i := i - 1
if i = 0 then
i := j
j := j + 1
endif
endif
done
Task
Implement the Gnome sort in your language to sort an array (or list) of numbers.
| #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)) (vector-ref a i))
(loop j (add1 j))
(begin (swap (sub1 i) i)
(let ([i (sub1 i)])
(if (zero? i)
(loop j (add1 j))
(loop i j)))))))
a)
(gnome-sort1 (vector 3 2 1 4 5 6) <=)
;; a functional version, roughly like the Scheme entry
(define (gnome-sort2 l <=?)
(match l
[(list) l]
[(list x xs ...)
(let loop ([x `((,x) . ,xs)])
(match x
[`(,ps) ps]
[`((,p . ,ps) ,n . ,ns)
(loop (cond [(<=? n p) `((,n ,p . ,ps) . ,ns)]
[(null? ps) `((,n) ,p . ,ns)]
[else `(,ps ,n ,p . ,ns)]))]))]))
(gnome-sort2 '(3 2 1 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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The cocktail shaker sort is an improvement on the Bubble Sort.
The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia):
function cocktailSort( A : list of sortable items )
do
swapped := false
for each i in 0 to length( A ) - 2 do
if A[ i ] > A[ i+1 ] then // test whether the two
// elements are in the wrong
// order
swap( A[ i ], A[ i+1 ] ) // let the two elements
// change places
swapped := true;
if swapped = false then
// we can exit the outer loop here if no swaps occurred.
break do-while loop;
swapped := false
for each i in length( A ) - 2 down to 0 do
if A[ i ] > A[ i+1 ] then
swap( A[ i ], A[ i+1 ] )
swapped := true;
while swapped; // if no elements have been swapped,
// then the list is sorted
Related task
cocktail sort with shifting bounds
| #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(In, [Min|Out]) :-
ctail(fwrd, In, [], [Max|Rev], SFlag),
( SFlag=sorted->reverse([Max|Rev], [Min|Out]);
(ctail(bkwd, Rev, [Max], [Min|Tmp], SortFlag),
(SortFlag=sorted->Out=Tmp; !, cocktail(Tmp, Out)))).
test :- In = [8,9,1,3,4,2,6,5,4],
writef(' input=%w\n', [In]),
cocktail(In, R),
writef('-> %w\n', [R]).
|
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
OEIS A019546: Primes whose digits are primes.
https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
| #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 &WHEEL {
if p * p > n {
return true;
}
if n % p == 0 {
return false;
}
p += w;
}
}
}
fn next_prime_digit_number(n: u32) -> u32 {
if n == 0 {
return 2;
}
match n % 10 {
2 => n + 1,
3 | 5 => n + 2,
_ => 2 + next_prime_digit_number(n / 10) * 10,
}
}
fn smarandache_prime_digital_sequence() -> impl std::iter::Iterator<Item = u32> {
let mut n = 0;
std::iter::from_fn(move || {
loop {
n = next_prime_digit_number(n);
if is_prime(n) {
break;
}
}
Some(n)
})
}
fn main() {
let limit = 1000000000;
let mut seq = smarandache_prime_digital_sequence().take_while(|x| *x < limit);
println!("First 25 SPDS primes:");
for i in seq.by_ref().take(25) {
print!("{} ", i);
}
println!();
if let Some(p) = seq.by_ref().nth(99 - 25) {
println!("100th SPDS prime: {}", p);
}
if let Some(p) = seq.by_ref().nth(999 - 100) {
println!("1000th SPDS prime: {}", p);
}
if let Some(p) = seq.by_ref().nth(9999 - 1000) {
println!("10,000th SPDS prime: {}", p);
}
if let Some(p) = seq.last() {
println!("Largest SPDS prime less than {}: {}", limit, p);
}
} |
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
OEIS A019546: Primes whose digits are primes.
https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
| #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
end
end
seq = smarandache.take(100)
p seq.first(25)
p seq.last
|
http://rosettacode.org/wiki/Snake | Snake |
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Snake is a game where the player maneuvers a line which grows in length every time the snake reaches a food source.
Task
Implement a variant of the Snake game, in any interactive environment, in which a sole player attempts to eat items by running into them with the head of the snake.
Each item eaten makes the snake longer and a new item is randomly generated somewhere else on the plane.
The game ends when the snake attempts to eat himself.
| #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
SnakeGame(height, width, snake, food)
end
function step!(game, direction)
next_head = game.snake[1] + direction
next_head = CartesianIndex(mod.(next_head.I, Base.OneTo.((game.height, game.width)))) # allow crossing boundry
if is_valid(game, next_head)
pushfirst!(game.snake, next_head)
if next_head == game.food
length(game.snake) < game.height * game.width && init_food!(game)
else
pop!(game.snake)
end
true
else
false
end
end
is_valid(game, position) = position ∉ game.snake
function init_food!(game)
p = rand(CartesianIndices((game.height, game.width)))
while !is_valid(game, p)
p = rand(CartesianIndices((game.height, game.width)))
end
game.food = p
end
function play(;n=10,t=0.5)
game = Node(SnakeGame(;width=n,height=n))
scene = Scene(resolution = (1000, 1000), raw = true, camera = campixel!)
display(scene)
area = scene.px_area
poly!(scene, area)
grid_size = @lift((widths($area)[1] / $game.height, widths($area)[2] / $game.width))
snake_boxes = @lift([FRect2D((p.I .- (1,1)) .* $grid_size , $grid_size) for p in $game.snake])
poly!(scene, snake_boxes, color=:blue, strokewidth = 5, strokecolor = :black)
snake_head_box = @lift(FRect2D(($game.snake[1].I .- (1,1)) .* $grid_size , $grid_size))
poly!(scene, snake_head_box, color=:black)
snake_head = @lift((($game.snake[1].I .- 0.5) .* $grid_size))
scatter!(scene, snake_head, marker='◉', color=:blue, markersize=@lift(minimum($grid_size)))
food_position = @lift(($game.food.I .- (0.5,0.5)) .* $grid_size)
scatter!(scene, food_position, color=:red, marker='♥', markersize=@lift(minimum($grid_size)))
score_text = @lift("Score: $(length($game.snake)-1)")
text!(scene, score_text, color=:gray, position = @lift((widths($area)[1]/2, widths($area)[2])), textsize = 50, align = (:center, :top))
direction = Ref{Any}(nothing)
on(scene.events.keyboardbuttons) do but
if ispressed(but, Keyboard.left)
direction[] = CartesianIndex(-1,0)
elseif ispressed(but, Keyboard.up)
direction[] = CartesianIndex(0,1)
elseif ispressed(but, Keyboard.down)
direction[] = CartesianIndex(0,-1)
elseif ispressed(but, Keyboard.right)
direction[] = CartesianIndex(1,0)
end
end
last_dir = nothing
while true
# avoid turn back
if !isnothing(direction[]) && (isnothing(last_dir) || direction[] != -last_dir)
last_dir = direction[]
end
if !isnothing(last_dir)
if step!(game[], last_dir)
game[] = game[]
else
break
end
end
sleep(t)
end
end
play()
|
http://rosettacode.org/wiki/Smith_numbers | Smith numbers | Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers are also known as joke numbers.
Example
Using the number 166
Find the prime factors of 166 which are: 2 x 83
Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13
Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13
Therefore, the number 166 is a Smith number.
Task
Write a program to find all Smith numbers below 10000.
See also
from Wikipedia: [Smith number].
from MathWorld: [Smith number].
from OEIS A6753: [OEIS sequence A6753].
from OEIS A104170: [Number of Smith numbers below 10^n].
from The Prime pages: [Smith numbers].
| #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) {
writef("%4s ", n);
cnt++;
}
if (cnt==10) {
cnt = 0;
writeln();
}
}
}
}
auto primeFactors(int n) {
import std.array : appender;
auto result = appender!(int[]);
for (int i=2; n%i==0; n/=i) {
result.put(i);
}
for (int i=3; i*i<=n; i+=2) {
while (n%i==0) {
result.put(i);
n/=i;
}
}
if (n!=1) {
result.put(n);
}
return result.data;
}
int sumDigits(int n) {
int sum;
while (n > 0) {
sum += (n%10);
n /= 10;
}
return sum;
} |
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle | Solve a Hidato puzzle | The task is to write a program which solves Hidato (aka Hidoku) puzzles.
The rules are:
You are given a grid with some numbers placed in it. The other squares in the grid will be blank.
The grid is not necessarily rectangular.
The grid may have holes in it.
The grid is always connected.
The number “1” is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique.
It may be assumed that the difference between numbers present on the grid is not greater than lucky 13.
The aim is to place a natural number in each blank square so that in the sequence of numbered squares from “1” upwards, each square is in the wp:Moore neighborhood of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints).
Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order.
A square may only contain one number.
In a proper Hidato puzzle, the solution is unique.
For example the following problem
has the following solution, with path marked on it:
Related tasks
A* search algorithm
N-queens problem
Solve a Holy Knight's tour
Solve a Knight's tour
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle;
| #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 + 2) { IntArray(nCols + 2) { -1 } }
for (r in 0 until nRows) {
val row = puzzle[r]
for (c in 0 until nCols) {
val cell = row[c]
if (cell == "_") {
board[r + 1][c + 1] = 0
}
else if (cell != ".") {
val value = cell.toInt()
board[r + 1][c + 1] = value
list.add(value)
if (value == 1) start = intArrayOf(r + 1, c + 1)
}
}
}
list.sort()
given = list.toIntArray()
}
fun solve(r: Int, c: Int, n: Int, next: Int): Boolean {
if (n > given[given.lastIndex]) return true
val back = board[r][c]
if (back != 0 && back != n) return false
if (back == 0 && given[next] == n) return false
var next2 = next
if (back == n) next2++
board[r][c] = n
for (i in -1..1)
for (j in -1..1)
if (solve(r + i, c + j, n + 1, next2)) return true
board[r][c] = back
return false
}
fun printBoard() {
for (row in board) {
for (c in row) {
if (c == -1)
print(" . ")
else
print(if (c > 0) "%2d ".format(c) else "__ ")
}
println()
}
}
fun main(args: Array<String>) {
var input = listOf(
"_ 33 35 _ _ . . .",
"_ _ 24 22 _ . . .",
"_ _ _ 21 _ _ . .",
"_ 26 _ 13 40 11 . .",
"27 _ _ _ 9 _ 1 .",
". . _ _ 18 _ _ .",
". . . . _ 7 _ _",
". . . . . . 5 _"
)
setUp(input)
printBoard()
println("\nFound:")
solve(start[0], start[1], 1, 0)
printBoard()
} |
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 to such problems. At least demonstrate your program by solving the following:
Example
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
Note that the zeros represent the available squares, not the pennies.
Extra credit is available for other interesting examples.
Related tasks
A* search algorithm
Knight's tour
N-queens problem
Solve a Hidato puzzle
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #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....." +
"....xxxxx...." +
".....xxx....." +
"..x..x.x..x.." +
"xxxxx...xxxxx" +
"..xx.....xx.." +
"xxxxx...xxxxx" +
"..x..x.x..x.." +
".....xxx....." +
"....xxxxx...." +
".....x.x....." +
".....x.x....."
var solve // recursive
solve = Fn.new { |pz, sz, sx, sy, idx, cnt|
if (idx > cnt) return true
for (i in 0...moves.count) {
var x = sx + moves[i][0]
var y = sy + moves[i][1]
if ((x >= 0 && x < sz) && (y >= 0 && y < sz) && pz[x][y] == 0) {
pz[x][y] = idx
if (solve.call(pz, sz, x, y, idx + 1, cnt)) return true
pz[x][y] = 0
}
}
return false
}
var findSolution = Fn.new { |b, sz|
var pz = List.filled(sz, null)
for (i in 0...sz) pz[i] = List.filled(sz, -1)
var x = 0
var y = 0
var idx = 0
var cnt = 0
for (j in 0...sz) {
for (i in 0...sz) {
if (b[idx] == "x") {
pz[i][j] = 0
cnt = cnt + 1
} else if (b[idx] == "s") {
pz[i][j] = 1
cnt = cnt + 1
x = i
y = j
}
idx = idx + 1
}
}
if (solve.call(pz, sz, x, y, 2, cnt)) {
for (j in 0...sz) {
for (i in 0...sz) {
if (pz[i][j] != -1) {
Fmt.write("$02d ", pz[i][j])
} else {
System.write("-- ")
}
}
System.print()
}
} else {
System.print("Cannot solve this puzzle!")
}
}
findSolution.call(board1, 8)
System.print()
findSolution.call(board2, 13) |
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Sort an array of composite structures by a key.
For example, if you define a composite structure that presents a name-value pair (in pseudo-code):
Define structure pair such that:
name as a string
value as a string
and an array of such pairs:
x: array of pairs
then define a sort routine that sorts the array x by the key name.
This task can always be accomplished with Sorting Using a Custom Comparator.
If your language is not listed here, please see the other article.
| #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 {A.rest :a1} {H.sort.i :f {A.first :a1} :a2}} }}}
{lambda {:f :a}
{H.sort.r :f :a {A.new}} }}
-> H.sort
{def H.display
{lambda {:h}
{table
{tr {S.map {{lambda {:h :i} {td {car {A.get :i :h}}}} :h}
{S.serie 0 {- {A.length :h} 1}}}}
{tr {S.map {{lambda {:h :i} {td {cdr {A.get :i :h}}}} :h}
{S.serie 0 {- {A.length :h} 1}}}}
}}}
-> H.display
1) an array of pairs:
{def H {A.new {cons Joe 5531}
{cons Adam 2341}
{cons Bernie 122}
{cons Walter 1234}
{cons David 19}}}
-> H
2) display sorted by names:
{H.display
{H.sort {lambda {:a :b} {< {lexicographic {car :a} {car :b}} 0}} {H}}}
->
Adam Bernie David Joe Walter
2341 122 19 5531 1234
3) display sorted by values:
{H.display
{H.sort {lambda {:a :b} {< {cdr :a} {cdr :b}}} {H}}}
->
David Bernie Walter Adam Joe
19 122 1234 2341 5531
|
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle | Solve the no connection puzzle | You are given a box with eight holes labelled A-to-H, connected by fifteen straight lines in the pattern as shown below:
A B
/│\ /│\
/ │ X │ \
/ │/ \│ \
C───D───E───F
\ │\ /│ /
\ │ X │ /
\│/ \│/
G H
You are also given eight pegs numbered 1-to-8.
Objective
Place the eight pegs in the holes so that the (absolute) difference between any two numbers connected by any line is greater than one.
Example
In this attempt:
4 7
/│\ /│\
/ │ X │ \
/ │/ \│ \
8───1───6───2
\ │\ /│ /
\ │ X │ /
\│/ \│/
3 5
Note that 7 and 6 are connected and have a difference of 1, so it is not a solution.
Task
Produce and show here one solution to the puzzle.
Related tasks
A* search algorithm
Solve a Holy Knight's tour
Knight's tour
N-queens problem
Solve a Hidato puzzle
Solve a Holy Knight's tour
Solve a Hopido puzzle
Solve a Numbrix puzzle
4-rings or 4-squares puzzle
See also
No Connection Puzzle (youtube).
| #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] ||
[edge $e $h] ||
[edge $f $h]
}
}
proc edge {x y} {
expr {abs($x-$y) == 1}
}
set layout [string trim {
A B
/|\ /|\
/ | X | \
/ |/ \| \
C - D - E - F
\ |\ /| /
\ | X | /
\|/ \|/
G H
} \n]
struct::list foreachperm p {1 2 3 4 5 6 7 8} {
if {![haveAdjacent {*}$p]} {
puts [string map [join [
lmap name {A B C D E F G H} val $p {list $name $val}
]] $layout]
break
}
} |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted.
Make your example work with the following list of values and set of indices:
Values: [7, 6, 5, 4, 3, 2, 1, 0]
Indices: {6, 1, 7}
Where the correct result would be:
[7, 0, 5, 4, 3, 2, 1, 6].
In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead.
The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given.
Cf.
Order disjoint list items
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted.
Make your example work with the following list of values and set of indices:
Values: [7, 6, 5, 4, 3, 2, 1, 0]
Indices: {6, 1, 7}
Where the correct result would be:
[7, 0, 5, 4, 3, 2, 1, 6].
In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead.
The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given.
Cf.
Order disjoint list items
| #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 example work with the following list of values and set of indices:
%
% Values: [7, 6, 5, 4, 3, 2, 1, 0]
%
% Indices: {6, 1, 7}
%
% Where the correct result would be:
%
% [7, 0, 5, 4, 3, 2, 1, 6].
%
% In case of one-based indexing, rather than the zero-based indexing above,
% you would use the indices {7, 2, 8} instead.
%
% The indices are described as a set rather than a list but any collection-type
% of those indices without duplication may be used as long as the example is
% insensitive to the order of indices given.
% ===
% Notes
% ===
% For predicate descriptions, see https://www.swi-prolog.org/pldoc/man?section=preddesc
%
% Solution using only predicates marked "builtin".
%
% - sort/2 is a built-in predicate. When called as sort(A,B) then
% it sorts A to B according to the "standard order of terms",
% (for integers, this means ascending order). It does remove
% duplicates.
% - msort/2 is the same as sort/2 but does not remove duplicates.
%
% Everything is a list as there is no "set" datatype in Prolog.
% ===
% Main predicate (the one that would be exported from a Module)
% sort_disjoint_sublist(+Values,+Indexes,?ValuesSorted)
% ===
sort_disjoint_sublist(Values,Indexes,ValuesSorted) :-
sort(Indexes,IndexesSorted),
insert_fresh_vars(0,IndexesSorted,Values,FreshVars,ValsToSort,ValuesFreshened),
msort(ValsToSort,ValsSorted), % this is the "sorting of values"
% The next two lines could be left out with suitable naming,
% but they make explicit what happens:
FreshVars = ValsSorted, % fresh variables are unified with sorted variables
ValuesSorted = ValuesFreshened. % ValuesFreshend is automatically the sought output
% ===
% Helper predicate (would not be exported from a Module)
% ===
% insert_fresh_vars(+CurIdx,+[I|Is],+[V|Vs],-FreshVars,-ValsToSort,-ValsFreshy)
%
% CurIdx: Monotonically increasing index into the list of values by
% which we iterate.
% [I|Is]: Sorted list of indexes of interest. The smallest (leftmost)
% element is removed on every "index hit", leaving eventually
% an empty list, which gives us the base case.
% [V|Vs]: The list of values of interest with the leftmost element the
% element with index CurIdx, all elements with lower index
% having been discarded. Leftmost element is popped off on
% each call.
% FreshVars: Constructed as output. If there was an "index hit", the
% fresh variable pushed on FreshVars is also pushed on Vars.
% ValsToSort: Constructed as output. If there was an "index hit", the
% leftmost value from [V|Vs] is pushed on.
% ValsFreshy: Constructed as output. If there was an "index hit", a fresh
% variable is pushed on. If there was no "index hit", the actual
% value from [V|Vs] is pushed on instead.
insert_fresh_vars(CurIdx,[I|Is],[V|Vs],FreshVars,ValsToSort,[V|ValsFreshy]) :-
CurIdx<I, % no index hit, CurIdx is still too small, iterate over value
!,
succ(CurIdx,NextIdx),
insert_fresh_vars(NextIdx,[I|Is],Vs,FreshVars,ValsToSort,ValsFreshy).
insert_fresh_vars(CurIdx,[I|Is],[V|Vs],[Fresh|FreshVars],[V|ValsToSort],[Fresh|ValsFreshy]) :-
CurIdx=I, % index hit, replace value by fresh variable
!,
succ(CurIdx,NextIdx),
insert_fresh_vars(NextIdx,Is,Vs,FreshVars,ValsToSort,ValsFreshy).
insert_fresh_vars(_,[],V,[],[],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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
Use a sorting facility provided by the language/library, combined with your own callback comparison function.
Note: Lexicographic order is case-insensitive.
| #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
witheach [ echo$ sp ]
cr cr
$ "sharna pax and hed on a poal when the ardship of Cambry come out of his hoal"
nest$ sortwith comparator
witheach [ echo$ sp ] |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
Use a sorting facility provided by the language/library, combined with your own callback comparison function.
Note: Lexicographic order is case-insensitive.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort.
The pseudocode for the algorithm is:
function gnomeSort(a[0..size-1])
i := 1
j := 2
while i < size do
if a[i-1] <= a[i] then
// for descending sort, use >= for comparison
i := j
j := j + 1
else
swap a[i-1] and a[i]
i := i - 1
if i = 0 then
i := j
j := j + 1
endif
endif
done
Task
Implement the Gnome sort in your language to sort an array (or list) of numbers.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The cocktail shaker sort is an improvement on the Bubble Sort.
The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia):
function cocktailSort( A : list of sortable items )
do
swapped := false
for each i in 0 to length( A ) - 2 do
if A[ i ] > A[ i+1 ] then // test whether the two
// elements are in the wrong
// order
swap( A[ i ], A[ i+1 ] ) // let the two elements
// change places
swapped := true;
if swapped = false then
// we can exit the outer loop here if no swaps occurred.
break do-while loop;
swapped := false
for each i in length( A ) - 2 down to 0 do
if A[ i ] > A[ i+1 ] then
swap( A[ i ], A[ i+1 ] )
swapped := true;
while swapped; // if no elements have been swapped,
// then the list is sorted
Related task
cocktail sort with shifting bounds
| #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
Next
high - 1
If hasChanged = #False
Break ;we can exit the outer loop here if no changes were made
EndIf
hasChanged = #False
For index = high To low Step -1
If a(index) > a(index + 1)
Swap a(index), a(index + 1)
hasChanged = #True
EndIf
Next
low + 1
Until hasChanged = #False ;if no elements have been changed, then the array is sorted
EndProcedure |
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@socket_connect", 3);
var socket_write = $loader.loadprim("std@socket_write", 2);
var socket_close = $loader.loadprim("std@socket_close", 1);
/* Initialize Neko socket API */
socket_init();
/* true; UDP, false; TCP */
var socket = socket_new(true);
var c = socket_connect(socket, host_resolve("localhost"), 256);
socket_write(socket, "hello socket world");
socket_close(socket); |
http://rosettacode.org/wiki/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #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
OEIS A019546: Primes whose digits are primes.
https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
| #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
OEIS A019546: Primes whose digits are primes.
https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
| #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 {
for w in wheel {
if p * p > number {
return true
}
if number % p == 0 {
return false
}
p += w
}
}
}
func nextPrimeDigitNumber(number: Int) -> Int {
if number == 0 {
return 2
}
switch number % 10 {
case 2:
return number + 1
case 3, 5:
return number + 2
default:
return 2 + nextPrimeDigitNumber(number: number/10) * 10
}
}
let limit = 1000000000
var n = 0
var max = 0
var count = 0
print("First 25 SPDS primes:")
while n < limit {
n = nextPrimeDigitNumber(number: n)
if !isPrime(number: n) {
continue
}
if count < 25 {
print(n, terminator: " ")
} else if count == 25 {
print()
}
count += 1
if (count == 100) {
print("Hundredth SPDS prime: \(n)")
} else if (count == 1000) {
print("Thousandth SPDS prime: \(n)")
} else if (count == 10000) {
print("Ten thousandth SPDS prime: \(n)")
}
max = n
}
print("Largest SPDS prime less than \(limit): \(max)") |
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
OEIS A019546: Primes whose digits are primes.
https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
| #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
}
}
i = i + 2
if (i > 10) {
var j = i % 10
if (j == 1 || j == 5) {
i = i + 2
} else if (j == 9) {
i = i + 4
}
}
}
System.print("The first 25 SPDS primes are:")
System.print(spds.take(25).toList)
System.print("\nThe 100th SPDS prime is %(spds[99])")
System.print("\nThe 1,000th SPDS prime is %(spds[999])") |
http://rosettacode.org/wiki/Snake | Snake |
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Snake is a game where the player maneuvers a line which grows in length every time the snake reaches a food source.
Task
Implement a variant of the Snake game, in any interactive environment, in which a sole player attempts to eat items by running into them with the head of the snake.
Each item eaten makes the snake longer and a new item is randomly generated somewhere else on the plane.
The game ends when the snake attempts to eat himself.
| #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(WID * HEI)
var dir = Dir.NORTH
val snk = nativeHeap.allocArray<COORD>(MAX_LEN)
lateinit var head: COORD
var tailIdx = 0
var headIdx = 0
var points = 0
init {
console = GetStdHandle(STD_OUTPUT_HANDLE)!!
SetConsoleTitleW("Snake")
memScoped {
val coord = alloc<COORD>().apply { X = (WID + 1).toShort(); Y = (HEI + 2).toShort() }
SetConsoleScreenBufferSize(console, coord.readValue())
val rc = alloc<SMALL_RECT>().apply {
Left = 0; Top = 0; Right = WID.toShort(); Bottom = (HEI + 1).toShort()
}
SetConsoleWindowInfo(console, TRUE, rc.ptr)
val ci = alloc<CONSOLE_CURSOR_INFO>().apply { dwSize = 1; bVisible = FALSE }
SetConsoleCursorInfo(console, ci.ptr)
}
}
fun play() {
while (true) {
createfield()
alive = true
while (alive) {
drawfield()
readKey()
moveSnake()
Sleep(50)
}
memScoped {
val c = alloc<COORD>().apply { X = 0; Y = (HEI + 1).toShort() }
SetConsoleCursorPosition(console, c.readValue())
}
SetConsoleTextAttribute(console, 0x000b)
print("Play again [Y/N]? ")
val a = readLine()!!.toLowerCase()
if (a.length > 0 && a[0] != 'y') {
nativeHeap.free(snk)
return
}
}
}
private fun createfield() {
memScoped {
val coord = alloc<COORD>().apply { X = 0; Y = 0 }
val c = alloc<DWORDVar>()
FillConsoleOutputCharacterW(console, 32, (HEI + 2) * 80, coord.readValue(), c.ptr)
FillConsoleOutputAttribute(console, 0x0000, (HEI + 2) * 80, coord.readValue(), c.ptr)
SetConsoleCursorPosition(console, coord.readValue())
}
for (x in 0 until WID * HEI) brd[x] = NUL
for (x in 0 until WID) {
brd[x + WID * (HEI - 1)] = '+'
brd[x] = '+'
}
for (y in 1 until HEI) {
brd[WID - 1 + WID * y] = '+'
brd[WID * y] = '+'
}
var xx: Int
var yy: Int
do {
xx = rand() % WID
yy = rand() % (HEI shr 1) + (HEI shr 1)
}
while (brd[xx + WID * yy] != NUL)
brd[xx + WID * yy] = '@'
tailIdx = 0
headIdx = 4
xx = 3
yy = 2
for (cc in tailIdx until headIdx) {
brd[xx + WID * yy] = '#'
snk[cc].X = (3 + cc).toShort()
snk[cc].Y = 2
}
head = snk[3]
dir = Dir.EAST
points = 0
}
private fun readKey() {
if ((GetAsyncKeyState(39).toInt() and 0x8000) != 0) dir = Dir.EAST
if ((GetAsyncKeyState(37).toInt() and 0x8000) != 0) dir = Dir.WEST
if ((GetAsyncKeyState(38).toInt() and 0x8000) != 0) dir = Dir.NORTH
if ((GetAsyncKeyState(40).toInt() and 0x8000) != 0) dir = Dir.SOUTH
}
private fun drawfield() {
memScoped {
val coord = alloc<COORD>()
var t = NUL
for (y in 0 until HEI) {
coord.Y = y.toShort()
for (x in 0 until WID) {
t = brd[x + WID * y]
if (t == NUL) continue
coord.X = x.toShort()
SetConsoleCursorPosition(console, coord.readValue())
if (coord.X == head.X && coord.Y == head.Y) {
SetConsoleTextAttribute(console, 0x002e)
print('O')
SetConsoleTextAttribute(console, 0x0000)
continue
}
when (t) {
'#' -> SetConsoleTextAttribute(console, 0x002a)
'+' -> SetConsoleTextAttribute(console, 0x0019)
'@' -> SetConsoleTextAttribute(console, 0x004c)
}
print(t)
SetConsoleTextAttribute(console, 0x0000)
}
}
print(t)
SetConsoleTextAttribute(console, 0x0007)
val c = alloc<COORD>().apply { X = 0; Y = HEI.toShort() }
SetConsoleCursorPosition(console, c.readValue())
print("Points: $points")
}
}
private fun moveSnake() {
when (dir) {
Dir.NORTH -> head.Y--
Dir.EAST -> head.X++
Dir.SOUTH -> head.Y++
Dir.WEST -> head.X--
}
val t = brd[head.X + WID * head.Y]
if (t != NUL && t != '@') {
alive = false
return
}
brd[head.X + WID * head.Y] = '#'
snk[headIdx].X = head.X
snk[headIdx].Y = head.Y
if (++headIdx >= MAX_LEN) headIdx = 0
if (t == '@') {
points++
var x: Int
var y: Int
do {
x = rand() % WID
y = rand() % (HEI shr 1) + (HEI shr 1)
}
while (brd[x + WID * y] != NUL)
brd[x + WID * y] = '@'
return
}
SetConsoleCursorPosition(console, snk[tailIdx].readValue())
print(' ')
brd[snk[tailIdx].X + WID * snk[tailIdx].Y] = NUL
if (++tailIdx >= MAX_LEN) tailIdx = 0
}
}
fun main(args: Array<String>) {
srand(time(null).toInt())
Snake().play()
} |
http://rosettacode.org/wiki/Smith_numbers | Smith numbers | Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers are also known as joke numbers.
Example
Using the number 166
Find the prime factors of 166 which are: 2 x 83
Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13
Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13
Therefore, the number 166 is a Smith number.
Task
Write a program to find all Smith numbers below 10000.
See also
from Wikipedia: [Smith number].
from MathWorld: [Smith number].
from OEIS A6753: [OEIS sequence A6753].
from OEIS A104170: [Number of Smith numbers below 10^n].
from The Prime pages: [Smith numbers].
| #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 of
factors. */
proc nonrec factors(word n; [*] word facs) word:
word count, fac;
count := 0;
/* take out factors of 2 */
while n > 0 and n & 1 = 0 do
n := n >> 1;
facs[count] := 2;
count := count + 1
od;
/* take out odd factors */
fac := 3;
while n >= fac do
while n % fac = 0 do
n := n / fac;
facs[count] := fac;
count := count + 1;
od;
fac := fac + 2
od;
count
corp
/* See if a number is a Smith number */
proc nonrec smith(word n) bool:
[32] word facs; /* 32 factors ought to be enough for everyone */
word dsum, facsum, nfacs, i;
nfacs := factors(n, facs);
if nfacs = 1 then
false /* primes are not Smith numbers */
else
dsum := digitsum(n);
facsum := 0;
for i from 0 upto nfacs-1 do
facsum := facsum + digitsum(facs[i])
od;
dsum = facsum
fi
corp
/* Find all Smith numbers below 10000 */
proc nonrec main() void:
word i, count;
count := 0;
for i from 2 upto 9999 do
if smith(i) then
write(i:5);
count := count + 1;
if count & 0xF = 0 then writeln() fi
fi
od;
writeln();
writeln("Found ", count, " Smith numbers.")
corp |
http://rosettacode.org/wiki/Smith_numbers | Smith numbers | Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers are also known as joke numbers.
Example
Using the number 166
Find the prime factors of 166 which are: 2 x 83
Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13
Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13
Therefore, the number 166 is a Smith number.
Task
Write a program to find all Smith numbers below 10000.
See also
from Wikipedia: [Smith number].
from MathWorld: [Smith number].
from OEIS A6753: [OEIS sequence A6753].
from OEIS A104170: [Number of Smith numbers below 10^n].
from The Prime pages: [Smith numbers].
| #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 of
factors. */
proc nonrec factors(word n; [*] word facs) word:
word count, fac;
count := 0;
/* take out factors of 2 */
while n > 0 and n & 1 = 0 do
n := n >> 1;
facs[count] := 2;
count := count + 1
od;
/* take out odd factors */
fac := 3;
while n >= fac do
while n % fac = 0 do
n := n / fac;
facs[count] := fac;
count := count + 1;
od;
fac := fac + 2
od;
count
corp
/* See if a number is a Smith number */
proc nonrec smith(word n) bool:
[32] word facs; /* 32 factors ought to be enough for everyone */
word dsum, facsum, nfacs, i;
nfacs := factors(n, facs);
if nfacs = 1 then
false /* primes are not Smith numbers */
else
dsum := digitsum(n);
facsum := 0;
for i from 0 upto nfacs-1 do
facsum := facsum + digitsum(facs[i])
od;
dsum = facsum
fi
corp
/* Find all Smith numbers below 10000 */
proc nonrec main() void:
word i, count;
count := 0;
for i from 2 upto 9999 do
if smith(i) then
write(i:5);
count := count + 1;
if count & 0xF = 0 then writeln() fi
fi
od;
writeln();
writeln("Found ", count, " Smith numbers.")
corp |
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle | Solve a Hidato puzzle | The task is to write a program which solves Hidato (aka Hidoku) puzzles.
The rules are:
You are given a grid with some numbers placed in it. The other squares in the grid will be blank.
The grid is not necessarily rectangular.
The grid may have holes in it.
The grid is always connected.
The number “1” is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique.
It may be assumed that the difference between numbers present on the grid is not greater than lucky 13.
The aim is to place a natural number in each blank square so that in the sequence of numbered squares from “1” upwards, each square is in the wp:Moore neighborhood of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints).
Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order.
A square may only contain one number.
In a proper Hidato puzzle, the solution is unique.
For example the following problem
has the following solution, with path marked on it:
Related tasks
A* search algorithm
N-queens problem
Solve a Holy Knight's tour
Solve a Knight's tour
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle;
| #Mathprog | Mathprog | /*Hidato.mathprog, part of KuKu by Nigel Galloway
Find a solution to a Hidato problem
[email protected]
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,COLSR}, integer, default 0;
set ZBLSV := 1..(ZBLS+1);
set ZBLSR := 1..ZBLS;
var BR{ROWSV,COLSV,ZBLSV}, binary;
void0{r in ROWSV, z in ZBLSR,c in (1-D)..0}: BR[r,c,z] = 0;
void1{r in ROWSV, z in ZBLSR,c in (COLS+1)..(COLS+D)}: BR[r,c,z] = 0;
void2{c in COLSV, z in ZBLSR,r in (1-D)..0}: BR[r,c,z] = 0;
void3{c in COLSV, z in ZBLSR,r in (ROWS+1)..(ROWS+D)}: BR[r,c,z] = 0;
void4{r in ROWSV,c in (1-D)..0}: BR[r,c,ZBLS+1] = 1;
void5{r in ROWSV,c in (COLS+1)..(COLS+D)}: BR[r,c,ZBLS+1] = 1;
void6{c in COLSV,r in (1-D)..0}: BR[r,c,ZBLS+1] = 1;
void7{c in COLSV,r in (ROWS+1)..(ROWS+D)}: BR[r,c,ZBLS+1] = 1;
Izfree{r in ROWSR, c in COLSR, z in ZBLSR : Iz[r,c] = -1}: BR[r,c,z] = 0;
Iz1{Izr in ROWSR, Izc in COLSR, r in ROWSR, c in COLSR, z in ZBLSR : Izr=r and Izc=c and Iz[Izr,Izc]=z}: BR[r,c,z] = 1;
rule1{z in ZBLSR}: sum{r in ROWSR, c in COLSR} BR[r,c,z] = 1;
rule2{r in ROWSR, c in COLSR}: sum{z in ZBLSV} BR[r,c,z] = 1;
rule3{r in ROWSR, c in COLSR, z in ZBLSR}: BR[0,0,z+1] + BR[r-1,c-1,z+1] + BR[r-1,c,z+1] + BR[r-1,c+1,z+1] + BR[r,c-1,z+1] + BR[r,c+1,z+1] + BR[r+1,c-1,z+1] + BR[r+1,c,z+1] + BR[r+1,c+1,z+1] - BR[r,c,z] >= 0;
solve;
for {r in ROWSR} {
for {c in COLSR} {
printf " %2d", sum{z in ZBLSR} BR[r,c,z]*z;
}
printf "\n";
}
data;
param ROWS := 8;
param COLS := 8;
param ZBLS := 40;
param
Iz: 1 2 3 4 5 6 7 8 :=
1 . 33 35 . . -1 -1 -1
2 . . 24 22 . -1 -1 -1
3 . . . 21 . . -1 -1
4 . 26 . 13 40 11 -1 -1
5 27 . . . 9 . 1 -1
6 -1 -1 . . 18 . . -1
7 -1 -1 -1 -1 . 7 . .
8 -1 -1 -1 -1 -1 -1 5 .
;
end; |
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Sort an array of composite structures by a key.
For example, if you define a composite structure that presents a name-value pair (in pseudo-code):
Define structure pair such that:
name as a string
value as a string
and an array of such pairs:
x: array of pairs
then define a sort routine that sorts the array x by the key name.
This task can always be accomplished with Sorting Using a Custom Comparator.
If your language is not listed here, please see the other article.
| #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 "Sorted by name" ' ( we specified column 1)
for i =1 to N
print IntArray$( i, 1), IntArray$( i, 2)
next i
|
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle | Solve the no connection puzzle | You are given a box with eight holes labelled A-to-H, connected by fifteen straight lines in the pattern as shown below:
A B
/│\ /│\
/ │ X │ \
/ │/ \│ \
C───D───E───F
\ │\ /│ /
\ │ X │ /
\│/ \│/
G H
You are also given eight pegs numbered 1-to-8.
Objective
Place the eight pegs in the holes so that the (absolute) difference between any two numbers connected by any line is greater than one.
Example
In this attempt:
4 7
/│\ /│\
/ │ X │ \
/ │/ \│ \
8───1───6───2
\ │\ /│ /
\ │ X │ /
\│/ \│/
3 5
Note that 7 and 6 are connected and have a difference of 1, so it is not a solution.
Task
Produce and show here one solution to the puzzle.
Related tasks
A* search algorithm
Solve a Holy Knight's tour
Knight's tour
N-queens problem
Solve a Hidato puzzle
Solve a Holy Knight's tour
Solve a Hopido puzzle
Solve a Numbrix puzzle
4-rings or 4-squares puzzle
See also
No Connection Puzzle (youtube).
| #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 = [
[0, 2], [0, 3], [0, 4], // A to C, D, E
[1, 3], [1, 4], [1, 5], // B to D, E, F
[6, 2], [6, 3], [6, 4], // G to C, D, E
[7, 3], [7, 4], [7, 5], // H to D, E, F
[2, 3], [3, 4], [4, 5] // C-D, D-E, E-F
]
// 'isValid' checks if the pegs are a valid solution.
// If the absolute difference between any pair of connected pegs is
// greater than one it is a valid solution.
var isValid = Fn.new { |pegs|
for (c in connections) {
if ((pegs[c[0]] - pegs[c[1]]).abs <= 1) return false
}
return true
}
var swap = Fn.new { |pegs, i, j|
var tmp = pegs[i]
pegs[i] = pegs[j]
pegs[j] = tmp
}
// 'solve' is a simple recursive brute force solver,
// it stops at the first found solution.
// It returns the solution, the number of positions tested,
// and the number of pegs swapped.
var solve
solve = Fn.new {
var pegs = List.filled(8, 0)
for (i in 0..7) pegs[i] = i + 1
var tests = 0
var swaps = 0
var recurse // recursive closure
recurse = Fn.new { |i|
if (i >= pegs.count - 1) {
tests = tests + 1
return isValid.call(pegs)
}
// Try each remaining peg from pegs[i] onwards
for (j in i...pegs.count) {
swaps = swaps + 1
swap.call(pegs, i, j)
if (recurse.call(i + 1)) return true
swap.call(pegs, i, j)
}
return false
}
recurse.call(0)
return Solution.new(pegs, tests, swaps)
}
var pegsAsString = Fn.new { |pegs|
var ca = conn.toList
var i = 0
for (c in ca) {
if ("ABCDEFGH".contains(c)) ca[i] = String.fromByte(48 + pegs[c.bytes[0] - 65])
i = i + 1
}
return ca.join()
}
var s = solve.call()
System.print(pegsAsString.call(s.p))
System.print("Tested %(s.tests) positions and did %(s.swaps) swaps.") |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
| #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}}
-> [2,33,41,51,111]
|
http://rosettacode.org/wiki/Sort_disjoint_sublist | Sort disjoint sublist |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted.
Make your example work with the following list of values and set of indices:
Values: [7, 6, 5, 4, 3, 2, 1, 0]
Indices: {6, 1, 7}
Where the correct result would be:
[7, 0, 5, 4, 3, 2, 1, 6].
In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead.
The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given.
Cf.
Order disjoint list items
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
Use a sorting facility provided by the language/library, combined with your own callback comparison function.
Note: Lexicographic order is case-insensitive.
| #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" "of")
;; Doing two sorts, relying on `sort's stability
(define (sort2 words)
(sort (sort words string-ci<?) > #:key string-length))
(sort2 '("Some" "pile" "of" "words"))
;; -> '("words" "pile" "Some" "of")
|
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of strings in order of descending length, and in ascending lexicographic order for strings of equal length.
Use a sorting facility provided by the language/library, combined with your own callback comparison function.
Note: Lexicographic order is case-insensitive.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
A bubble sort is generally considered to be the simplest sorting algorithm.
A bubble sort is also known as a sinking sort.
Because of its simplicity and ease of visualization, it is often taught in introductory computer science courses.
Because of its abysmal O(n2) performance, it is not used often for large (or even medium-sized) datasets.
The bubble sort works by passing sequentially over a list, comparing each value to the one immediately after it. If the first value is greater than the second, their positions are switched. Over a number of passes, at most equal to the number of elements in the list, all of the values drift into their correct positions (large values "bubble" rapidly toward the end, pushing others down around them).
Because each pass finds the maximum item and puts it at the end, the portion of the list to be sorted can be reduced at each pass.
A boolean variable is used to track whether any changes have been made in the current pass; when a pass completes without changing anything, the algorithm exits.
This can be expressed in pseudo-code as follows (assuming 1-based indexing):
repeat
if itemCount <= 1
return
hasChanged := false
decrement itemCount
repeat with index from 1 to itemCount
if (item at index) > (item at (index + 1))
swap (item at index) with (item at (index + 1))
hasChanged := true
until hasChanged = false
Task
Sort an array of elements using the bubble sort algorithm. The elements must have a total order and the index of the array can be of any discrete type. For languages where this is not possible, sort an array of integers.
References
The article on Wikipedia.
Dance interpretation.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort.
The pseudocode for the algorithm is:
function gnomeSort(a[0..size-1])
i := 1
j := 2
while i < size do
if a[i-1] <= a[i] then
// for descending sort, use >= for comparison
i := j
j := j + 1
else
swap a[i-1] and a[i]
i := i - 1
if i = 0 then
i := j
j := j + 1
endif
endif
done
Task
Implement the Gnome sort in your language to sort an array (or list) of numbers.
| #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
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The cocktail shaker sort is an improvement on the Bubble Sort.
The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia):
function cocktailSort( A : list of sortable items )
do
swapped := false
for each i in 0 to length( A ) - 2 do
if A[ i ] > A[ i+1 ] then // test whether the two
// elements are in the wrong
// order
swap( A[ i ], A[ i+1 ] ) // let the two elements
// change places
swapped := true;
if swapped = false then
// we can exit the outer loop here if no swaps occurred.
break do-while loop;
swapped := false
for each i in length( A ) - 2 down to 0 do
if A[ i ] > A[ i+1 ] then
swap( A[ i ], A[ i+1 ] )
swapped := true;
while swapped; // if no elements have been swapped,
// then the list is sorted
Related task
cocktail sort with shifting bounds
| #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:
return |
http://rosettacode.org/wiki/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #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'
if port = '' then port = 256
if message = '' then message = 'hello socket world'
sendToSocket(host, port, message)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method sendToSocket(host, port, message) public static
do
sokt = Socket(host, port)
soks = sokt.getOutputStream()
soks.write((String message).getBytes())
soks.flush()
sokt.close()
catch ix = IOException
ix.printStackTrace()
end
return
|
http://rosettacode.org/wiki/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #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
OEIS A019546: Primes whose digits are primes.
https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
| #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:= N/10;
case rem(0) of
0, 1, 4, 6, 8, 9: return false
other [];
until N = 0;
return true;
];
int C, N;
[C:= 0; N:= 2;
loop [if IsPrime(N) then
if PrimeDigits(N) then
[C:= C+1;
if C <= 25 then
[IntOut(0, N); ChOut(0, ^ )];
if C = 100 then
[Text(0, "^m^j100th: "); IntOut(0, N)];
if C = 1000 then quit;
];
N:= N+1;
];
Text(0, "^m^j1000th: "); IntOut(0, N); CrLf(0);
] |
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
OEIS A019546: Primes whose digits are primes.
https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
| #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
if flag = len(nStr$) then
num = num + 1
if num < limit print "", n, " ";
if num = limit100 print "\n\n100th Smarandache prime: ", n
end if
next n
end
sub isPrime(v)
if v < 2 return False
if mod(v, 2) = 0 return v = 2
if mod(v, 3) = 0 return v = 3
d = 5
while d * d <= v
if mod(v, d) = 0 then return False else d = d + 2 : fi
wend
return True
end sub |
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
OEIS A019546: Primes whose digits are primes.
https://www.scribd.com/document/214851583/On-the-Smarandache-prime-digital-subsequence-sequences
| #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(BI(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 in length every time the snake reaches a food source.
Task
Implement a variant of the Snake game, in any interactive environment, in which a sole player attempts to eat items by running into them with the head of the snake.
Each item eaten makes the snake longer and a new item is randomly generated somewhere else on the plane.
The game ends when the snake attempts to eat himself.
| #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 before we get in
if x == Body[i] and y == Body[i+1] then
return true
end
end
return false
end
local function isPositionInApple(x, y)
if x == Apple.x and y == Apple.y then
return true
end
return false
end
local function newApple ()
local ApplePlaced = false
while not ApplePlaced do
local x = GridSize*math.random (GridWidth)
local y = GridSize*math.random (GridHeight)
if not isPositionInBody(x, y) then
Apple = {x=x, y=y}
ApplePlaced = true
end
end
end
local function newGame ()
Score = 0
GameOver = false
local x = GridSize*math.floor(math.random (0.25*GridWidth, 0.75*GridWidth))
print (x)
local y = GridSize*math.floor(math.random (0.25*GridHeight, 0.75*GridHeight))
print (y)
local iDirection = math.random(4)
local d = directions[iDirection]
Head = {
x=x,
y=y,
iDirection = iDirection,
nextDirection = iDirection,
}
Body = {x, y, x-GridSize*d.x, y-GridSize*d.y}
Apples = {}
newApple ()
end
function love.load()
newGame ()
end
local function moveSnake (x, y, iDirection, longer)
table.insert (Body, 1, x)
table.insert (Body, 2, y)
Head.x = x
Head.y = y
Head.iDirection = iDirection
if not longer then
-- remove last pair
table.remove(Body)
table.remove(Body)
end
if x <= 0 or x > GridSize*(GridWidth) or
y <= 0 or y > GridSize*(GridHeight) then
GameOver = true
end
end
function love.update(dt)
Timer = Timer + dt
if Timer < UpdateTime then return end
Timer = Timer - UpdateTime
local iDirection = Head.nextDirection
local d = directions[iDirection]
local x, y = Head.x+GridSize*d.x, Head.y+GridSize*d.y
if isPositionInBody(x, y) then
GameOver = true
elseif isPositionInApple(x, y) then
Score = Score + 1
newApple ()
moveSnake (x, y, iDirection, true)
else
moveSnake (x, y, iDirection, false)
end
end
function drawHead () -- position, length, width and angle
love.graphics.push()
love.graphics.translate(Head.x, Head.y)
love.graphics.rotate((Head.iDirection-2)*math.pi/2)
love.graphics.polygon("fill",
-GridSize/3, -GridSize /3,
-GridSize/3, GridSize /3,
GridSize/3, 0)
love.graphics.pop()
end
function love.draw()
love.graphics.setColor(0,1,0)
love.graphics.print ('Score: '..tostring(Score), 10, 10)
if GameOver then
love.graphics.print ('Game Over: '..tostring(GameOver)..'. Press "Space" to continue', 10, 30)
else
love.graphics.translate(GridSize, GridSize)
love.graphics.setColor(0.6,0.6,0.6)
love.graphics.setLineWidth(0.25)
for x = GridSize, GridSize*GridWidth, GridSize do
love.graphics.line (x, GridSize, x, GridSize*GridHeight)
end
for y = GridSize, GridSize*GridHeight, GridSize do
love.graphics.line (GridSize, y, GridSize*GridWidth, y)
end
love.graphics.setLineWidth((GridSize/4)+0.5)
love.graphics.setColor(1,1,1)
love.graphics.line (Body)
drawHead ()
love.graphics.setColor(1,0,0)
love.graphics.circle ('fill', Apple.x, Apple.y, GridSize/4)
end
end
function love.keypressed(key, scancode, isrepeat)
if false then
elseif key == "space" then
if GameOver then
GameOver = false
newGame ()
end
elseif key == "escape" then
love.event.quit()
else
local iDirection = Head.iDirection
if iDirection == UP or
iDirection == DOWN then
local right = love.keyboard.isScancodeDown ("d")
local left = love.keyboard.isScancodeDown ("a")
if right and not left then
iDirection = RIGHT
elseif left and not right then
iDirection = LEFT
end
else -- right or left
local down = love.keyboard.isScancodeDown ("s")
local up = love.keyboard.isScancodeDown ("w")
if up and not down then
iDirection = UP
elseif down and not up then
iDirection = DOWN
end
end
Head.nextDirection = iDirection
end
end |
http://rosettacode.org/wiki/Smith_numbers | Smith numbers | Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers are also known as joke numbers.
Example
Using the number 166
Find the prime factors of 166 which are: 2 x 83
Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13
Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13
Therefore, the number 166 is a Smith number.
Task
Write a program to find all Smith numbers below 10000.
See also
from Wikipedia: [Smith number].
from MathWorld: [Smith number].
from OEIS A6753: [OEIS sequence A6753].
from OEIS A104170: [Number of Smith numbers below 10^n].
from The Prime pages: [Smith numbers].
| #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]
defp decomposition(n, k, acc) when rem(n, k) == 0, do: decomposition(div(n, k), k, [k | acc])
defp decomposition(n, k, acc), do: decomposition(n, k+1, acc)
end
m = 10000
smith = Enum.filter(1..m, &Smith.number?/1)
IO.puts "#{length(smith)} smith numbers below #{m}:"
IO.puts "First 10: #{Enum.take(smith,10) |> Enum.join(", ")}"
IO.puts "Last 10: #{Enum.take(smith,-10) |> Enum.join(", ")}" |
http://rosettacode.org/wiki/Smith_numbers | Smith numbers | Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers are also known as joke numbers.
Example
Using the number 166
Find the prime factors of 166 which are: 2 x 83
Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13
Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13
Therefore, the number 166 is a Smith number.
Task
Write a program to find all Smith numbers below 10000.
See also
from Wikipedia: [Smith number].
from MathWorld: [Smith number].
from OEIS A6753: [OEIS sequence A6753].
from OEIS A104170: [Number of Smith numbers below 10^n].
from The Prime pages: [Smith numbers].
| #F.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->fN g=fst(primes32()|>Seq.scan(fun n g->fG n g)(0,g)|>Seq.find(fun(_,n)->n=1)))
|>Seq.chunkBySize 20|>Seq.iter(fun n->Seq.iter(printf "%4d ") n; printfn "")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.