task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle | Solve a Hidato puzzle | The task is to write a program which solves Hidato (aka Hidoku) puzzles.
The rules are:
You are given a grid with some numbers placed in it. The other squares in the grid will be blank.
The grid is not necessarily rectangular.
The grid may have holes in it.
The grid is always connected.
The number “1” is always 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;
| #C.23 | C# | using System.Collections;
using System.Collections.Generic;
using static System.Console;
using static System.Math;
using static System.Linq.Enumerable;
public class Solver
{
private static readonly (int dx, int dy)[]
//other puzzle types elided
hidatoMoves = {(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)};
private (int dx, int dy)[] moves;
public static void Main()
{
Print(new Solver(hidatoMoves).Solve(false, new [,] {
{ 0, 33, 35, 0, 0, -1, -1, -1 },
{ 0, 0, 24, 22, 0, -1, -1, -1 },
{ 0, 0, 0, 21, 0, 0, -1, -1 },
{ 0, 26, 0, 13, 40, 11, -1, -1 },
{ 27, 0, 0, 0, 9, 0, 1, -1 },
{ -1, -1, 0, 0, 18, 0, 0, -1 },
{ -1, -1, -1, -1, 0, 7, 0, 0 },
{ -1, -1, -1, -1, -1, -1, 5, 0 }
}));
}
public Solver(params (int dx, int dy)[] moves) => this.moves = moves;
public int[,] Solve(bool circular, params string[] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
public int[,] Solve(bool circular, int[,] puzzle)
{
var (board, given, count) = Parse(puzzle);
return Solve(board, given, count, circular);
}
private int[,] Solve(int[,] board, BitArray given, int count, bool circular)
{
var (height, width) = (board.GetLength(0), board.GetLength(1));
bool solved = false;
for (int x = 0; x < height && !solved; x++) {
solved = Range(0, width).Any(y => Solve(board, given, circular, (height, width), (x, y), count, (x, y), 1));
if (solved) return board;
}
return null;
}
private bool Solve(int[,] board, BitArray given, bool circular,
(int h, int w) size, (int x, int y) start, int last, (int x, int y) current, int n)
{
var (x, y) = current;
if (x < 0 || x >= size.h || y < 0 || y >= size.w) return false;
if (board[x, y] < 0) return false;
if (given[n - 1]) {
if (board[x, y] != n) return false;
} else if (board[x, y] > 0) return false;
board[x, y] = n;
if (n == last) {
if (!circular || AreNeighbors(start, current)) return true;
}
for (int i = 0; i < moves.Length; i++) {
var move = moves[i];
if (Solve(board, given, circular, size, start, last, (x + move.dx, y + move.dy), n + 1)) return true;
}
if (!given[n - 1]) board[x, y] = 0;
return false;
bool AreNeighbors((int x, int y) p1, (int x, int y) p2) => moves.Any(m => (p2.x + m.dx, p2.y + m.dy).Equals(p1));
}
private static (int[,] board, BitArray given, int count) Parse(string[] input)
{
(int height, int width) = (input.Length, input[0].Length);
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++) {
string line = input[x];
for (int y = 0; y < width; y++) {
board[x, y] = y < line.Length && char.IsDigit(line[y]) ? line[y] - '0' : -1;
if (board[x, y] >= 0) count++;
}
}
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static (int[,] board, BitArray given, int count) Parse(int[,] input)
{
(int height, int width) = (input.GetLength(0), input.GetLength(1));
int[,] board = new int[height, width];
int count = 0;
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if ((board[x, y] = input[x, y]) >= 0) count++;
BitArray given = Scan(board, count, height, width);
return (board, given, count);
}
private static BitArray Scan(int[,] board, int count, int height, int width)
{
var given = new BitArray(count + 1);
for (int x = 0; x < height; x++)
for (int y = 0; y < width; y++)
if (board[x, y] > 0) given[board[x, y] - 1] = true;
return given;
}
private static void Print(int[,] board)
{
if (board == null) {
WriteLine("No solution");
} else {
int w = board.Cast<int>().Where(i => i > 0).Max(i => (int?)Ceiling(Log10(i+1))) ?? 1;
string e = new string('-', w);
foreach (int x in Range(0, board.GetLength(0)))
WriteLine(string.Join(" ", Range(0, board.GetLength(1))
.Select(y => board[x, y] < 0 ? e : board[x, y].ToString().PadLeft(w, ' '))));
}
WriteLine();
}
} |
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.
| #Julia | Julia | struct BoardState
board::String
csol::String
position::Int
end
function move(s::BoardState, dpos)
buffer = Vector{UInt8}(deepcopy(s.board))
if s.board[s.position] == '@'
buffer[s.position] = ' '
else
buffer[s.position] = '.'
end
newpos = s.position + dpos
if s.board[newpos] == ' '
buffer[newpos] = '@'
else
buffer[newpos] = '+'
end
String(buffer)
end
function push(s::BoardState, dpos)
newpos = s.position + dpos
boxpos = newpos + dpos
if s.board[boxpos] != ' ' && s.board[boxpos] != '.'
return ""
end
buffer = Vector{UInt8}(deepcopy(s.board))
if s.board[s.position] == '@'
buffer[s.position] = ' '
else
buffer[s.position] = '.'
end
if s.board[newpos] == '$'
buffer[newpos] = '@'
else
buffer[newpos] = '+'
end
if s.board[boxpos] == ' '
buffer[boxpos] = '$'
else
buffer[boxpos] = '*'
end
String(buffer)
end
function solve(board)
width = findfirst("\n", board[2:end])[1] + 1
dopt = (u = -width, l = -1, d = width, r = 1)
visited = Dict(board => true)
open::Vector{BoardState} = [BoardState(board, "", findfirst("@", board)[1])]
while length(open) > 0
s1 = open[1]
open = open[2:end]
for dir in keys(dopt)
newpos = s1.position + dopt[dir]
x = s1.board[newpos]
if x == '$' || x == '*'
newboard = push(s1, dopt[dir])
if newboard == "" || haskey(visited, newboard)
continue
end
newsol = s1.csol * uppercase(string(dir))
if findfirst(r"[\.\+]", newboard) == nothing
return newsol
end
elseif x == ' ' || x == '.'
newboard = move(s1, dopt[dir])
if haskey(visited, newboard)
continue
end
newsol = s1.csol * string(dir)
else
continue
end
open = push!(open, BoardState(newboard, newsol, newpos))
visited[newboard] = true
end
end
"No solution" # we should only get here if no solution to the sokoban
end
const testlevel = strip(raw"""
#######
# #
# #
#. # #
#. $$ #
#.$$ #
#.# @#
#######""")
println("For sokoban level:\n$testlevel\n...solution is :\n$(solve(testlevel))")
|
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.
| #Kotlin | Kotlin | // version 1.2.0
import java.util.LinkedList
class Sokoban(board: List<String>) {
val destBoard: String
val currBoard: String
val nCols = board[0].length
var playerX = 0
var playerY = 0
init {
val destBuf = StringBuilder()
val currBuf = StringBuilder()
for (r in 0 until board.size) {
for (c in 0 until nCols) {
val ch = board[r][c]
destBuf.append(if (ch != '$' && ch != '@') ch else ' ')
currBuf.append(if (ch != '.') ch else ' ')
if (ch == '@') {
playerX = c
playerY = r
}
}
}
destBoard = destBuf.toString()
currBoard = currBuf.toString()
}
fun move(x: Int, y: Int, dx: Int, dy: Int, trialBoard: String): String {
val newPlayerPos = (y + dy) * nCols + x + dx
if (trialBoard[newPlayerPos] != ' ') return ""
val trial = trialBoard.toCharArray()
trial[y * nCols + x] = ' '
trial[newPlayerPos] = '@'
return String(trial)
}
fun push(x: Int, y: Int, dx: Int, dy: Int, trialBoard: String): String {
val newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx
if (trialBoard[newBoxPos] != ' ') return ""
val trial = trialBoard.toCharArray()
trial[y * nCols + x] = ' '
trial[(y + dy) * nCols + x + dx] = '@'
trial[newBoxPos] = '$'
return String(trial)
}
fun isSolved(trialBoard: String): Boolean {
for (i in 0 until trialBoard.length) {
if ((destBoard[i] == '.') != (trialBoard[i] == '$')) return false
}
return true
}
fun solve(): String {
data class Board(val cur: String, val sol: String, val x: Int, val y: Int)
val dirLabels = listOf('u' to 'U', 'r' to 'R', 'd' to 'D', 'l' to 'L')
val dirs = listOf(0 to -1, 1 to 0, 0 to 1, -1 to 0)
val history = mutableSetOf<String>()
history.add(currBoard)
val open = LinkedList<Board>()
open.add(Board(currBoard, "", playerX, playerY))
while (!open.isEmpty()) {
val (cur, sol, x, y) = open.poll()
for (i in 0 until dirs.size) {
var trial = cur
val dx = dirs[i].first
val dy = dirs[i].second
// are we standing next to a box ?
if (trial[(y + dy) * nCols + x + dx] == '$') {
// can we push it ?
trial = push(x, y, dx, dy, trial)
if (!trial.isEmpty()) {
// or did we already try this one ?
if (trial !in history) {
val newSol = sol + dirLabels[i].second
if (isSolved(trial)) return newSol
open.add(Board(trial, newSol, x + dx, y + dy))
history.add(trial)
}
}
} // otherwise try changing position
else {
trial = move(x, y, dx, dy, trial)
if (!trial.isEmpty() && trial !in history) {
val newSol = sol + dirLabels[i].first
open.add(Board(trial, newSol, x + dx, y + dy))
history.add(trial)
}
}
}
}
return "No solution"
}
}
fun main(args: Array<String>) {
val level = listOf(
"#######",
"# #",
"# #",
"#. # #",
"#. $$ #",
"#.$$ #",
"#.# @#",
"#######"
)
println(level.joinToString("\n"))
println()
println(Sokoban(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
| #Lua | Lua |
local p1, p1W = ".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8
local p2, p2W = ".....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.....", 13
local puzzle, movesCnt, wid = {}, 0, 0
local moves = { { -1, -2 }, { 1, -2 }, { -1, 2 }, { 1, 2 },
{ -2, -1 }, { -2, 1 }, { 2, -1 }, { 2, 1 } }
function isValid( x, y )
return( x > 0 and x <= wid and y > 0 and y <= wid and puzzle[x + y * wid - wid] == 0 )
end
function solve( x, y, s )
if s > movesCnt then return true end
local test, a, b
for i = 1, #moves do
test = false
a = x + moves[i][1]; b = y + moves[i][2]
if isValid( a, b ) then
puzzle[a + b * wid - wid] = s
if solve( a, b, s + 1 ) then return true end
puzzle[a + b * wid - wid] = 0
end
end
return false
end
function printSolution()
local lp
for j = 1, wid do
for i = 1, wid do
lp = puzzle[i + j * wid - wid]
if lp == -1 then io.write( " " )
else io.write( string.format( " %.2d", lp ) )
end
end
print()
end
print( "\n" )
end
local sx, sy
function fill( pz, w )
puzzle = {}; wid = w; movesCnt = #pz
local lp
for i = 1, #pz do
lp = pz:sub( i, i )
if lp == "x" then
table.insert( puzzle, 0 )
elseif lp == "." then
table.insert( puzzle, -1 ); movesCnt = movesCnt - 1
else
table.insert( puzzle, 1 )
sx = 1 + ( i - 1 ) % wid; sy = math.floor( ( i + wid - 1 ) / wid )
end
end
end
-- [[ entry point ]] --
print( "\n\n" ); fill( p1, p1W );
if solve( sx, sy, 2 ) then printSolution() end
print( "\n\n" ); fill( p2, p2W );
if solve( sx, sy, 2 ) then printSolution() end
|
http://rosettacode.org/wiki/Solve_a_Hopido_puzzle | Solve a Hopido puzzle | Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following:
"Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7×7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!"
Knowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds.
Example:
. 0 0 . 0 0 .
0 0 0 0 0 0 0
0 0 0 0 0 0 0
. 0 0 0 0 0 .
. . 0 0 0 . .
. . . 0 . . .
Extra credits are available for other interesting designs.
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 Numbrix puzzle
Solve the no connection puzzle
| #Wren | Wren | import "/sort" for Sort
import "/fmt" for Fmt
var board = [
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0..."
]
var moves = [
[-3, 0], [0, 3], [ 3, 0], [ 0, -3],
[ 2, 2], [2, -2], [-2, 2], [-2, -2]
]
var grid = []
var totalToFill = 0
var countNeighbors = Fn.new { |r, c|
var num = 0
for (m in moves) if (grid[r + m[1]][c + m[0]] == 0) num = num + 1
return num
}
var neighbors = Fn.new { |r, c|
var nbrs = []
for (m in moves) {
var x = m[0]
var y = m[1]
if (grid[r + y][c + x] == 0) {
var num = countNeighbors.call(r + y, c + x) - 1
nbrs.add([r + y, c + x, num])
}
}
return nbrs
}
var solve // recursive
solve = Fn.new { |r, c, count|
if (count > totalToFill) return true
var nbrs = neighbors.call(r, c)
if (nbrs.isEmpty && count != totalToFill) return false
var cmp = Fn.new { |n1, n2| (n1[2] - n2[2]).sign }
Sort.insertion(nbrs, cmp) // stable sort
for (nb in nbrs) {
var rr = nb[0]
var cc = nb[1]
grid[rr][cc] = count
if (solve.call(rr, cc, count + 1)) return true
grid[rr][cc] = 0
}
return false
}
var printResult = Fn.new {
for (row in grid) {
for (i in row) {
if (i == -1) {
System.write(" ")
} else {
Fmt.write("$2d ", i)
}
}
System.print()
}
}
var nRows = board.count + 6
var nCols = board[0].count + 6
grid = List.filled(nRows, null)
for (r in 0...nRows) {
grid[r] = List.filled(nCols, -1)
for (c in 3...nCols - 3) {
if (r >= 3 && r < nRows - 3) {
if (board[r - 3][c - 3] == "0") {
grid[r][c] = 0
totalToFill = totalToFill + 1
}
}
}
}
var pos = -1
var r
var c
while (true) {
while (true) {
pos = pos + 1
r = (pos / nCols).truncate
c = pos % nCols
if (grid[r][c] != -1) break
}
grid[r][c] = 1
if (solve.call(r, c, 2)) break
grid[r][c] = 0
if (pos >= nRows * nCols) break
}
printResult.call() |
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Sort an array of composite structures by a key.
For example, if you define a composite structure that presents a name-value pair (in pseudo-code):
Define structure pair such that:
name as a string
value as a string
and an array of such pairs:
x: array of pairs
then define a sort routine that sorts the array x by the key name.
This task can always be accomplished with Sorting Using a Custom Comparator.
If your language is not listed here, please see the other article.
| #F.23 | F# | let persons = [| ("Joe", 120); ("foo", 31); ("bar", 51) |]
Array.sortInPlaceBy fst persons
printfn "%A" persons |
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.
| #Factor | Factor | TUPLE: example-pair name value ;
: sort-by-name ( seq -- seq' ) [ [ name>> ] compare ] sort ; |
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).
| #Kotlin | Kotlin | // version 1.2.0
import kotlin.math.abs
// Holes A=0, B=1, …, H=7
// With connections:
const val conn = """
A B
/|\ /|\
/ | X | \
/ |/ \| \
C - D - E - F
\ |\ /| /
\ | X | /
\|/ \|/
G H
"""
val connections = listOf(
0 to 2, 0 to 3, 0 to 4, // A to C, D, E
1 to 3, 1 to 4, 1 to 5, // B to D, E, F
6 to 2, 6 to 3, 6 to 4, // G to C, D, E
7 to 3, 7 to 4, 7 to 5, // H to D, E, F
2 to 3, 3 to 4, 4 to 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.
fun isValid(pegs: IntArray): Boolean {
for ((a, b) in connections) {
if (abs(pegs[a] - pegs[b]) <= 1) return false
}
return true
}
fun swap(pegs: IntArray, i: Int, j: Int) {
val 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.
fun solve(): Triple<IntArray, Int, Int> {
val pegs = IntArray(8) { it + 1 }
var tests = 0
var swaps = 0
fun recurse(i: Int): Boolean {
if (i >= pegs.size - 1) {
tests++
return isValid(pegs)
}
// Try each remaining peg from pegs[i] onwards
for (j in i until pegs.size) {
swaps++
swap(pegs, i, j)
if (recurse(i + 1)) return true
swap(pegs, i, j)
}
return false
}
recurse(0)
return Triple(pegs, tests, swaps)
}
fun pegsAsString(pegs: IntArray): String {
val ca = conn.toCharArray()
for ((i, c) in ca.withIndex()) {
if (c in 'A'..'H') ca[i] = '0' + pegs[c - 'A']
}
return String(ca)
}
fun main(args: Array<String>) {
val (p, tests, swaps) = solve()
println(pegsAsString(p))
println("Tested $tests positions and did $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.
| #FreeBASIC | FreeBASIC | ' version 11-03-2016
' compile with: fbc -s console
#Include Once "crt/stdlib.bi" ' needed for qsort subroutine
' Declare Sub qsort (ByVal As Any Ptr, <== point to start of array
' ByVal As size_t, <== size of array
' ByVal As size_t, <== size of array element
' ByVal As Function(ByVal As Any Ptr, ByVal As Any Ptr) As Long) <== callback function
' declare callback function with Cdecl to ensures that the parameters are passed in the correct order
'
' size of long: 4 bytes on 32bit OS, 8 bytes on 64bit OS
' ascending
Function callback Cdecl (ByVal element1 As Any Ptr, ByVal element2 As Any Ptr) As Long
Function = *Cast(Long Ptr, element1) - *Cast(Long Ptr, element2)
End Function
' Function callback Cdecl (ByVal element1 As Any Ptr, ByVal element2 As Any Ptr) As Long
' Dim As Long e1 = *Cast(Long Ptr, element1)
' Dim As Long e2 = *Cast(Long Ptr, element2)
' Dim As Long result = Sgn(e1 - e2)
' If Sgn(e1) = -1 And Sgn(e2) = -1 Then result = -result
' Function = result
' End Function
' ------=< MAIN >=------
Dim As Long i, array(20)
Dim As Long lb = LBound(array)
Dim As Long ub = UBound(array)
For i = lb To ub ' fill array
array(i) = 10 - i
Next
Print
Print "unsorted array"
For i = lb To ub ' display array
Print Using "###";array(i);
Next
Print : Print
' sort array
qsort(@array(lb), ub - lb +1, SizeOf(array), @callback)
Print "sorted array"
For i = lb To ub ' show sorted array
Print Using "###";array(i);
Next
Print
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers | Sort a list of object identifiers |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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
Object identifiers (OID)
Task
Show how to sort a list of OIDs, in their natural sort order.
Details
An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number.
Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields.
Test case
Input (list of strings)
Output (list of strings)
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11150.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11150.3.4.0
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11150.3.4.0
1.3.6.1.4.1.11150.3.4.0.1
Related tasks
Natural sorting
Sort using a custom comparator
| #REXX | REXX | /*REXX program performs a sort of OID (Object IDentifiers ◄── used in Network data).*/
call gen /*generate an array (@.) from the OIDs.*/
call show 'before sort ───► ' /*display the @ array before sorting.*/
say copies('░', 79) /* " fence, separate before & after*/
call adj 1 /*expand the $ list of OID numbers. */
call bSort # /*sort " " " " " " */
call adj 0 /*shrink " " " " " " */
call show ' after sort ───► ' /*display the @ array after sorting. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
bSort: procedure expose @.; parse arg n; m=n-1 /*N: is the number of @ array elements.*/
do m=m for m by -1 until ok; ok= 1 /*keep sorting the @ array until done. */
do j=1 for m; _= j + 1 /*calculate the next (index) in @ array*/
if @.j>@._ then parse value @.j @._ 0 with @._ @.j ok
end /*j*/ /* [↑] swap two out─of─order elements.*/
end /*m*/ /* [↑] use a simple bubble sort. */
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
gen: $= 1.3.6.1.4.1.11.2.17.19.3.4.0.10 , /* ◄──┐ */
1.3.6.1.4.1.11.2.17.5.2.0.79 , /* ◄──┤ */
1.3.6.1.4.1.11.2.17.19.3.4.0.4 , /* ◄──┼─◄─ six OID numbers (as a list).*/
1.3.6.1.4.1.11150.3.4.0.1 , /* ◄──┤ */
1.3.6.1.4.1.11.2.17.19.3.4.0.1 , /* ◄──┤ */
1.3.6.1.4.1.11150.3.4.0 /* ◄──┘ */
w= 0 /*W: max length of #'s.*/
#= words($); do i=1 for #; @.i= word($, i); w= max(w, length(@.i) )
end /*i*/ /*W: max length of #'s.*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
adj: arg LZ; do j=1 for #; x= translate(@.j, , .); y= /*construct X version. */
do k=1 for words(x); _= word(x, k) /*get a number in X. */
if LZ then y= y right(_, w, 0) /*(prepend) leading 0's*/
else y= y (_ + 0) /* (elide) " " */
end /*k*/
@.j = translate( space(y), ., ' ') /*reconstitute number. */
end /*j*/ /*LZ: Leading Zero(s).*/
return /*── ─ ─ */
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: do a=1 for #; say right("OID number",20) right(a,length(#)) arg(1) @.a; end; return |
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
| #Ksh | Ksh |
#!/bin/ksh
# Sort disjoint sublist
# # Variables:
#
typeset -a arr_Val=( 7 6 5 4 3 2 1 0 )
typeset -a arr_Ind=( 6 1 7 )
integer i
# # Functions:
#
# # Function _insertionSort(array) - Insertion sort of array of integers
#
function _insertionSort {
typeset _arr ; nameref _arr="$1"
typeset _i _j _val ; integer _i _j _val
for (( _i=1; _i<${#_arr[*]}; _i++ )); do
_val=${_arr[_i]}
(( _j = _i - 1 ))
while (( _j>=0 && _arr[_j]>_val )); do
_arr[_j+1]=${_arr[_j]}
(( _j-- ))
done
_arr[_j+1]=${_val}
done
}
######
# main #
######
print "Before sort: ${arr_Val[*]}"
typeset -a arr_2sort
for ((i=0; i<${#arr_Ind[*]}; i++)); do
arr_2sort+=( ${arr_Val[${arr_Ind[i]}]} )
done
_insertionSort arr_2sort # Sort the chosen values
_insertionSort arr_Ind # Sort the indices
for ((i=0; i<${#arr_Ind[*]}; i++)); do
arr_Val[${arr_Ind[i]}]=${arr_2sort[i]}
done
print "After sort: ${arr_Val[*]}" |
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
| #Lua | Lua | values = { 7, 6, 5, 4, 3, 2, 1, 0 }
indices = { 6, 1, 7 }
i = 1 -- discard duplicates
while i < #indices do
j = i + 1
while j < #indices do
if indices[i] == indices[j] then
table.remove( indices[j] )
end
j = j + 1
end
i = i + 1
end
for i = 1, #indices do
indices[i] = indices[i] + 1 -- the tables of lua are one-based
end
vals = {}
for i = 1, #indices do
vals[i] = values[ indices[i] ]
end
table.sort( vals )
table.sort( indices )
for i = 1, #indices do
values[ indices[i] ] = vals[i]
end
for i = 1, #values do
io.write( values[i], " " )
end |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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 (the values of) three variables (X, Y, and Z) that contain any value (numbers and/or literals).
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other).
I.E.: (for the three variables x, y, and z), where:
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
After sorting, the three variables would hold:
x = '(from the "Wizard of OZ")'
y = 'bears, oh my!'
z = 'lions, tigers, and'
For numeric value sorting, use:
I.E.: (for the three variables x, y, and z), where:
x = 77444
y = -12
z = 0
After sorting, the three variables would hold:
x = -12
y = 0
z = 77444
The variables should contain some form of a number, but specify if the algorithm
used can be for floating point or integers. Note any limitations.
The values may or may not be unique.
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used.
More than one algorithm could be shown if one isn't clearly the better choice.
One algorithm could be:
• store the three variables x, y, and z
into an array (or a list) A
• sort (the three elements of) the array A
• extract the three elements from the array and place them in the
variables x, y, and z in order of extraction
Another algorithm (only for numeric values):
x= 77444
y= -12
z= 0
low= x
mid= y
high= z
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */
z= max(low, mid, high) /* " " highest " " " " " */
y= low + mid + high - x - z /* " " middle " " " " " */
Show the results of the sort here on this page using at least the values of those shown above.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: genSort3 (in type: elemType) is func
begin
global
const proc: doSort3 (in var elemType: x, in var elemType: y, in var elemType: z) is func
local
var array elemType: sorted is 0 times elemType.value;
begin
writeln("BEFORE: x=[" <& x <& "]; y=[" <& y <& "]; z=[" <& z <& "]");
sorted := sort([](x, y, z));
x := sorted[1];
y := sorted[2];
z := sorted[3];
writeln("AFTER: x=[" <& x <& "]; y=[" <& y <& "]; z=[" <& z <& "]");
end func;
end global;
end func;
genSort3(integer);
genSort3(string);
const proc: main is func
begin
doSort3(77444, -12, 0);
doSort3("lions, tigers, and", "bears, oh my!", "(from the \"Wizard of OZ\")");
end func; |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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 (the values of) three variables (X, Y, and Z) that contain any value (numbers and/or literals).
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other).
I.E.: (for the three variables x, y, and z), where:
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
After sorting, the three variables would hold:
x = '(from the "Wizard of OZ")'
y = 'bears, oh my!'
z = 'lions, tigers, and'
For numeric value sorting, use:
I.E.: (for the three variables x, y, and z), where:
x = 77444
y = -12
z = 0
After sorting, the three variables would hold:
x = -12
y = 0
z = 77444
The variables should contain some form of a number, but specify if the algorithm
used can be for floating point or integers. Note any limitations.
The values may or may not be unique.
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used.
More than one algorithm could be shown if one isn't clearly the better choice.
One algorithm could be:
• store the three variables x, y, and z
into an array (or a list) A
• sort (the three elements of) the array A
• extract the three elements from the array and place them in the
variables x, y, and z in order of extraction
Another algorithm (only for numeric values):
x= 77444
y= -12
z= 0
low= x
mid= y
high= z
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */
z= max(low, mid, high) /* " " highest " " " " " */
y= low + mid + high - x - z /* " " middle " " " " " */
Show the results of the sort here on this page using at least the values of those shown above.
| #SenseTalk | SenseTalk | Set x to "lions, tigers and"
Set y to "bears, oh my!"
Set z to "(from the Wizard of Oz)"
log x
log y
log z
set RosettaListAlpha to (x,y,z)
log RosettaListAlpha
sort RosettaListAlpha alphabetically
log RosettaListAlpha
LogSuccess "Alphabetical Sort Successful"
set (x,y,z) to RosettaListAlpha
log x
log y
log z
LogSuccess "Sorted Items back into Original Variables"
Set a to "77444"
set b to "-12"
set c to "0"
set d to "62224"
set RosettaListNum to (a,b,c,d)
log RosettaListNum
sort RosettaListNum numerically
log RosettaListNum
LogSuccess "Numerical Sort Successful"
set (a,b,c,d) to RosettaListNum
log a
log b
log c
log d
LogSuccess "Sorted Numbers back into Original Variables" |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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 (the values of) three variables (X, Y, and Z) that contain any value (numbers and/or literals).
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other).
I.E.: (for the three variables x, y, and z), where:
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
After sorting, the three variables would hold:
x = '(from the "Wizard of OZ")'
y = 'bears, oh my!'
z = 'lions, tigers, and'
For numeric value sorting, use:
I.E.: (for the three variables x, y, and z), where:
x = 77444
y = -12
z = 0
After sorting, the three variables would hold:
x = -12
y = 0
z = 77444
The variables should contain some form of a number, but specify if the algorithm
used can be for floating point or integers. Note any limitations.
The values may or may not be unique.
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used.
More than one algorithm could be shown if one isn't clearly the better choice.
One algorithm could be:
• store the three variables x, y, and z
into an array (or a list) A
• sort (the three elements of) the array A
• extract the three elements from the array and place them in the
variables x, y, and z in order of extraction
Another algorithm (only for numeric values):
x= 77444
y= -12
z= 0
low= x
mid= y
high= z
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */
z= max(low, mid, high) /* " " highest " " " " " */
y= low + mid + high - x - z /* " " middle " " " " " */
Show the results of the sort here on this page using at least the values of those shown above.
| #Sidef | Sidef | func sort_refs(*arr) {
arr.map{ *_ }.sort ~Z arr -> each { *_[1] = _[0] }
}
var x = 77444
var y = -12
var z = 0
sort_refs(\x, \y, \z)
say x
say y
say z |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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.
| #Ol | Ol |
(import (scheme char))
(define (comp a b)
(let ((la (string-length a))
(lb (string-length b)))
(or
(> la lb)
(and (= la lb) (string-ci<? a b)))))
(print
(sort comp '(
"lorem" "ipsum" "dolor" "sit" "amet" "consectetur"
"adipiscing" "elit" "maecenas" "varius" "sapien"
"vel" "purus" "hendrerit" "vehicula" "integer"
"hendrerit" "viverra" "turpis" "ac" "sagittis"
"arcu" "pharetra" "id")))
|
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort | Sorting algorithms/Bogosort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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
Bogosort a list of numbers.
Bogosort simply shuffles a collection randomly until it is sorted.
"Bogosort" is a perversely inefficient algorithm only used as an in-joke.
Its average run-time is O(n!) because the chance that any given shuffle of a set will end up in sorted order is about one in n factorial, and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence.
Its best case is O(n) since a single pass through the elements may suffice to order them.
Pseudocode:
while not InOrder(list) do
Shuffle(list)
done
The Knuth shuffle may be used to implement the shuffle part of this algorithm.
| #Ursala | Ursala | #import std
#import nat
shuffle = @iNX ~&l->r ^jrX/~&l ~&lK8PrC
bogosort = (not ordered nleq)-> shuffle
#cast %nL
example = bogosort <8,50,0,12,47,51> |
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.
| #Forth | Forth | defer bubble-test
' > is bubble-test
: bubble { addr cnt -- }
cnt 1 do
addr cnt i - cells bounds do
i 2@ bubble-test if i 2@ swap i 2! then
cell +loop
loop ; |
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.
| #Phix | Phix | with javascript_semantics
function gnomeSort(sequence s)
integer i = 1, j = 2
while i<length(s) do
object si = s[i],
sn = s[i+1]
if si<=sn then
i = j
j += 1
else
s[i] = sn
s[i+1] = si
i -= 1
if i = 0 then
i = j
j += 1
end if
end if
end while
return s
end function
?gnomeSort(shuffle(tagset(10)))
|
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
| #ooRexx | ooRexx | /* Rexx */
placesList = .array~of( -
"UK London", "US New York" , "US Boston", "US Washington" -
, "UK Washington", "US Birmingham" , "UK Birmingham", "UK Boston" -
)
sortedList = cocktailSort(placesList~allItems())
lists = .array~of(placesList, sortedList)
loop ln = 1 to lists~items()
cl = lists[ln]
loop ct = 1 to cl~items()
say cl[ct]
end ct
say
end ln
return
exit
::routine cocktailSort
use arg A
Alength = A~items()
swapped = .false
loop label swaps until \swapped
swapped = .false
loop i_ = 1 to Alength - 1
if A[i_] > A[i_ + 1] then do
swap = A[i_ + 1]
A[i_ + 1] = A[i_]
A[i_] = swap
swapped = .true
end
end i_
if \swapped then do
leave swaps
end
swapped = .false
loop i_ = Alength - 1 to 1 by -1
if A[i_] > A[i_ + 1] then do
swap = A[i_ + 1]
A[i_ + 1] = A[i_]
A[i_] = swap
swapped = .true
end
end i_
end swaps
return A |
http://rosettacode.org/wiki/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #Elixir | Elixir |
defmodule Sockets do
require Logger
def send_message(port, message) do
{:ok, socket} = :gen_tcp.connect('localhost', port, [])
:gen_tcp.send(socket, message)
end
end
Sockets.send_message(256, "hello socket world")
|
http://rosettacode.org/wiki/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #Emacs_Lisp | Emacs Lisp | (let ((proc (make-network-process :name "my sock"
:host 'local ;; or hostname string
:service 256)))
(process-send-string proc "hello socket world")
(delete-process proc)) |
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss.
If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to
estimate the probability that the coin toss was heads. Her estimate is recorded and she is
then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied.
If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to
estimate the probability the coin toss was heads, but is then given a drug which makes her forget
that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day
later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss
was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday.
Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always
estimate the probability of heads as 1/2, since she does not have any additional information. Others
have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice
as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate
should be 1/3 heads.
Task
Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the
proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty
is asked the question.
| #Phix | Phix | constant iterations = 1_000_000,
fmt = """
Wakings over %,d repetitions = %,d
Percentage probability of heads on waking = %f%%
"""
integer heads = 0, wakings = 0
for i=1 to iterations do
integer flip = rand(2) -- 1==heads, 2==tails
wakings += 1 + (flip==2)
heads += (flip==1)
end for
printf(1,fmt,{iterations,wakings,heads/wakings*100})
|
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss.
If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to
estimate the probability that the coin toss was heads. Her estimate is recorded and she is
then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied.
If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to
estimate the probability the coin toss was heads, but is then given a drug which makes her forget
that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day
later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss
was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday.
Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always
estimate the probability of heads as 1/2, since she does not have any additional information. Others
have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice
as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate
should be 1/3 heads.
Task
Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the
proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty
is asked the question.
| #Python | Python | from random import choice
def sleeping_beauty_experiment(repetitions):
"""
Run the Sleeping Beauty Problem experiment `repetitions` times, checking to see
how often we had heads on waking Sleeping Beauty.
"""
gotheadsonwaking = 0
wakenings = 0
for _ in range(repetitions):
coin_result = choice(["heads", "tails"])
# On Monday, we check if we got heads.
wakenings += 1
if coin_result == "heads":
gotheadsonwaking += 1
# If tails, we do this again, but of course we will not add as if it was heads..
if coin_result == "tails":
wakenings += 1
if coin_result == "heads":
gotheadsonwaking += 1 # never done
# Show the number of times she was wakened.
print("Wakenings over", repetitions, "experiments:", wakenings)
# Return the number of correct bets SB made out of the total number
# of times she is awoken over all the experiments with that bet.
return gotheadsonwaking / wakenings
CREDENCE = sleeping_beauty_experiment(1_000_000)
print("Results of experiment: Sleeping Beauty should estimate a credence of:", CREDENCE)
|
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
| #Go | Go | package main
import (
"fmt"
"math/big"
)
var b = new(big.Int)
func isSPDSPrime(n uint64) bool {
nn := n
for nn > 0 {
r := nn % 10
if r != 2 && r != 3 && r != 5 && r != 7 {
return false
}
nn /= 10
}
b.SetUint64(n)
if b.ProbablyPrime(0) { // 100% accurate up to 2 ^ 64
return true
}
return false
}
func listSPDSPrimes(startFrom, countFrom, countTo uint64, printOne bool) uint64 {
count := countFrom
for n := startFrom; ; n += 2 {
if isSPDSPrime(n) {
count++
if !printOne {
fmt.Printf("%2d. %d\n", count, n)
}
if count == countTo {
if printOne {
fmt.Println(n)
}
return n
}
}
}
}
func main() {
fmt.Println("The first 25 terms of the Smarandache prime-digital sequence are:")
fmt.Println(" 1. 2")
n := listSPDSPrimes(3, 1, 25, false)
fmt.Println("\nHigher terms:")
indices := []uint64{25, 100, 200, 500, 1000, 2000, 5000, 10000, 20000, 50000, 100000}
for i := 1; i < len(indices); i++ {
fmt.Printf("%6d. ", indices[i])
n = listSPDSPrimes(n+2, indices[i-1], indices[i], true)
}
} |
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.
| #AutoHotkey | AutoHotkey | gosub Init
Gui, +AlwaysOnTop
Gui, font, s12, consolas
Gui, add, Edit, vEditGrid x10 y10 ReadOnly, % grid2Text(oGrid)
Gui, add, Text, vScore x10 y+10 w200 ReadOnly, % "Your Score = " Score
Gui, show,, Snake
GuiControl, Focus, Score
return
;-----------------------------------------
Init:
Width := 100, Height := 30 ; set grid size
tail := 20, step := 10
Timer := 75
item := 0, direction := ""
oTrail := [], Score := 0
xx := generateGrid(width, Height)
oGrid := xx.1
row := xx.2, col := xx.3
return
;-----------------------------------------
Move:
if !item
{
loop
{
Random, itemC, 3, % width-2
Random, itemR, 3, % Height-2
}
until, !oGrid[itemR, itemC]
oGrid[itemR, itemC] := "@"
item := true
}
gosub, crawl
return
;-----------------------------------------
#IfWinActive, Snake
left::
Right::
up::
Down::
if ((A_ThisHotkey = "right") && (Direction = "left"))
|| ((A_ThisHotkey = "left") && (Direction = "right"))
|| ((A_ThisHotkey = "up") && (Direction = "Down"))
|| ((A_ThisHotkey = "Down") && (Direction = "up"))
|| ((A_ThisHotkey = "right") && (Direction = "right"))
|| ((A_ThisHotkey = "left") && (Direction = "left"))
|| ((A_ThisHotkey = "up") && (Direction = "up"))
|| ((A_ThisHotkey = "Down") && (Direction = "Down"))
return
Direction := A_ThisHotkey
gosub, crawl
return
#IfWinActive
;-----------------------------------------
crawl:
switch, Direction
{
case "left" : oGrid[row , col--] := 1
case "Right" : oGrid[row , col++] := 1
case "up" : oGrid[row--, col ] := 1
case "Down" : oGrid[row++, col ] := 1
}
; out of bounds or snake eats itself
if oGrid[row, col] = 1 || col < 1 || col > width || row < 1 || row > height
gosub, YouLose
; snake eats item
if (oGrid[row, col] = "@")
{
item := false
tail += step
GuiControl,, Score, % "Your Score = " ++Score
}
; snake advances
oGrid[row, col] := 2
oTrail.Push(row "," col)
if (oTrail.count() >= tail)
x := StrSplit(oTrail.RemoveAt(1), ","), oGrid[x.1, x.2] := false
GuiControl,, EditGrid, % grid2Text(oGrid)
SetTimer, Move, % 0-Timer
return
;-----------------------------------------
YouLose:
SetTimer, Move, Off
MsgBox, 262180, ,% "Your Score is " Score "`nPlay Again?"
IfMsgBox, No
ExitApp
gosub Init
GuiControl,, EditGrid, % grid2Text(oGrid)
return
;-----------------------------------------
grid2Text(oGrid){
for row, obj in oGrid {
for col, val in obj ; @=item, 2=Head, 1=tail
text .= val = "@" ? "@" : val =2 ? "█" : val = 1 ? "▓" : " "
text .= "`n"
}
return trim(text, "`n")
}
;-----------------------------------------
generateGrid(width, Height){
global oTrail
oGrid := []
loop, % width
{
col := A_Index
loop, % Height
row := A_Index, oGrid[row, col] := false
}
Random, col, 3, % width-2
Random, row, 3, % Height-2
oGrid[row, col] := 2
oTrail.Push(row "," col)
return [oGrid, row, col]
}
;----------------------------------------- |
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].
| #Ada | Ada |
with Ada.Text_IO;
procedure smith is
type Vector is array (natural range <>) of Positive;
empty_vector : constant Vector(1..0):= (others=>1);
function digits_sum (n : Positive) return Positive is
(if n < 10 then n else n mod 10 + digits_sum (n / 10));
function prime_factors (n : Positive; d : Positive := 2) return Vector is
(if n = 1 then empty_vector elsif n mod d = 0 then prime_factors (n / d, d) & d
else prime_factors (n, d + (if d=2 then 1 else 2)));
function vector_digits_sum (v : Vector) return Natural is
(if v'Length = 0 then 0 else digits_sum (v(v'First)) + vector_digits_sum (v(v'First+1..v'Last)));
begin
for n in 1..10000 loop
declare
primes : Vector := prime_factors (n);
begin
if primes'Length > 1 and then vector_digits_sum (primes) = digits_sum (n) then
Ada.Text_IO.put (n'img);
end if;
end;
end loop;
end smith;
|
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle | Solve a Hidato puzzle | The task is to write a program which solves Hidato (aka Hidoku) puzzles.
The rules are:
You are given a grid with some numbers placed in it. The other squares in the grid will be blank.
The grid is not necessarily rectangular.
The grid may have holes in it.
The grid is always connected.
The number “1” is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique.
It may be assumed that the difference between numbers present on the grid is not greater than lucky 13.
The aim is to place a natural number in each blank square so that in the sequence of numbered squares from “1” upwards, each square is in the wp:Moore neighborhood of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints).
Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order.
A square may only contain one number.
In a proper Hidato puzzle, the solution is unique.
For example the following problem
has the following solution, with path marked on it:
Related tasks
A* search algorithm
N-queens problem
Solve a Holy Knight's tour
Solve a Knight's tour
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle;
| #C.2B.2B | C++ |
#include <iostream>
#include <sstream>
#include <iterator>
#include <vector>
//------------------------------------------------------------------------------
using namespace std;
//------------------------------------------------------------------------------
struct node
{
int val;
unsigned char neighbors;
};
//------------------------------------------------------------------------------
class hSolver
{
public:
hSolver()
{
dx[0] = -1; dx[1] = 0; dx[2] = 1; dx[3] = -1; dx[4] = 1; dx[5] = -1; dx[6] = 0; dx[7] = 1;
dy[0] = -1; dy[1] = -1; dy[2] = -1; dy[3] = 0; dy[4] = 0; dy[5] = 1; dy[6] = 1; dy[7] = 1;
}
void solve( vector<string>& puzz, int max_wid )
{
if( puzz.size() < 1 ) return;
wid = max_wid; hei = static_cast<int>( puzz.size() ) / wid;
int len = wid * hei, c = 0; max = 0;
arr = new node[len]; memset( arr, 0, len * sizeof( node ) );
weHave = new bool[len + 1]; memset( weHave, 0, len + 1 );
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "*" ) { arr[c++].val = -1; continue; }
arr[c].val = atoi( ( *i ).c_str() );
if( arr[c].val > 0 ) weHave[arr[c].val] = true;
if( max < arr[c].val ) max = arr[c].val;
c++;
}
solveIt(); c = 0;
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) == "." )
{
ostringstream o; o << arr[c].val;
( *i ) = o.str();
}
c++;
}
delete [] arr;
delete [] weHave;
}
private:
bool search( int x, int y, int w )
{
if( w == max ) return true;
node* n = &arr[x + y * wid];
n->neighbors = getNeighbors( x, y );
if( weHave[w] )
{
for( int d = 0; d < 8; d++ )
{
if( n->neighbors & ( 1 << d ) )
{
int a = x + dx[d], b = y + dy[d];
if( arr[a + b * wid].val == w )
if( search( a, b, w + 1 ) ) return true;
}
}
return false;
}
for( int d = 0; d < 8; d++ )
{
if( n->neighbors & ( 1 << d ) )
{
int a = x + dx[d], b = y + dy[d];
if( arr[a + b * wid].val == 0 )
{
arr[a + b * wid].val = w;
if( search( a, b, w + 1 ) ) return true;
arr[a + b * wid].val = 0;
}
}
}
return false;
}
unsigned char getNeighbors( int x, int y )
{
unsigned char c = 0; int m = -1, a, b;
for( int yy = -1; yy < 2; yy++ )
for( int xx = -1; xx < 2; xx++ )
{
if( !yy && !xx ) continue;
m++; a = x + xx, b = y + yy;
if( a < 0 || b < 0 || a >= wid || b >= hei ) continue;
if( arr[a + b * wid].val > -1 ) c |= ( 1 << m );
}
return c;
}
void solveIt()
{
int x, y; findStart( x, y );
if( x < 0 ) { cout << "\nCan't find start point!\n"; return; }
search( x, y, 2 );
}
void findStart( int& x, int& y )
{
for( int b = 0; b < hei; b++ )
for( int a = 0; a < wid; a++ )
if( arr[a + wid * b].val == 1 ) { x = a; y = b; return; }
x = y = -1;
}
int wid, hei, max, dx[8], dy[8];
node* arr;
bool* weHave;
};
//------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
int wid;
string p = ". 33 35 . . * * * . . 24 22 . * * * . . . 21 . . * * . 26 . 13 40 11 * * 27 . . . 9 . 1 * * * . . 18 . . * * * * * . 7 . . * * * * * * 5 ."; wid = 8;
//string p = "54 . 60 59 . 67 . 69 . . 55 . . 63 65 . 72 71 51 50 56 62 . * * * * . . . 14 * * 17 . * 48 10 11 * 15 . 18 . 22 . 46 . * 3 . 19 23 . . 44 . 5 . 1 33 32 . . 43 7 . 36 . 27 . 31 42 . . 38 . 35 28 . 30"; wid = 9;
//string p = ". 58 . 60 . . 63 66 . 57 55 59 53 49 . 65 . 68 . 8 . . 50 . 46 45 . 10 6 . * * * . 43 70 . 11 12 * * * 72 71 . . 14 . * * * 30 39 . 15 3 17 . 28 29 . . 40 . . 19 22 . . 37 36 . 1 20 . 24 . 26 . 34 33"; wid = 9;
istringstream iss( p ); vector<string> puzz;
copy( istream_iterator<string>( iss ), istream_iterator<string>(), back_inserter<vector<string> >( puzz ) );
hSolver s; s.solve( puzz, wid );
int c = 0;
for( vector<string>::iterator i = puzz.begin(); i != puzz.end(); i++ )
{
if( ( *i ) != "*" && ( *i ) != "." )
{
if( atoi( ( *i ).c_str() ) < 10 ) cout << "0";
cout << ( *i ) << " ";
}
else cout << " ";
if( ++c >= wid ) { cout << endl; c = 0; }
}
cout << endl << endl;
return system( "pause" );
}
//--------------------------------------------------------------------------------------------------
|
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.
| #Nim | Nim | import deques, sets, strutils
type
Sokoban = object
destBoard: string
currBoard: string
nCols: Natural
playerX: Natural
playerY: Natural
Board = tuple[cur, sol: string; x, y: int]
func initSokoban(board: openArray[string]): Sokoban =
result.nCols = board[0].len
for row in 0..board.high:
for col in 0..<result.nCols:
let ch = board[row][col]
result.destBoard.add if ch notin ['$', '@']: ch else: ' '
result.currBoard.add if ch != '.': ch else: ' '
if ch == '@':
result.playerX = col
result.playerY = row
func move(sokoban: Sokoban; x, y, dx, dy: int; trialBoard: string): string =
let newPlayerPos = (y + dy) * sokoban.nCols + x + dx
if trialBoard[newPlayerPos] != ' ': return
result = trialBoard
result[y * sokoban.nCols + x] = ' '
result[newPlayerPos] = '@'
func push(sokoban: Sokoban; x, y, dx, dy: int; trialBoard: string): string =
let newBoxPos = (y + 2 * dy) * sokoban.nCols + x + 2 * dx
if trialBoard[newBoxPos] != ' ': return
result = trialBoard
result[y * sokoban.nCols + x] = ' '
result[(y + dy) * sokoban.nCols + x + dx] = '@'
result[newBoxPos] = '$'
func isSolved(sokoban: Sokoban; trialBoard: string): bool =
for i in 0..trialBoard.high:
if (sokoban.destBoard[i] == '.') != (trialBoard[i] == '$'): return false
result = true
func solve(sokoban: Sokoban): string =
var history: HashSet[string]
history.incl sokoban.currBoard
const Dirs = [(0, -1, 'u', 'U'), (1, 0, 'r', 'R'), (0, 1, 'd', 'D'), (-1, 0, 'l', 'L')]
var open: Deque[Board]
open.addLast (sokoban.currBoard, "", sokoban.playerX, sokoban.playerY)
while open.len != 0:
let (cur, sol, x, y) = open.popFirst()
for dir in Dirs:
var trial = cur
let dx = dir[0]
let dy = dir[1]
# Are we standing next to a box?
if trial[(y + dy) * sokoban.nCols + x + dx] == '$':
# Can we push it?
trial = sokoban.push(x, y, dx, dy, trial)
if trial.len != 0:
# Or did we already try this one?
if trial notin history:
let newSol = sol & dir[3]
if sokoban.isSolved(trial): return newSol
open.addLast (trial, newSol, x + dx, y + dy)
history.incl trial
else:
# Try to change position.
trial = sokoban.move(x, y, dx, dy, trial)
if trial.len != 0 and trial notin history:
let newSol = sol & dir[2]
open.addLast (trial, newSol, x + dx, y + dy)
history.incl trial
result = "no solution"
when isMainModule:
const Level = ["#######",
"# #",
"# #",
"#. # #",
"#. $$ #",
"#.$$ #",
"#.# @#",
"#######"]
echo Level.join("\n")
echo()
echo initSokoban(Level).solve() |
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.
| #OCaml | OCaml | type dir = U | D | L | R
type move_t = Move of dir | Push of dir
let letter = function
| Push(U) -> 'U' | Push(D) -> 'D' | Push(L) -> 'L' | Push(R) -> 'R'
| Move(U) -> 'u' | Move(D) -> 'd' | Move(L) -> 'l' | Move(R) -> 'r'
let cols = ref 0
let delta = function U -> -(!cols) | D -> !cols | L -> -1 | R -> 1
let store = Hashtbl.create 251
let mark t = Hashtbl.replace store t ()
let marked t = Hashtbl.mem store t
let show ml =
List.iter (fun c -> print_char (letter c)) (List.rev ml); print_newline()
let gen_moves (x,boxes) bd =
let empty i = bd.(i) = ' ' && not (List.mem i boxes) in
let check l dir =
let dx = delta dir in
let x1 = x+dx in
if List.mem x1 boxes then (
if empty (x1+dx) then Push(dir) :: l else l
) else (
if bd.(x1) = ' ' then Move(dir) :: l else l
) in
(List.fold_left check [] [U; L; R; D])
let do_move (x,boxes) = function
| Push(d) -> let dx = delta d in
let x1 = x+dx in let x2 = x1+dx in
let rec shift = function
| [] -> failwith "shift"
| h :: t -> if h = x1 then x2 :: t else h :: shift t in
x1, List.fast_sort compare (shift boxes)
| Move(d) -> (x+(delta d)), boxes
let init_pos bd =
let p = ref 0 in
let q = ref [] in
let check i c =
if c = '$' || c = '*' then q := i::!q
else if c = '@' then p := i in (
Array.iteri check bd;
(!p, List.fast_sort compare !q);
)
let final_box bd =
let check (i,l) c = if c = '.' || c = '*' then (i+1,i::l) else (i+1,l) in
List.fast_sort compare (snd (Array.fold_left check (0,[]) bd))
let array_of_input inp =
let r = List.length inp and c = String.length (List.hd inp) in
let a = Array.create (r*c) ' ' in (
for i = 0 to pred r do
let s = List.nth inp i in
for j = 0 to pred c do a.(i*c+j) <- s.[j] done
done;
cols := c; a)
let solve b =
let board = array_of_input b in
let targets = final_box board in
let solved pos = targets = snd pos in
let clear = Array.map (function '#' -> '#' | _ -> ' ') in
let bdc = clear board in
let q = Queue.create () in
let pos1 = init_pos board in
begin
mark pos1;
Queue.add (pos1, []) q;
while not (Queue.is_empty q) do
let curr, mhist = Queue.pop q in
let moves = gen_moves curr bdc in
let check m =
let next = do_move curr m in
if not (marked next) then
if solved next then (show (m::mhist); exit 0)
else (mark next; Queue.add (next,m::mhist) q) in
List.iter check moves
done;
print_endline "No solution"
end;;
let level = ["#######";
"# #";
"# #";
"#. # #";
"#. $$ #";
"#.$$ #";
"#.# @#";
"#######"] in
solve level |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | puzzle = " 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";
puzzle = StringSplit[puzzle, "\n"];
puzzle = StringTake[#, {1, -1, 2}] & /@ puzzle;
pos0 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "0"][[All, 1]], {i, Length@puzzle}];
pos1 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "1"][[All, 1]], {i, Length@puzzle}];
allpoints = Join[pos1, pos0];
validmoves = Select[Subsets[allpoints, {2}], Differences /* Norm /* EqualTo[Sqrt[5]]];
g = Graph[UndirectedEdge @@@ validmoves];
e = VertexList[g];
order = FindShortestTour[g][[2]]
Graphics[{Red, Disk[#, 0.2] & /@ e, Black, BlockMap[Arrow, e[[order]], 2, 1]}] |
http://rosettacode.org/wiki/Solve_a_Hopido_puzzle | Solve a Hopido puzzle | Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Post Mortem contains the following:
"Big puzzles represented another problem. Up until quite late in the project our puzzle solver was painfully slow with most puzzles above 7×7 tiles. Testing the solution from each starting point could take hours. If the tile layout was changed even a little, the whole puzzle had to be tested again. We were just about to give up the biggest puzzles entirely when our programmer suddenly came up with a magical algorithm that cut the testing process down to only minutes. Hooray!"
Knowing the kindness in the heart of every contributor to Rosetta Code, I know that we shall feel that as an act of humanity we must solve these puzzles for them in let's say milliseconds.
Example:
. 0 0 . 0 0 .
0 0 0 0 0 0 0
0 0 0 0 0 0 0
. 0 0 0 0 0 .
. . 0 0 0 . .
. . . 0 . . .
Extra credits are available for other interesting designs.
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 Numbrix puzzle
Solve the no connection puzzle
| #zkl | zkl | hi:= // 0==empty cell, X==not a cell
#<<<
" X 0 0 X 0 0 X
0 0 0 0 0 0 0
0 0 0 0 0 0 0
X 0 0 0 0 0 X
X X 0 0 0 X X
X X X 0 X X X";
#<<<
adjacent:=T( T(-3,0),
T(-2,-2), T(-2,2),
T(0,-3), T(0,3),
T(2,-2), T(2,2),
T(3,0) );
puzzle:=Puzzle(hi,adjacent);
puzzle.print_board();
puzzle.solve();
println();
puzzle.print_board();
println(); |
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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.
| #Fantom | Fantom |
class Pair // create a composite structure
{
Str name
Str value
new make (Str name, Str value)
{
this.name = name
this.value = value
}
override Str toStr ()
{
"(Pair: $name, $value)"
}
}
class Main
{
public static Void main ()
{
// samples
pairs := [Pair("Fantom", "OO"), Pair("Clojure", "Functional"), Pair("Java", "OO") ]
sorted := pairs.dup // make a copy of original list
sorted.sort |Pair a, Pair b -> Int| // sort using custom comparator
{
a.name <=> b.name
}
echo ("Started with : " + pairs.join(" "))
echo ("Finished with: " + sorted.join(" "))
}
}
|
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Sort an array of composite structures by a key.
For example, if you define a composite structure that presents a name-value pair (in pseudo-code):
Define structure pair such that:
name as a string
value as a string
and an array of such pairs:
x: array of pairs
then define a sort routine that sorts the array x by the key name.
This task can always be accomplished with Sorting Using a Custom Comparator.
If your language is not listed here, please see the other article.
| #Fortran | Fortran | PROGRAM EXAMPLE
IMPLICIT NONE
TYPE Pair
CHARACTER(6) :: name
CHARACTER(1) :: value
END TYPE Pair
TYPE(Pair) :: rcc(10), temp
INTEGER :: i, j
rcc(1) = Pair("Black", "0")
rcc(2) = Pair("Brown", "1")
rcc(3) = Pair("Red", "2")
rcc(4) = Pair("Orange", "3")
rcc(5) = Pair("Yellow", "4")
rcc(6) = Pair("Green", "5")
rcc(7) = Pair("Blue", "6")
rcc(8) = Pair("Violet", "7")
rcc(9) = Pair("Grey", "8")
rcc(10) = Pair("White", "9")
DO i = 2, SIZE(rcc)
j = i - 1
temp = rcc(i)
DO WHILE (j>=1 .AND. LGT(rcc(j)%name, temp%name))
rcc(j+1) = rcc(j)
j = j - 1
END DO
rcc(j+1) = temp
END DO
WRITE (*,"(2A6)") rcc
END PROGRAM EXAMPLE |
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).
| #M2000_Interpreter | M2000 Interpreter |
Module no_connection_puzzle {
\\ Holes
Inventory Connections="A":="CDE","B":="DEF","C":="ADG", "D":="ABCEGH"
Append Connections, "E":="ABDFGH","F":="HEB", "G":="CDE","H":="DEF"
Inventory ToDelete, Solutions
\\ eliminate double connnections
con=each(Connections)
While con {
m$=eval$(con, con^)
c$=eval$(con)
If c$="*" Then continue
For i=1 to len(C$) {
d$=mid$(c$,i,1)
r$=Filter$(Connections$(d$), m$)
If r$<>"" Then {
Return connections, d$:=r$
} else {
If m$=connections$(d$) Then {
Return connections, d$:="*" : If not exist(todelete, d$) Then Append todelete, d$
}
}
}
}
con=each(todelete)
While con {
Delete Connections, eval$(con)
}
Inventory Holes
For i=0 to 7 : Append Holes, Chr$(65+i):=i : Next i
CheckValid=lambda Holes, Connections (a$, arr) -> {
val=Array(arr, Holes(a$))
con$=Connections$(a$)
res=True
For i=1 to Len(con$) {
If Abs(Array(Arr, Holes(mid$(con$,i,1)))-val)<2 Then res=False: Exit
}
=res
}
a=(1,2,3,4,5,6,7,8)
h=(,)
solution=(,)
done=False
counter=0
Print "Wait..."
P(h, a)
sol=Each(Solutions)
While sol {
Print "Solution:";sol^+1
Disp(Eval(Solutions))
aa$=Key$
}
Sub P(h, a)
If len(a)<=1 Then process(cons(h, a)) : Exit Sub
local b=cons(a)
For i=1 to len(b) {
b=cons(cdr(b),car(b))
P(cons(h,car(b)), cdr(b))
}
End Sub
Sub Process(a)
counter++
Print counter
If keypress(32) Then {
local sol=Each(Solutions)
aa$=Key$
While sol {
Print "Solution:";sol^+1
Disp(Eval(Solutions))
aa$=Key$
}
}
hole=each(Connections)
done=True
While hole {
If not CheckValid(Eval$(hole, hole^), a) Then done=False : Exit
}
If done Then Append Solutions, Len(Solutions):=a : Print a
End Sub
Sub Disp(a)
Print format$(" {0} {1}", array(a), array(a,1))
Print " /|\ /|\"
Print " / | X | \"
Print " / |/ \| \"
Print Format$("{0} - {1} - {2} - {3}", array(a,2),array(a,3), array(a,4), array(a,5))
Print " \ |\ /| /"
Print " \ | X | /"
Print " \|/ \|/"
Print Format$(" {0} {1}", array(a,6), array(a,7))
End Sub
}
no_connection_puzzle
|
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).
| #m4 | m4 | divert(-1)
define(`abs',`eval(((( $1 ) < 0) * (-( $1 ))) + ((0 <= ( $1 )) * ( $1 )))')
define(`display_solution',
` substr($1,0,1) substr($1,1,1)
/|\ /|\
/ | X | \
/ |/ \| \
substr($1,2,1)`---'substr($1,3,1)`---'substr($1,4,1)`---'substr($1,5,1)
\ |\ /| /
\ | X | /
\|/ \|/
substr($1,6,1) substr($1,7,1)')
define(`satisfies_constraints',
`eval(satisfies_no_duplicates_constraint($1) && satisfies_difference_constraints($1))')
define(`satisfies_no_duplicates_constraint',
`eval(index(all_but_last($1),last($1)) == -1)')
define(`satisfies_difference_constraints',
`pushdef(`A',ifelse(eval(1 <= len($1)),1,substr($1,0,1),100))`'dnl
pushdef(`B',ifelse(eval(2 <= len($1)),1,substr($1,1,1),200))`'dnl
pushdef(`C',ifelse(eval(3 <= len($1)),1,substr($1,2,1),300))`'dnl
pushdef(`D',ifelse(eval(4 <= len($1)),1,substr($1,3,1),400))`'dnl
pushdef(`E',ifelse(eval(5 <= len($1)),1,substr($1,4,1),500))`'dnl
pushdef(`F',ifelse(eval(6 <= len($1)),1,substr($1,5,1),600))`'dnl
pushdef(`G',ifelse(eval(7 <= len($1)),1,substr($1,6,1),700))`'dnl
pushdef(`H',ifelse(eval(8 <= len($1)),1,substr($1,7,1),800))`'dnl
eval(1 < abs((A) - (C)) &&
1 < abs((A) - (D)) &&
1 < abs((A) - (E)) &&
1 < abs((C) - (G)) &&
1 < abs((D) - (G)) &&
1 < abs((E) - (G)) &&
1 < abs((B) - (D)) &&
1 < abs((B) - (E)) &&
1 < abs((B) - (F)) &&
1 < abs((D) - (H)) &&
1 < abs((E) - (H)) &&
1 < abs((F) - (H)) &&
1 < abs((C) - (D)) &&
1 < abs((D) - (E)) &&
1 < abs((E) - (F)))'`dnl
popdef(`A',`B',`C',`D',`E',`F',`G',`H')')
define(`all_but_last',`substr($1,0,decr(len($1)))')
define(`last',`substr($1,decr(len($1)))')
define(`last_is_eight',`eval((last($1)) == 8)')
define(`strip_eights',`ifelse(last_is_eight($1),1,`$0(all_but_last($1))',`$1')')
define(`incr_last',`all_but_last($1)`'incr(last($1))')
define(`solve_puzzle',`_$0(1)')
define(`_solve_puzzle',
`ifelse(eval(len($1) == 8 && satisfies_constraints($1)),1,`display_solution($1)',
satisfies_constraints($1),1,`$0($1`'1)',
last_is_eight($1),1,`$0(incr_last(strip_eights($1)))',
`$0(incr_last($1))')')
divert`'dnl
dnl
solve_puzzle |
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.
| #Frink | Frink | a = [5, 2, 4, 1, 6, 7, 9, 3, 8, 0]
sort[a] |
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.
| #FunL | FunL | nums = [5, 2, 78, 2, 578, -42]
println( sort(nums) ) // sort in ascending order
println( nums.sortWith((>)) ) // sort in descending order |
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers | Sort a list of object identifiers |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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
Object identifiers (OID)
Task
Show how to sort a list of OIDs, in their natural sort order.
Details
An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number.
Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields.
Test case
Input (list of strings)
Output (list of strings)
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11150.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11150.3.4.0
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11150.3.4.0
1.3.6.1.4.1.11150.3.4.0.1
Related tasks
Natural sorting
Sort using a custom comparator
| #Ring | Ring |
/*
+--------------------------------------------------------------
+ Program Name : SortOIDNumeric.ring
+ Date : 2016-07-14
+ Author : Bert Mariani
+ Purpose : Sort OID List in Numeric Order
+--------------------------------------------------------------
*/
oldOidList =
[
".1.3.6.1.4.1.11.2.17.19.3.4.0.10",
".1.3.6.1.4.1.11.2.17.5.2.0.79",
".1.3.6.1.4.1.11.2.17.19.3.4.0.4",
".1.3.6.1.4.1.11150.3.4.0.1",
".1.3.6.1.4.1.11.2.17.19.3.4.0.1",
".1.3.6.1.4.1.11150.3.4.0"
]
### SHOW BEFORE SORT
See nl + "oldOIDList Before Sort" +nl
See oldOidList
#---------------------
delChar = "."
nulChar = ""
padChar = " "
padSize = 6
newDotPadList = []
### Split list into lines
for line in oldOidList
### Split line by . into components
noDotList = str2list( substr(line, delChar, nl) )
### Pad components with left blanks to make equal size
newPadList = PadStringList(noDotList, padChar, padSize)
### Join the components back to a line
newDotPadString = JoinStringList(delChar, newPadList)
### Create new list - Alpha
Add(newDotPadList, newDotPadString)
next
### Sorts Alpha list
newDotPadListSorted = sort(newDotPadList)
### SHOW ALPHA INTERMEDIATE OUTPUT
See nl + "newDotPadListSorted Intermediate Sort" +nl
See newDotPadListSorted
### Remove blanks for original look
newOidList = RemovePadCharList( newDotPadListSorted, padChar, nulChar)
###--------------------
### SHOW AFTER SORT - NUMERIC
See nl + "newOIDList Final Sort" +nl
See newOidList
###--------------------------------------------------------------------
### Function: PadStringList
### newList = PadStringList(oldList, padChar, padSize )
###--------------------------------------------------------------------
Func PadStringList oldList, padChar, padSize
newList = []
for line in oldList
newPadSize = padSize - len(line)
newLine = Copy( padChar, newPadSize) + line
Add(newList, newLine)
next
### First line in all blank because of leading dot - remove
Del(newList,1)
return newList
###------------------------------------------------------------
### FUNC JoinStringList
### newString = JoinStringList( joinChar, oldList)
###------------------------------------------------------------
Func JoinStringList joinChar, OldList
newString = ""
for line in OldList
newString = newString + joinChar + line
next
return newString
###---------------------------------------------------------------------
### FUNC RemovePadCharList
### newOidList = RemovePadCharList( oldList, padChar, nulChar)
###---------------------------------------------------------------------
Func RemovePadCharList oldList, padChar, nulChar
newList = []
for line in oldList
noPadString = substr(line, padChar, nulChar)
Add(newList, noPadString)
next
return newList
###-----------------------------------------------------------
>; |
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers | Sort a list of object identifiers |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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
Object identifiers (OID)
Task
Show how to sort a list of OIDs, in their natural sort order.
Details
An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number.
Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields.
Test case
Input (list of strings)
Output (list of strings)
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11150.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11150.3.4.0
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11150.3.4.0
1.3.6.1.4.1.11150.3.4.0.1
Related tasks
Natural sorting
Sort using a custom comparator
| #Ruby | Ruby | %w[
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11150.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11150.3.4.0
]
.sort_by{|oid| oid.split(".").map(&:to_i)}
.each{|oid| puts oid} |
http://rosettacode.org/wiki/Sort_disjoint_sublist | Sort disjoint sublist |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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
| #Maple | Maple | sortDisjoint := proc(values, indices::set)
local vals,inds,i:
vals := sort([seq(values[i], i in indices)]):
inds := sort(convert(indices, Array)):
for i to numelems(vals) do
values(inds[i]) := vals[i]:
od:
end proc:
tst := Array([7,6,5,4,3,2,1,0]):
sortDisjoint(tst,{7,2,8}); |
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
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Values = { 7, 6, 5, 4, 3, 2, 1, 0} ; Indices = { 7, 2, 8 };
Values[[Sort[Indices]]] = Sort[Values[[Indices]]];
Values |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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 (the values of) three variables (X, Y, and Z) that contain any value (numbers and/or literals).
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other).
I.E.: (for the three variables x, y, and z), where:
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
After sorting, the three variables would hold:
x = '(from the "Wizard of OZ")'
y = 'bears, oh my!'
z = 'lions, tigers, and'
For numeric value sorting, use:
I.E.: (for the three variables x, y, and z), where:
x = 77444
y = -12
z = 0
After sorting, the three variables would hold:
x = -12
y = 0
z = 77444
The variables should contain some form of a number, but specify if the algorithm
used can be for floating point or integers. Note any limitations.
The values may or may not be unique.
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used.
More than one algorithm could be shown if one isn't clearly the better choice.
One algorithm could be:
• store the three variables x, y, and z
into an array (or a list) A
• sort (the three elements of) the array A
• extract the three elements from the array and place them in the
variables x, y, and z in order of extraction
Another algorithm (only for numeric values):
x= 77444
y= -12
z= 0
low= x
mid= y
high= z
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */
z= max(low, mid, high) /* " " highest " " " " " */
y= low + mid + high - x - z /* " " middle " " " " " */
Show the results of the sort here on this page using at least the values of those shown above.
| #Swift | Swift | func varSort<T: Comparable>(_ x: inout T, _ y: inout T, _ z: inout T) {
let res = [x, y, z].sorted()
x = res[0]
y = res[1]
z = res[2]
}
var x = "lions, tigers, and"
var y = "bears, oh my!"
var z = "(from the \"Wizard of OZ\")"
print("Before:")
print("x = \(x)")
print("y = \(y)")
print("z = \(z)")
print()
varSort(&x, &y, &z)
print("After:")
print("x = \(x)")
print("y = \(y)")
print("z = \(z)") |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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 (the values of) three variables (X, Y, and Z) that contain any value (numbers and/or literals).
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other).
I.E.: (for the three variables x, y, and z), where:
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
After sorting, the three variables would hold:
x = '(from the "Wizard of OZ")'
y = 'bears, oh my!'
z = 'lions, tigers, and'
For numeric value sorting, use:
I.E.: (for the three variables x, y, and z), where:
x = 77444
y = -12
z = 0
After sorting, the three variables would hold:
x = -12
y = 0
z = 77444
The variables should contain some form of a number, but specify if the algorithm
used can be for floating point or integers. Note any limitations.
The values may or may not be unique.
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used.
More than one algorithm could be shown if one isn't clearly the better choice.
One algorithm could be:
• store the three variables x, y, and z
into an array (or a list) A
• sort (the three elements of) the array A
• extract the three elements from the array and place them in the
variables x, y, and z in order of extraction
Another algorithm (only for numeric values):
x= 77444
y= -12
z= 0
low= x
mid= y
high= z
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */
z= max(low, mid, high) /* " " highest " " " " " */
y= low + mid + high - x - z /* " " middle " " " " " */
Show the results of the sort here on this page using at least the values of those shown above.
| #Tcl | Tcl |
set x {lions, tigers, and}
set y {bears, oh my!}
set z {(from the "Wizard of OZ")}
lassign [lsort [list $x $y $z]] x y z
puts "x: $x"
puts "y: $y"
puts "z: $z"
set x 77444
set y -12
set z 0
lassign [lsort [list $x $y $z]] x y z
puts "x: $x"
puts "y: $y"
puts "z: $z"
|
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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.
| #ooRexx | ooRexx | A=.array~of('The seven deadly sins','Pride','avarice','Wrath','envy','gluttony','sloth','Lust')
say 'Sorted in order of descending length, and in ascending lexicographic order'
say A~sortWith(.DescLengthAscLexical~new)~makeString
::class DescLengthAscLexical mixinclass Comparator
::method compare
use strict arg left, right
if left~length==right~length
then return left~caselessCompareTo(right)
else return right~length-left~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.
| #OxygenBasic | OxygenBasic |
uses generics 'containing sort macros
uses console
string sdata={"CC","Aa","aAa","bb","bbB","b","B","c","A"}
'
int count = countof sdata
'
macro filter(f,a)
=================
'sdata[a]
f=1 'allow all
end macro
'
macro compare(f,a,b)
====================
int la=len sdata[a]
int lb=len sdata[b]
if la<lb
f=1 'descending length
elseif la>lb
'
elseif ucase(sdata[a])>ucase(sdata[b])
f=1 'ascending but case insensitive
endif
end macro
'
NewSortIndex(index,count,rcount,filter,compare)
NewSortedData(sorted,sdata,index,rcount)
'
print "Count: " rcount cr cr
int i
for i=1 to rcount
print sorted[i] cr
next
pause
|
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort | Sorting algorithms/Bogosort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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
Bogosort a list of numbers.
Bogosort simply shuffles a collection randomly until it is sorted.
"Bogosort" is a perversely inefficient algorithm only used as an in-joke.
Its average run-time is O(n!) because the chance that any given shuffle of a set will end up in sorted order is about one in n factorial, and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence.
Its best case is O(n) since a single pass through the elements may suffice to order them.
Pseudocode:
while not InOrder(list) do
Shuffle(list)
done
The Knuth shuffle may be used to implement the shuffle part of this algorithm.
| #VBA | VBA | Private Function Knuth(a As Variant) As Variant
Dim t As Variant, i As Integer
If Not IsMissing(a) Then
For i = UBound(a) To LBound(a) + 1 Step -1
j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))
t = a(i)
a(i) = a(j)
a(j) = t
Next i
End If
Knuth = a
End Function
Private Function inOrder(s As Variant)
i = 2
Do While i <= UBound(s)
If s(i) < s(i - 1) Then
inOrder = False
Exit Function
End If
i = i + 1
Loop
inOrder = True
End Function
Private Function bogosort(ByVal s As Variant) As Variant
Do While Not inOrder(s)
Debug.Print Join(s, ", ")
s = Knuth(s)
Loop
bogosort = s
End Function
Public Sub main()
Debug.Print Join(bogosort(Knuth([{1,2,3,4,5,6}])), ", ")
End Sub |
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.
| #Fortran | Fortran | SUBROUTINE Bubble_Sort(a)
REAL, INTENT(in out), DIMENSION(:) :: a
REAL :: temp
INTEGER :: i, j
LOGICAL :: swapped
DO j = SIZE(a)-1, 1, -1
swapped = .FALSE.
DO i = 1, j
IF (a(i) > a(i+1)) THEN
temp = a(i)
a(i) = a(i+1)
a(i+1) = temp
swapped = .TRUE.
END IF
END DO
IF (.NOT. swapped) EXIT
END DO
END SUBROUTINE Bubble_Sort |
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.
| #PHP | PHP | function gnomeSort($arr){
$i = 1;
$j = 2;
while($i < count($arr)){
if ($arr[$i-1] <= $arr[$i]){
$i = $j;
$j++;
}else{
list($arr[$i],$arr[$i-1]) = array($arr[$i-1],$arr[$i]);
$i--;
if($i == 0){
$i = $j;
$j++;
}
}
}
return $arr;
}
$arr = array(3,1,6,2,9,4,7,8,5);
echo implode(',',gnomeSort($arr)); |
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
| #Oz | Oz | declare
proc {CocktailSort Arr}
proc {Swap I J}
Arr.J := (Arr.I := Arr.J) %% assignment returns the old value
end
IsSorted = {NewCell false}
Up = {List.number {Array.low Arr} {Array.high Arr}-1 1}
Down = {Reverse Up}
in
for until:@IsSorted break:Break do
for Range in [Up Down] do
IsSorted := true
for I in Range do
if Arr.I > Arr.(I+1) then
IsSorted := false
{Swap I I+1}
end
end
if @IsSorted then {Break} end
end
end
end
Arr = {Tuple.toArray unit(10 9 8 7 6 5 4 3 2 1)}
in
{CocktailSort Arr}
{Inspect Arr} |
http://rosettacode.org/wiki/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #Erlang | Erlang | -module(socket).
-export([start/0]).
start() ->
{ok, Sock} = gen_tcp:connect("localhost", 256,
[binary, {packet, 0}]),
ok = gen_tcp:send(Sock, "hello socket world"),
ok = gen_tcp:close(Sock).
|
http://rosettacode.org/wiki/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #Factor | Factor | "localhost" 256 <inet> utf8 [ "hello socket world" print ] with-client |
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss.
If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to
estimate the probability that the coin toss was heads. Her estimate is recorded and she is
then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied.
If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to
estimate the probability the coin toss was heads, but is then given a drug which makes her forget
that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day
later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss
was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday.
Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always
estimate the probability of heads as 1/2, since she does not have any additional information. Others
have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice
as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate
should be 1/3 heads.
Task
Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the
proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty
is asked the question.
| #Quackery | Quackery | [ $ "bigrat.qky" loadfile ] now!
[ say "Number of trials: "
dup echo cr
0 ( heads count )
0 ( sleeps count )
rot times
[ 1+
2 random if
[ 1+ dip 1+ ] ]
say "Data: heads count: "
over echo cr
say " sleeps count: "
dup echo cr
say "Credence of heads: "
2dup 20 point$ echo$ cr
say " or approximately: "
10 round vulgar$ echo$ cr ] is trials ( n --> n/d )
1000000 trials |
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss.
If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to
estimate the probability that the coin toss was heads. Her estimate is recorded and she is
then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied.
If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to
estimate the probability the coin toss was heads, but is then given a drug which makes her forget
that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day
later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss
was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday.
Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always
estimate the probability of heads as 1/2, since she does not have any additional information. Others
have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice
as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate
should be 1/3 heads.
Task
Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the
proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty
is asked the question.
| #R | R | beautyProblem <- function(n)
{
wakeCount <- headCount <- 0
for(i in seq_len(n))
{
wakeCount <- wakeCount + 1
if(sample(c("H", "T"), 1) == "H") headCount <- headCount + 1 else wakeCount <- wakeCount + 1
}
headCount/wakeCount
}
print(beautyProblem(10000000)) |
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss.
If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to
estimate the probability that the coin toss was heads. Her estimate is recorded and she is
then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied.
If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to
estimate the probability the coin toss was heads, but is then given a drug which makes her forget
that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day
later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss
was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday.
Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always
estimate the probability of heads as 1/2, since she does not have any additional information. Others
have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice
as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate
should be 1/3 heads.
Task
Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the
proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty
is asked the question.
| #Raku | Raku | sub sleeping-beauty ($trials) {
my $gotheadsonwaking = 0;
my $wakenings = 0;
^$trials .map: {
given <Heads Tails>.roll {
++$wakenings;
when 'Heads' { ++$gotheadsonwaking }
when 'Tails' { ++$wakenings }
}
}
say "Wakenings over $trials experiments: ", $wakenings;
$gotheadsonwaking / $wakenings
}
say "Results of experiment: Sleeping Beauty should estimate a credence of: ", sleeping-beauty(1_000_000); |
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
| #Haskell | Haskell | {-# LANGUAGE NumericUnderscores #-}
import Control.Monad (guard)
import Math.NumberTheory.Primes.Testing (isPrime)
import Data.List.Split (chunksOf)
import Data.List (intercalate)
import Text.Printf (printf)
smarandache :: [Integer]
smarandache = [2,3,5,7] <> s [2,3,5,7] >>= \x -> guard (isPrime x) >> [x]
where s xs = r <> s r where r = xs >>= \x -> [x*10+2, x*10+3, x*10+5, x*10+7]
nextSPDSTerms :: [Int] -> [(String, String)]
nextSPDSTerms = go 1 smarandache
where
go _ _ [] = []
go c (x:xs) terms
| c `elem` terms = (commas c, commas x) : go nextCount xs (tail terms)
| otherwise = go nextCount xs terms
where nextCount = succ c
commas :: Show a => a -> String
commas = reverse . intercalate "," . chunksOf 3 . reverse . show
main :: IO ()
main = do
printf "The first 25 SPDS:\n%s\n\n" $ f smarandache
mapM_ (uncurry (printf "The %9sth SPDS: %15s\n")) $
nextSPDSTerms [100, 1_000, 10_000, 100_000, 1_000_000]
where f = show . take 25 |
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.
| #BASIC | BASIC |
REM Snake
#define EXTCHAR Chr(255)
Dim Shared As Integer puntos, contar, longitud, posX, posY, oldhi = 0
Dim Shared As Integer x(500), y(500)
For contar = 1 To 500
x(contar) = 0 : y(contar) = 0
Next contar
Dim Shared As Byte fruitX, fruitY, convida
Dim Shared As Single delay
Dim Shared As String direccion, usuario
Sub Intro
Cls
Color 15, 0
Print " _ _ _ _ "
Print " / \ / \ / \ / \ "
Print " ___________/ _\/ _\/ _\/ _\____________ "
Print " __________/ /_/ /_/ /_/ /______________ "
Print " | /\ /\ /\ / \ \___ "
Print " |/ \_/ \_/ \_/ \ "+Chr(248)+"\ "
Print " \___/--< "
Color 14, 0
Locate 10, 28: Print "---SNAKE---"
Locate 12, 4: Print "Para jugar, usa las teclas de flecha para moverte."
Locate 13, 4: Print "Pulsa <1-3> para velocidad, o <Esc> para salir."
If puntos > oldhi Then oldhi = puntos
Locate 14, 4: Print "M xima puntuaci¢n: "; oldhi
usuario = ""
While usuario = ""
usuario = Inkey
Wend
If usuario = Chr(27) Then End 'ESC
delay = .14
If usuario = "1" Then delay = .26
If usuario = "3" Then delay = .08
Cls
longitud = 9
puntos = 0
posX = 40 : posY = 10
direccion = "derecha"
convida = true
fruitX = Int(Rnd * 79) + 1
fruitY = Int(Rnd * 20) + 1
Locate 22, 1
For contar = 1 To 80
Print Chr(196); ''"-";
Next contar
End Sub
Sub MenuPrincipal
Dim As Integer num, oldX, oldY
Dim As Single tm, tm2
Color 10
Locate 23, 2: Print "SNAKE - <Esc> salir - Puntos: "; puntos
If posX = fruitX And posY = fruitY Then
longitud += 1
puntos += 1
fruitX = Int(Rnd * 79) + 1
fruitY = Int(Rnd * 21) + 1
End If
Locate fruitY, fruitX : Color 12: Print Chr(01) : Color 10'"@"
x(0) = posX : y(0) = posY
For contar = 1 To 499
num = 500 - contar
x(num) = x(num - 1)
y(num) = y(num - 1)
Next contar
oldX = x(longitud) : oldY = y(longitud)
If oldX > 0 And oldY > 0 Then Locate oldY, oldX : Print " "
Locate posY, posX: Print Chr(219) '"Û"
tm = Timer
tm2 = tm + delay
While tm < tm2
tm = Timer
usuario = Inkey
If usuario = EXTCHAR & "H" Then direccion = "arriba"
If usuario = EXTCHAR & "P" Then direccion = "abajo"
If usuario = EXTCHAR & "K" Then direccion = "izquierda"
If usuario = EXTCHAR & "M" Then direccion = "derecha"
If usuario = Chr(27) Then Intro
Wend
If direccion = "derecha" Then posX += 1
If posX > 80 Then convida = false
If direccion = "izquierda" Then posX -= 1
If posX < 1 Then convida = false
If direccion = "arriba" Then posY -= 1
If posY < 1 Then convida = false
If direccion = "abajo" Then posY += 1
If posY > 21 Then convida = false
For contar = 0 To longitud
If posX = x(contar) And posY = y(contar) Then convida = false
Next contar
If convida = false Then
Cls : Locate 11, 19: Print "Pulsa <space>..."
Locate 10, 18: Print "Has muerto! Con"; puntos; " puntos." : Sleep
While Inkey = "": Wend
Intro
End If
MenuPrincipal
End Sub
'--- Programa Principal ---
Randomize Timer
Intro
MenuPrincipal
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].
| #ALGOL_68 | ALGOL 68 | # sieve of Eratosthene: sets s[i] to TRUE if i is prime, FALSE otherwise #
PROC sieve = ( REF[]BOOL s )VOID:
BEGIN
# start with everything flagged as prime #
FOR i TO UPB s DO s[ i ] := TRUE OD;
# sieve out the non-primes #
s[ 1 ] := FALSE;
FOR i FROM 2 TO ENTIER sqrt( UPB s ) DO
IF s[ i ] THEN FOR p FROM i * i BY i TO UPB s DO s[ p ] := FALSE OD FI
OD
END # sieve # ;
# construct a sieve of primes up to the maximum number required for the task #
INT max number = 10 000;
[ 1 : max number ]BOOL is prime;
sieve( is prime );
# returns the sum of the digits of n #
OP DIGITSUM = ( INT n )INT:
BEGIN
INT sum := 0;
INT rest := ABS n;
WHILE rest > 0 DO
sum +:= rest MOD 10;
rest OVERAB 10
OD;
sum
END # DIGITSUM # ;
# returns TRUE if n is a Smith number, FALSE otherwise #
# n must be between 1 and max number #
PROC is smith = ( INT n )BOOL:
IF is prime[ ABS n ] THEN
# primes are not Smith numbers #
FALSE
ELSE
# find the factors of n and sum the digits of the factors #
INT rest := ABS n;
INT factor digit sum := 0;
INT factor := 2;
WHILE factor < max number AND rest > 1 DO
IF NOT is prime[ factor ] THEN
# factor isn't a prime #
factor +:= 1
ELSE
# factor is a prime #
IF rest MOD factor /= 0 THEN
# factor isn't a factor of n #
factor +:= 1
ELSE
# factor is a factor of n #
rest OVERAB factor;
factor digit sum +:= DIGITSUM factor
FI
FI
OD;
( factor digit sum = DIGITSUM n )
FI # is smith # ;
# print all the Smith numbers below the maximum required #
INT smith count := 0;
FOR n TO max number - 1 DO
IF is smith( n ) THEN
# have a smith number #
print( ( whole( n, -7 ) ) );
smith count +:= 1;
IF smith count MOD 10 = 0 THEN
print( ( newline ) )
FI
FI
OD;
print( ( newline, "THere are ", whole( smith count, -7 ), " Smith numbers below ", whole( max number, -7 ), newline ) )
|
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;
| #Curry | Curry | import CLPFD
import Constraint (andC, anyC)
import Findall (unpack)
import Integer (abs)
hidato :: [[Int]] -> Success
hidato path =
test path inner
& domain inner 1 40
& allDifferent inner
& andFD [x `near` y | x <- cells, y <- cells]
& labeling [] (concat path)
where
andFD = solve . foldr1 (#/\#)
cells = enumerate path
inner free
near :: (Int,Int,Int) -> (Int,Int,Int) -> Constraint
(x,rx,cx) `near` (y,ry,cy) = x #<=# y #/\# dist (y -# x)
#\/# x #># y #/\# dist (x -# y)
#\/# x #=# 0
#\/# y #=# 0
where
dist d = abs (rx - ry) #<=# d
#/\# abs (cx - cy) #<=# d
enumerate :: [[Int]] -> [(Int,Int,Int)]
enumerate xss = [(x,row,col) | (xs,row) <- xss `zip` [1..]
, (x ,col) <- xs `zip` [1..]
]
test [[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
,[ 0, A, 33, 35, B, C, 0, 0, 0, 0]
,[ 0, D, E, 24, 22, F, 0, 0, 0, 0]
,[ 0, G, H, I, 21, J, K, 0, 0, 0]
,[ 0, L, 26, M, 13, 40, 11, 0, 0, 0]
,[ 0, 27, N, O, P, 9, Q, 1, 0, 0]
,[ 0, 0, 0, R, S, 18, T, U, 0, 0]
,[ 0, 0, 0, 0, 0, V, 7, W, X, 0]
,[ 0, 0, 0, 0, 0, 0, 0, 5, Y, 0]
,[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
]
[ A, 33, 35, B, C
, D, E, 24, 22, F
, G, H, I, 21, J, K
, L, 26, M, 13, 40, 11
, 27, N, O, P, 9, Q, 1
, R, S, 18, T, U
, V, 7, W, X
, 5, Y
] = success
main = unpack hidato |
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.
| #Perl | Perl | #!perl
use strict;
use warnings qw(FATAL all);
my @initial = split /\n/, <<'';
#############
# # #
# $$$$$$$ @#
#....... #
#############
#######
# #
# #
#. # #
#. $$ #
#.$$ #
#.# @#
#######
=for
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
=cut
my $cols = length($initial[0]);
my $initial = join '', @initial;
my $size = length($initial);
die unless $size == $cols * @initial;
sub WALL() { 1 }
sub PLAYER() { 2 }
sub BOX() { 4 }
sub GOAL() { 8 }
my %input = (
' ' => 0, '#' => WALL, '@' => PLAYER, '$' => BOX,
'.' => GOAL, '+' => PLAYER|GOAL, '*' => BOX|GOAL,
);
my %output = reverse(%input);
sub packed_initial {
my $ret = '';
vec( $ret, $_, 4 ) = $input{substr $initial, $_, 1}
for( 0 .. $size-1 );
$ret;
}
sub printable_board {
my $board = shift;
my @c = @output{map vec($board, $_, 4), 0 .. $size-1};
my $ret = '';
while( my @row = splice @c, 0, $cols ) {
$ret .= join '', @row, "\n";
}
$ret;
}
my $packed = packed_initial();
my @udlr = qw(u d l r);
my @UDLR = qw(U D L R);
my @deltas = (-$cols, +$cols, -1, +1);
my %fseen;
INIT_FORWARD: {
$initial =~ /(\@|\+)/ or die;
use vars qw(@ftodo @fnext);
@ftodo = (["", $packed, $-[0]]);
$fseen{$packed} = '';
}
my %rseen;
INIT_REVERSE: {
my $goal = $packed;
vec($goal, $ftodo[0][2], 4) -= PLAYER;
my @u = grep { my $t = vec($goal, $_, 4); $t & GOAL and not $t & BOX } 0 .. $size-1;
my @b = grep { my $t = vec($goal, $_, 4); $t & BOX and not $t & GOAL } 0 .. $size-1;
die unless @u == @b;
vec($goal, $_, 4) += BOX for @u;
vec($goal, $_, 4) -= BOX for @b;
use vars qw(@rtodo @rnext);
FINAL_PLACE: for my $player (0 .. $size-1) {
next if vec($goal, $player, 4);
FIND_GOAL: {
vec($goal, $player + $_, 4) & GOAL and last FIND_GOAL for @deltas;
next FINAL_PLACE;
}
my $a_goal = $goal;
vec($a_goal, $player, 4) += PLAYER;
push @rtodo, ["", $a_goal, $player ];
$rseen{$a_goal} = '';
#print printable_board($a_goal);
}
}
my $movelen = -1;
my ($solution);
MAIN: while( @ftodo and @rtodo ) {
FORWARD: {
my ($moves, $level, $player) = @{pop @ftodo};
die unless vec($level, $player, 4) & PLAYER;
for my $dir_num (0 .. 3) {
my $delta = $deltas[$dir_num];
my @loc = map $player + $delta * $_, 0 .. 2;
my @val = map vec($level, $_, 4), @loc;
next if $val[1] & WALL or ($val[1] & BOX and $val[2] & (BOX|WALL));
my $new = $level;
vec($new, $loc[0], 4) -= PLAYER;
vec($new, $loc[1], 4) += PLAYER;
my $nmoves;
if( $val[1] & BOX ) {
vec($new, $loc[1], 4) -= BOX;
vec($new, $loc[2], 4) += BOX;
$nmoves = $moves . $UDLR[$dir_num];
} else {
$nmoves = $moves . $udlr[$dir_num];
}
next if exists $fseen{$new};
$fseen{$new} = $nmoves;
push @fnext, [ $nmoves, $new, $loc[1] ];
exists $rseen{$new} or next;
#print(($val[1] & BOX) ? "Push $UDLR[$dir_num]\n" : "Fwalk $udlr[$dir_num]\n");
$solution = $new;
last MAIN;
}
last FORWARD if @ftodo;
use vars qw(*ftodo *fnext);
(*ftodo, *fnext) = (\@fnext, \@ftodo);
} # end FORWARD
BACKWARD: {
my ($moves, $level, $player) = @{pop @rtodo};
die "<$level>" unless vec($level, $player, 4) & PLAYER;
for my $dir_num (0 .. 3) {
my $delta = $deltas[$dir_num];
# look behind and in front of the player.
my @loc = map $player + $delta * $_, -1 .. 1;
my @val = map vec($level, $_, 4), @loc;
# unlike the forward solution, we cannot push boxes
next if $val[0] & (WALL|BOX);
my $new = $level;
vec($new, $loc[0], 4) += PLAYER;
vec($new, $loc[1], 4) -= PLAYER;
# unlike the forward solution, if we have a box behind us
# we can *either* pull it or not. This means there are
# two "successors" to this board.
if( $val[2] & BOX ) {
my $pull = $new;
vec($pull, $loc[2], 4) -= BOX;
vec($pull, $loc[1], 4) += BOX;
goto RWALK if exists $rseen{$pull};
my $pmoves = $UDLR[$dir_num] . $moves;
$rseen{$pull} = $pmoves;
push @rnext, [$pmoves, $pull, $loc[0]];
goto RWALK unless exists $fseen{$pull};
print "Doing pull\n";
$solution = $pull;
last MAIN;
}
RWALK:
next if exists $rseen{$new}; # next direction.
my $wmoves = $udlr[$dir_num] . $moves;
$rseen{$new} = $wmoves;
push @rnext, [$wmoves, $new, $loc[0]];
next unless exists $fseen{$new};
print "Rwalk\n";
$solution = $new;
last MAIN;
}
last BACKWARD if @rtodo;
use vars qw(*rtodo *rnext);
(*rtodo, *rnext) = (\@rnext, \@rtodo);
} # end BACKWARD
}
if( $solution ) {
my $fmoves = $fseen{$solution};
my $rmoves = $rseen{$solution};
print "Solution found!\n";
print "Time: ", (time() - $^T), " seconds\n";
print "Moves: $fmoves $rmoves\n";
print "Move Length: ", length($fmoves . $rmoves), "\n";
print "Middle Board: \n", printable_board($solution);
} else {
print "No solution found!\n";
}
__END__
|
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
| #Nim | Nim | import sequtils, strformat
const Moves = [[-1, -2], [1, -2], [-2, -1], [2, -1], [-2, 1], [2, 1], [-1, 2], [1, 2]]
proc solve(pz: var seq[seq[int]]; sx, sy, idx, count: Natural): bool =
if idx > count: return true
var x, y: int
for move in Moves:
x = sx + move[0]
y = sy + move[1]
if x in 0..pz.high and y in 0..pz.high and pz[x][y] == 0:
pz[x][y] = idx
if pz.solve(x, y, idx + 1, count): return true
pz[x][y] = 0
proc findSolution(board: openArray[string]) =
let sz = board.len
var pz = newSeqWith(sz, repeat(-1, sz))
var count = 0
var x, y: int
for i in 0..<sz:
for j in 0..<sz:
case board[i][j]
of 'x':
pz[i][j] = 0
inc count
of 's':
pz[i][j] = 1
inc count
(x, y) = (i, j)
else:
discard
if pz.solve(x, y, 2, count):
for i in 0..<sz:
for j in 0..<sz:
if pz[i][j] != -1:
stdout.write &"{pz[i][j]:02} "
else:
stdout.write "-- "
stdout.write '\n'
when isMainModule:
const
Board1 = [" xxx ",
" x xx ",
" xxxxxxx",
"xxx x x",
"x x xxx",
"sxxxxxx ",
" xx x ",
" xxx "]
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....."]
Board1.findSolution()
echo()
Board2.findSolution() |
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.
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Type Pair
As String name, value
Declare Constructor(name_ As String, value_ As String)
Declare Operator Cast() As String
End Type
Constructor Pair(name_ As String, value_ As String)
name = name_
value = value_
End Constructor
Operator Pair.Cast() As String
Return "[" + name + ", " + value + "]"
End Operator
' selection sort, quick enough for sorting small number of pairs
Sub sortPairsByName(p() As Pair)
Dim As Integer i, j, m
For i = LBound(p) To UBound(p) - 1
m = i
For j = i + 1 To UBound(p)
If p(j).name < p(m).name Then m = j
Next j
If m <> i Then Swap p(i), p(m)
Next i
End Sub
Dim As Pair pairs(1 To 4) = _
{ _
Pair("grass", "green"), _
Pair("snow", "white" ), _
Pair("sky", "blue"), _
Pair("cherry", "red") _
}
Print "Before sorting :"
For i As Integer = 1 To 4
Print Tab(3); pairs(i)
Next
sortPairsByName pairs()
Print
Print "After sorting by name :"
For i As Integer = 1 To 4
Print Tab(3); pairs(i)
Next
Print
Print "Press any key to quit"
Sleep |
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).
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | sol = Fold[
Select[#,
Function[perm, Abs[perm[[#2[[1]]]] - perm[[#2[[2]]]]] > 1]] &,
Permutations[
Range[8]], {{1, 3}, {1, 4}, {1, 5}, {2, 4}, {2, 5}, {2, 6}, {3,
4}, {3, 7}, {4, 5}, {4, 7}, {4, 8}, {5, 6}, {5, 7}, {5, 8}, {6,
8}}][[1]];
Print[StringForm[
" `` ``\n /|\\ /|\\\n / | X | \\\n / |/ \\| \\\n`` - `` \
- `` - ``\n \\ |\\ /| /\n \\ | X | /\n \\|/ \\|/\n `` ``",
Sequence @@ sol]]; |
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).
| #Nim | Nim | import strformat
const Connections = [(1, 3), (1, 4), (1, 5), # A to C, D, E
(2, 4), (2, 5), (2, 6), # B to D, E, F
(7, 3), (7, 4), (7, 5), # G to C, D, E
(8, 4), (8, 5), (8, 6), # H to D, E, F
(3, 4), (4, 5), (5, 6)] # C-D, D-E, E-F
type
Peg = 1..8
Pegs = array[1..8, Peg]
func valid(pegs: Pegs): bool =
for (src, dst) in Connections:
if abs(pegs[src] - pegs[dst]) == 1:
return false
result = true
proc print(pegs: Pegs; num: Positive) =
echo &"----- {num} -----"
echo &" {pegs[1]} {pegs[2]}"
echo &"{pegs[3]} {pegs[4]} {pegs[5]} {pegs[6]}"
echo &" {pegs[7]} {pegs[8]}"
echo()
proc findSolution(pegs: var Pegs; left, right: Natural; solCount = 0): Natural =
var solCount = solCount
if left == right:
if pegs.valid():
inc solCount
pegs.print(solCount)
else:
for i in left..right:
swap pegs[left], pegs[i]
solCount = pegs.findSolution(left + 1, right, solCount)
swap pegs[left], pegs[i]
result = solCount
when isMainModule:
var pegs = [Peg 1, 2, 3, 4, 5, 6, 7, 8]
discard pegs.findSolution(1, 8) |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | Public Sub Main()
Dim iArray As Integer[] = [8, 2, 5, 9, 1, 3, 6, 7, 4]
Dim iTemp As Integer
Dim sOutput As String
For Each iTemp In iArray.Sort()
sOutput &= iTemp & ", "
Next
Print Left(sOutput, -2)
End |
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.
| #Gambas | Gambas | Public Sub Main()
Dim iArray As Integer[] = [8, 2, 5, 9, 1, 3, 6, 7, 4]
Dim iTemp As Integer
Dim sOutput As String
For Each iTemp In iArray.Sort()
sOutput &= iTemp & ", "
Next
Print Left(sOutput, -2)
End |
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers | Sort a list of object identifiers |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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
Object identifiers (OID)
Task
Show how to sort a list of OIDs, in their natural sort order.
Details
An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number.
Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields.
Test case
Input (list of strings)
Output (list of strings)
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11150.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11150.3.4.0
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11150.3.4.0
1.3.6.1.4.1.11150.3.4.0.1
Related tasks
Natural sorting
Sort using a custom comparator
| #Rust | Rust | fn split(s: &str) -> impl Iterator<Item = u64> + '_ {
s.split('.').map(|x| x.parse().unwrap())
}
fn main() {
let mut oids = vec![
"1.3.6.1.4.1.11.2.17.19.3.4.0.10",
"1.3.6.1.4.1.11.2.17.5.2.0.79",
"1.3.6.1.4.1.11.2.17.19.3.4.0.4",
"1.3.6.1.4.1.11150.3.4.0.1",
"1.3.6.1.4.1.11.2.17.19.3.4.0.1",
"1.3.6.1.4.1.11150.3.4.0",
];
oids.sort_by(|a, b| Iterator::cmp(split(a), split(b)));
println!("{:#?}", oids);
} |
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers | Sort a list of object identifiers |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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
Object identifiers (OID)
Task
Show how to sort a list of OIDs, in their natural sort order.
Details
An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number.
Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields.
Test case
Input (list of strings)
Output (list of strings)
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11150.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11150.3.4.0
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11150.3.4.0
1.3.6.1.4.1.11150.3.4.0.1
Related tasks
Natural sorting
Sort using a custom comparator
| #Sather | Sather | class MAIN is
oid_lt (a, b: STR): BOOL is
as ::= a.cursor.split('.');
bs ::= b.cursor.split('.');
loop
na ::= #INT(as.elt!);
nb ::= #INT(bs.elt!);
if na /= nb then return na < nb; end;
end;
return as.size < bs.size;
end;
main is
sorter: ARR_SORT_ALG{STR, ARRAY{STR}};
input: ARRAY{STR} := |"1.3.6.1.4.1.11.2.17.19.3.4.0.10",
"1.3.6.1.4.1.11.2.17.5.2.0.79",
"1.3.6.1.4.1.11.2.17.19.3.4.0.4",
"1.3.6.1.4.1.11150.3.4.0.1",
"1.3.6.1.4.1.11.2.17.19.3.4.0.1",
"1.3.6.1.4.1.11150.3.4.0"|;
sorted ::= input.copy;
sorter.sort_by(sorted, bind(oid_lt(_, _)));
#OUT+"unsorted:\n";
loop #OUT+input.elt! + "\n"; end;
#OUT+"sorted:\n";
loop #OUT+sorted.elt! + "\n"; end;
end;
end; |
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
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method sortDisjoint(oldList, indices) public static
newList = oldList.space()
if indices.words() > 1 then do -- only do work if we need to
subList = ArrayList()
idxList = ArrayList()
-- pick the input list apart
loop ix = 1 to indices.words()
iw = indices.word(ix)
nw = oldList.word(iw)
-- protect against bad outcomes...
if iw > oldList.words() then signal ArrayIndexOutOfBoundsException()
if iw < 1 then signal ArrayIndexOutOfBoundsException()
subList.add(nw)
idxList.add(iw)
end ix
Collections.sort(subList) -- sort sublist
Collections.sort(idxList) -- sort indices
-- put it all back together
loop kx = 0 to subList.size() - 1
kk = Rexx subList.get(kx)
ii = Rexx idxList.get(kx)
newList = newList.subword(1, ii - 1) kk newList.subword(ii + 1)
end kx
end
return newList
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
parse arg vList ',' iList
if vList = '' then vList = 7 6 5 4 3 2 1 0
if iList = '' then iList = 7 2 8
rList = sortDisjoint(vList, iList)
say 'In: ' vList.space
say 'Out:' rList.space
say 'Idx:' iList.space
return
|
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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 (the values of) three variables (X, Y, and Z) that contain any value (numbers and/or literals).
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other).
I.E.: (for the three variables x, y, and z), where:
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
After sorting, the three variables would hold:
x = '(from the "Wizard of OZ")'
y = 'bears, oh my!'
z = 'lions, tigers, and'
For numeric value sorting, use:
I.E.: (for the three variables x, y, and z), where:
x = 77444
y = -12
z = 0
After sorting, the three variables would hold:
x = -12
y = 0
z = 77444
The variables should contain some form of a number, but specify if the algorithm
used can be for floating point or integers. Note any limitations.
The values may or may not be unique.
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used.
More than one algorithm could be shown if one isn't clearly the better choice.
One algorithm could be:
• store the three variables x, y, and z
into an array (or a list) A
• sort (the three elements of) the array A
• extract the three elements from the array and place them in the
variables x, y, and z in order of extraction
Another algorithm (only for numeric values):
x= 77444
y= -12
z= 0
low= x
mid= y
high= z
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */
z= max(low, mid, high) /* " " highest " " " " " */
y= low + mid + high - x - z /* " " middle " " " " " */
Show the results of the sort here on this page using at least the values of those shown above.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Swap(Of T)(ByRef a As T, ByRef b As T)
Dim c = a
a = b
b = c
End Sub
Sub Sort(Of T As IComparable(Of T))(ByRef a As T, ByRef b As T, ByRef c As T)
If a.CompareTo(b) > 0 Then
Swap(a, b)
End If
If a.CompareTo(c) > 0 Then
Swap(a, c)
End If
If b.CompareTo(c) > 0 Then
Swap(b, c)
End If
End Sub
Sub Main()
Dim x = 77444
Dim y = -12
Dim z = 0
Sort(x, y, z)
Console.WriteLine((x, y, z))
Dim a = "lions, tigers, and"
Dim b = "bears, oh my!"
Dim c = "(from the 'Wizard of OZ')"
Sort(a, b, c)
Console.WriteLine((a, b, c))
End Sub
End Module |
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.
| #Oz | Oz | declare
fun {LexicographicLessThan Xs Ys}
for
X in {Map Xs Char.toLower}
Y in {Map Ys Char.toLower}
return:Return
default:{Length Xs}<{Length Ys}
do
if X < Y then {Return true} end
end
end
fun {LessThan Xs Ys}
{Length Xs} > {Length Ys}
orelse
{Length Xs} == {Length Ys} andthen {LexicographicLessThan Xs Ys}
end
Strings = ["Here" "are" "some" "sample" "strings" "to" "be" "sorted"]
in
{ForAll {Sort Strings LessThan} System.showInfo} |
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort | Sorting algorithms/Bogosort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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
Bogosort a list of numbers.
Bogosort simply shuffles a collection randomly until it is sorted.
"Bogosort" is a perversely inefficient algorithm only used as an in-joke.
Its average run-time is O(n!) because the chance that any given shuffle of a set will end up in sorted order is about one in n factorial, and the worst case is infinite since there's no guarantee that a random shuffling will ever produce a sorted sequence.
Its best case is O(n) since a single pass through the elements may suffice to order them.
Pseudocode:
while not InOrder(list) do
Shuffle(list)
done
The Knuth shuffle may be used to implement the shuffle part of this algorithm.
| #VBScript | VBScript | sub swap( byref a, byref b )
dim tmp
tmp = a
a = b
b = tmp
end sub
'knuth shuffle (I think)
function shuffle( a )
dim i
dim r
randomize timer
for i = lbound( a ) to ubound( a )
r = int( rnd * ( ubound( a ) + 1 ) )
if r <> i then
swap a(i), a(r)
end if
next
shuffle = a
end function
function inOrder( a )
dim res
dim i
for i = 0 to ubound( a ) - 1
res = ( a(i) <= a(i+1) )
if res = false then exit for
next
inOrder = res
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.
| #FreeBASIC | FreeBASIC | ' version 21-10-2016
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
Sub bubblesort(bs() As Long)
' sort from lower bound to the highter bound
' array's can have subscript range from -2147483648 to +2147483647
Dim As Long lb = LBound(bs)
Dim As Long ub = UBound(bs)
Dim As Long done, i
Do
done = 0
For i = lb To ub -1
' replace "<" with ">" for downwards sort
If bs(i) > bs(i +1) Then
Swap bs(i), bs(i +1)
done = 1
End If
Next
Loop Until done = 0
End Sub
' ------=< MAIN >=------
Dim As Long i, array(-7 To 7)
Dim As Long a = LBound(array), b = UBound(array)
Randomize Timer
For i = a To b : array(i) = i : Next
For i = a To b ' little shuffle
Swap array(i), array(Int(Rnd * (b - a +1)) + a)
Next
Print "unsort ";
For i = a To b : Print Using "####"; array(i); : Next : Print
bubblesort(array()) ' sort the array
Print " sort ";
For i = a To b : Print Using "####"; array(i); : Next : Print
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
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.
| #PicoLisp | PicoLisp | (de gnomeSort (Lst)
(let J (cdr Lst)
(for (I Lst (cdr I))
(if (>= (cadr I) (car I))
(setq I J J (cdr J))
(xchg I (cdr I))
(if (== I Lst)
(setq I J J (cdr J))
(setq I (prior I Lst)) ) ) ) )
Lst ) |
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
| #PARI.2FGP | PARI/GP | cocktailSort(v)={
while(1,
my(done=1);
for(i=2,#v,
if(v[i-1]>v[i],
my(t=v[i-1]);
v[i-1]=v[i];
v[i]=t;
done=0
)
);
if(done, return(v));
done=1;
forstep(i=#v,2,-1,
if(v[i-1]>v[i],
my(t=v[i-1]);
v[i-1]=v[i];
v[i]=t;
done=0
)
);
if(done, return(v))
)
}; |
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.
| #Fantom | Fantom |
using inet
class Socket
{
public static Void main ()
{
sock := TcpSocket()
sock.connect(IpAddr("localhost"), 256)
sock.out.printLine("hello socket world")
sock.out.flush
sock.close
}
}
|
http://rosettacode.org/wiki/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #Forth | Forth | include unix/socket.fs
s" localhost" 256 open-socket
dup s" hello socket world" rot write-socket
close-socket |
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss.
If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to
estimate the probability that the coin toss was heads. Her estimate is recorded and she is
then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied.
If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to
estimate the probability the coin toss was heads, but is then given a drug which makes her forget
that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day
later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss
was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday.
Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always
estimate the probability of heads as 1/2, since she does not have any additional information. Others
have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice
as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate
should be 1/3 heads.
Task
Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the
proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty
is asked the question.
| #Red | Red | Red ["Sleeping Beauty problem"]
experiments: 1'000'000
heads: awakenings: 0
loop experiments [
awakenings: awakenings + 1
either 1 = random 2 [heads: heads + 1] [awakenings: awakenings + 1]
]
print ["Awakenings over" experiments "experiments:" awakenings]
print ["Probability of heads on waking:" heads / awakenings] |
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss.
If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to
estimate the probability that the coin toss was heads. Her estimate is recorded and she is
then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied.
If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to
estimate the probability the coin toss was heads, but is then given a drug which makes her forget
that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day
later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss
was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday.
Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always
estimate the probability of heads as 1/2, since she does not have any additional information. Others
have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice
as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate
should be 1/3 heads.
Task
Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the
proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty
is asked the question.
| #REXX | REXX | /*REXX pgm uses a Monte Carlo estimate for the results for the Sleeping Beauty problem. */
parse arg n seed . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 1000000 /*Not specified? Then use the default.*/
if datatype(seed, 'W') then call random ,,seed /* Specified? Then use as RAND seed*/
awake= 0 /* " " " " awakened. */
do #=0 for n /*perform experiment: 1 million times?*/
if random(,1) then awake= awake + 1 /*Sleeping Beauty is awoken. */
else #= # + 1 /* " " keeps sleeping. */
end /*#*/ /* [↑] RANDOM returns: 0 or 1 */
say 'Wakenings over ' commas(n) " repetitions: " commas(#)
say 'The percentage probability of heads on awakening: ' (awake / # * 100)"%"
exit 0 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
commas: parse arg ?; do jc=length(?)-3 to 1 by -3; ?=insert(',', ?, jc); end; return ? |
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin toss.
If this coin toss comes up heads, Sleeping Beauty wakes once (on Monday) and is asked to
estimate the probability that the coin toss was heads. Her estimate is recorded and she is
then put back to sleep for 2 days until Wednesday, at which time the experiment's results are tallied.
If instead the coin toss is tails, Sleeping Beauty wakes as before on Monday and asked to
estimate the probability the coin toss was heads, but is then given a drug which makes her forget
that she had been woken on Monday before being put back to sleep again. She then wakes only 1 day
later, on Tuesday. She is then asked (on Tuesday) again to guess the probability that the coin toss
was heads or tails. She is then put back to sleep and awakes as before 1 day later, on Wednesday.
Some decision makers have argued that since the coin toss was fair Sleeping Beauty should always
estimate the probability of heads as 1/2, since she does not have any additional information. Others
have disagreed, saying that if Sleeping Beauty knows the study design she also knows that she is twice
as likely to wake up and be asked to estimate the coin flip on tails than on heads, so the estimate
should be 1/3 heads.
Task
Given the above problem, create a Monte Carlo estimate of the actual results. The program should find the
proportion of heads on waking and asking Sleeping Beauty for an estimate, as a credence or as a percentage of the times Sleeping Beauty
is asked the question.
| #Ruby | Ruby | def sleeping_beauty_experiment(n)
coin = [:heads, :tails]
gotheadsonwaking = 0
wakenings = 0
n.times do
wakenings += 1
coin.sample == :heads ? gotheadsonwaking += 1 : wakenings += 1
end
puts "Wakenings over #{n} experiments: #{wakenings}"
gotheadsonwaking / wakenings.to_f
end
puts "Results of experiment: Sleeping Beauty should estimate
a credence of: #{sleeping_beauty_experiment(1_000_000)}"
|
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
| #J | J | Filter=: (#~`)(`:6)
NB. given a prime y, smarandache y is 1 iff it's a smarandache prime
smarandache=: [: -. (0 e. (p:i.4) e.~ 10 #.inv ])&>
SP=: smarandache Filter p: i. 1000000
SP {~ i. 25 NB. first 25 Smarandache primes
2 3 5 7 23 37 53 73 223 227 233 257 277 337 353 373 523 557 577 727 733 757 773 2237 2273
99 _1 { SP NB. 100th and largest Smarandache prime of the first million primes
33223 7777753
# SP NB. Tally of Smarandache primes in the first million primes
1903
|
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
| #Java | Java |
public class SmarandachePrimeDigitalSequence {
public static void main(String[] args) {
long s = getNextSmarandache(7);
System.out.printf("First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 ");
for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {
if ( isPrime(s) ) {
System.out.printf("%d ", s);
count++;
}
}
System.out.printf("%n%n");
for (int i = 2 ; i <=5 ; i++ ) {
long n = (long) Math.pow(10, i);
System.out.printf("%,dth Smarandache prime-digital sequence number = %d%n", n, getSmarandachePrime(n));
}
}
private static final long getSmarandachePrime(long n) {
if ( n < 10 ) {
switch ((int) n) {
case 1: return 2;
case 2: return 3;
case 3: return 5;
case 4: return 7;
}
}
long s = getNextSmarandache(7);
long result = 0;
for ( int count = 1 ; count <= n-4 ; s = getNextSmarandache(s) ) {
if ( isPrime(s) ) {
count++;
result = s;
}
}
return result;
}
private static final boolean isPrime(long test) {
if ( test % 2 == 0 ) return false;
for ( long i = 3 ; i <= Math.sqrt(test) ; i += 2 ) {
if ( test % i == 0 ) {
return false;
}
}
return true;
}
private static long getNextSmarandache(long n) {
// If 3, next is 7
if ( n % 10 == 3 ) {
return n+4;
}
long retVal = n-4;
// Last digit 7. k = largest position from right where we have a 7.
int k = 0;
while ( n % 10 == 7 ) {
k++;
n /= 10;
}
// Determine first digit from right where digit != 7.
long digit = n % 10;
// Digit is 2, 3, or 5. 3-2 = 1, 5-3 = 2, 7-5 = 2, so digit = 2, coefficient = 1, otherwise 2.
long coeff = (digit == 2 ? 1 : 2);
// Compute next value
retVal += coeff * Math.pow(10, k);
// Subtract values for digit = 7.
while ( k > 1 ) {
retVal -= 5 * Math.pow(10, k-1);
k--;
}
// Even works for 777..777 --> 2222...223
return retVal;
}
}
|
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.
| #C | C | // Snake
// The problem with implementing this task in C is, the language standard
// does not cover some details essential for interactive games:
// a nonblocking keyboard input, a positional console output,
// a and millisecond-precision timer: these things are all system-dependent.
// Therefore the program is split in two pieces, a system-independent
// game logic, and a system-dependent UI, separated by a tiny API:
char nonblocking_getch();
void positional_putch(int x, int y, char ch);
void millisecond_sleep(int n);
void init_screen();
void update_screen();
void close_screen();
// The implementation of a system-dependent part.
// Requires POSIX IEEE 1003.1-2008 compliant system and ncurses library.
#ifdef __linux__
#define _POSIX_C_SOURCE 200809L
#include <time.h> // nanosleep
#include <ncurses.h> // getch, mvaddch, and others
char nonblocking_getch() { return getch(); }
void positional_putch(int x, int y, char ch) { mvaddch(x, y, ch); }
void millisecond_sleep(int n) {
struct timespec t = { 0, n * 1000000 };
nanosleep(&t, 0);
// for older POSIX standards, consider usleep()
}
void update_screen() { refresh(); }
void init_screen() {
initscr();
noecho();
cbreak();
nodelay(stdscr, TRUE);
}
void close_screen() { endwin(); }
#endif
// An implementation for some other system...
#ifdef _WIN32
#error "not implemented"
#endif
// The game logic, system-independent
#include <time.h> // time
#include <stdlib.h> // rand, srand
#define w 80
#define h 40
int board[w * h];
int head;
enum Dir { N, E, S, W } dir;
int quit;
enum State { SPACE=0, FOOD=1, BORDER=2 };
// negative values denote the snake (a negated time-to-live in given cell)
// reduce a time-to-live, effectively erasing the tail
void age() {
int i;
for(i = 0; i < w * h; ++i)
if(board[i] < 0)
++board[i];
}
// put a piece of food at random empty position
void plant() {
int r;
do
r = rand() % (w * h);
while(board[r] != SPACE);
board[r] = FOOD;
}
// initialize the board, plant a very first food item
void start(void) {
int i;
for(i = 0; i < w; ++i)
board[i] = board[i + (h - 1) * w] = BORDER;
for(i = 0; i < h; ++i)
board[i * w] = board[i * w + w - 1] = BORDER;
head = w * (h - 1 - h % 2) / 2; // screen center for any h
board[head] = -5;
dir = N;
quit = 0;
srand(time(0));
plant();
}
void step() {
int len = board[head];
switch(dir) {
case N: head -= w; break;
case S: head += w; break;
case W: --head; break;
case E: ++head; break;
}
switch(board[head]) {
case SPACE:
board[head] = len - 1; // keep in mind len is negative
age();
break;
case FOOD:
board[head] = len - 1;
plant();
break;
default:
quit = 1;
}
}
void show() {
const char * symbol = " @.";
int i;
for(i = 0; i < w * h; ++i)
positional_putch(i / w, i % w,
board[i] < 0 ? '#' : symbol[board[i]]);
update_screen();
}
int main (int argc, char * argv[]) {
init_screen();
start();
do {
show();
switch(nonblocking_getch()) {
case 'i': dir = N; break;
case 'j': dir = W; break;
case 'k': dir = S; break;
case 'l': dir = E; break;
case 'q': quit = 1; break;
}
step();
millisecond_sleep(100); // beware, this approach
// is not suitable for anything but toy projects like this
}
while(!quit);
millisecond_sleep(999);
close_screen();
return 0;
} |
http://rosettacode.org/wiki/Smith_numbers | Smith numbers | Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers are also known as joke numbers.
Example
Using the number 166
Find the prime factors of 166 which are: 2 x 83
Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13
Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13
Therefore, the number 166 is a Smith number.
Task
Write a program to find all Smith numbers below 10000.
See also
from Wikipedia: [Smith number].
from MathWorld: [Smith number].
from OEIS A6753: [OEIS sequence A6753].
from OEIS A104170: [Number of Smith numbers below 10^n].
from The Prime pages: [Smith numbers].
| #Arturo | Arturo | digitSum: function [v][
n: new v
result: new 0
while [n > 0][
'result + n % 10
'n / 10
]
return result
]
smith?: function [z][
return
(prime? z) ? -> false
-> (digitSum z) = sum map factors.prime z 'num [digitSum num]
]
found: 0
loop 1..10000 'x [
if smith? x [
found: found + 1
prints (pad to :string x 6) ++ " "
if 0 = found % 10 -> print ""
]
]
print "" |
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;
| #D | D | import std.stdio, std.array, std.conv, std.algorithm, std.string;
int[][] board;
int[] given, start;
void setup(string s) {
auto lines = s.splitLines;
auto cols = lines[0].split.length;
auto rows = lines.length;
given.length = 0;
board = new int[][](rows + 2, cols + 2);
foreach (row; board)
row[] = -1;
foreach (r, row; lines) {
foreach (c, cell; row.split) {
switch (cell) {
case "__":
board[r + 1][c + 1] = 0;
break;
case ".":
break;
default:
int val = cell.to!int;
board[r + 1][c + 1] = val;
given ~= val;
if (val == 1)
start = [r + 1, c + 1];
}
}
}
given.sort();
}
bool solve(int r, int c, int n, int next = 0) {
if (n > given.back)
return true;
if (board[r][c] && board[r][c] != n)
return false;
if (board[r][c] == 0 && given[next] == n)
return false;
int back = board[r][c];
board[r][c] = n;
foreach (i; -1 .. 2)
foreach (j; -1 .. 2)
if (solve(r + i, c + j, n + 1, next + (back == n)))
return true;
board[r][c] = back;
return false;
}
void printBoard() {
foreach (row; board) {
foreach (c; row)
writef(c == -1 ? " . " : c ? "%2d " : "__ ", c);
writeln;
}
}
void main() {
auto hi = "__ 33 35 __ __ . . .
__ __ 24 22 __ . . .
__ __ __ 21 __ __ . .
__ 26 __ 13 40 11 . .
27 __ __ __ 9 __ 1 .
. . __ __ 18 __ __ .
. . . . __ 7 __ __
. . . . . . 5 __";
hi.setup;
printBoard;
"\nFound:".writeln;
solve(start[0], start[1], 1);
printBoard;
} |
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.
| #Phix | Phix | -- demo\rosetta\Sokoban.exw
integer w, h -- (set from parsing the input grid)
sequence moves -- "", as +/-w and +/-1 (udlr)
string live -- "", Y if box can go there
function reachable(sequence pushes, string level)
integer p = find_any("@+",level)
string ok = repeat('N',length(level))
ok[p] = 'Y'
while true do
p = find('Y',ok)
if p=0 then exit end if
ok[p] = 'y'
for i=1 to length(moves) do
integer pn = p+moves[i]
if ok[pn]='N'
and find(level[pn]," .") then
ok[pn] = 'Y'
end if
end for
end while
for i=length(pushes)-1 to 1 by -2 do
if ok[pushes[i]-pushes[i+1]]!='y' then
pushes[i..i+1] = {}
end if
end for
return pushes
end function
function pushable(string level)
sequence res = {}
for i=1 to length(level) do
if find(level[i],"$*") then
if find(level[i-w]," .@+")
and find(level[i+w]," .@+") then
if live[i-w]='Y' then res &= {i,-w} end if
if live[i+w]='Y' then res &= {i,+w} end if
end if
if find(level[i-1]," .@+")
and find(level[i+1]," .@+") then
if live[i-1]='Y' then res &= {i,-1} end if
if live[i+1]='Y' then res &= {i,+1} end if
end if
end if
end for
return reachable(res,level)
end function
function solve(string level)
atom t2 = time()+2
integer seen = new_dict()
sequence solution = "No solution.", partial = {}
sequence todo = {{level,partial,pushable(level)}}, pushes
while length(todo) do
sequence t1 = todo[1]
todo = todo[2..$]
{level,partial,pushes} = t1
integer p = find_any("@+",level)
while length(pushes) do
integer {s,m} = pushes[1..2]
pushes = pushes[3..$]
level[p] = " ."[find(level[p],"@+")]
level[s] = "@+"[find(level[s],"$*")]
level[s+m] = "$*"[find(level[s+m]," .")]
if getd_index(level,seen)=0 then
sequence np = partial&{s,m}
if not find('$',level) then
solution = np
todo = {}
pushes = {}
exit
end if
setd(level,true,seen)
if time()>t2 then
printf(1,"working... (seen %d)\r",dict_size(seen))
t2 = time()+2
end if
todo = append(todo,{level,np,pushable(level)})
end if
level = t1[1] -- (reset)
end while
end while
destroy_dict(seen)
return solution
end function
procedure plays(string level, sequence solution)
-- This plays push-only solutions (see play() for lurd)
string res = level
integer p = find_any("@+",level)
for i=1 to length(solution) by 2 do
integer {s,m} = solution[i..i+1] m+=s
level[p] = " ."[find(level[p],"@+")]
level[s] = "@+"[find(level[s],"$*")]
level[m] = "$*"[find(level[m]," .")]
res &= level
p = s
end for
-- (replacing +0 with 1/2/3 may help in some cases)
puts(1,join_by(split(res,'\n'),h,floor(80/(w+2))+0))
end procedure
procedure mark_live(integer p, string level)
-- (idea cribbed from the C version)
if live[p]='N' then
live[p] = 'Y'
integer l = length(level)
if p-w*2>=1 and level[p-w]!='#' and level[p-w*2]!='#' then mark_live(p-w,level) end if
if p+w*2<=l and level[p+w]!='#' and level[p+w*2]!='#' then mark_live(p+w,level) end if
if p-2 >=1 and level[p-1]!='#' and level[p-2] !='#' then mark_live(p-1,level) end if
if p+2 <=l and level[p+1]!='#' and level[p+2] !='#' then mark_live(p+1,level) end if
end if
end procedure
function make_square(string level)
--
-- Sets {h, w, moves, live}, and returns an evened-out/rectangular level
--
if level[$]!='\n' then level &= '\n' end if -- (for the display)
sequence lines = split(level,'\n')
h = length(lines)-1 -- set height (ignore trailing \n)
sequence ln = repeat(0,h)
for i=1 to h do
ln[i] = {length(lines[i]),i}
for j=1 to length(lines[i]) do
-- validate each line, why not
if not find(lines[i,j]," #.$@*") then
crash("invalid input")
end if
end for
end for
ln = sort(ln)
w = ln[$][1]+1 -- set width (==longest, inc \n)
moves = {-w,+w,-1,+1} -- and make these (udlr) legal ...
for i=1 to h do
integer {l,n} = ln[i], pad = w-1-l
if pad=0 then exit end if
lines[n] &= repeat(' ',pad) -- ... by evening up the "grid"
end for
level = join(lines,'\n')
live = join(repeat(repeat('N',w-1),h),'\n')
for p=1 to length(level) do
if find(level[p],".+*") then
mark_live(p,level)
end if
end for
return level
end function
constant input = """
#######
# #
# #
#. # #
#. $$ #
#.$$ #
#.# @#
#######
"""
atom t0 = time()
string level = make_square(input)
sequence pushset = solve(level)
integer pop = length(pushset)/2
if string(pushset) then
puts(1,level)
printf(1,"%s\n",{pushset}) -- ("No Solution.")
else
printf(1,"solution of %d pushes (%s)\n",{pop,elapsed(time()-t0)})
plays(level,pushset)
end if |
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.
| #PicoLisp | PicoLisp | (load "@lib/simul.l")
# Display board
(de display ()
(disp *Board NIL
'((This)
(pack
(if2 (== This *Pos) (memq This *Goals)
"+" # Player on goal
"@" # Player elsewhere
(if (: val) "*" ".") # On gloal
(or (: val) " ") ) # Elsewhere
" " ) ) ) )
# Initialize
(de main (Lst)
(mapc
'((B L)
(mapc
'((This C)
(case C
(" ")
("." (push '*Goals This))
("@" (setq *Pos This))
("$" (=: val C) (push '*Boxes This))
(T (=: val C)) ) )
B L ) )
(setq *Board (grid (length (car Lst)) (length Lst)))
(apply mapcar (flip (mapcar chop Lst)) list) )
(display) )
# Generate possible push-moves
(de pushes ()
(make
(for Box *Boxes
(unless (or (; (west Box) val) (; (east Box) val))
(when (moves (east Box))
(link (cons (cons Box (west Box)) *Pos "L" @)) )
(when (moves (west Box))
(link (cons (cons Box (east Box)) *Pos "R" @)) ) )
(unless (or (; (south Box) val) (; (north Box) val))
(when (moves (north Box))
(link (cons (cons Box (south Box)) *Pos "D" @)) )
(when (moves (south Box))
(link (cons (cons Box (north Box)) *Pos "U" @)) ) ) ) ) )
# Moves of player to destination
(de moves (Dst Hist)
(or
(== Dst *Pos)
(mini length
(extract
'((Dir)
(with ((car Dir) Dst)
(cond
((== This *Pos) (cons (cdr Dir)))
((: val))
((memq This Hist))
((moves This (cons Dst Hist))
(cons (cdr Dir) @) ) ) ) )
'((west . "r") (east . "l") (south . "u") (north . "d")) ) ) ) )
# Find solution
(de go (Res)
(unless (idx '*Hist (sort (copy *Boxes)) T) # No repeated state
(if (find '((This) (<> "$" (: val))) *Goals)
(pick
'((Psh)
(setq # Move
*Pos (caar Psh)
*Boxes (cons (cdar Psh) (delq *Pos *Boxes)) )
(put *Pos 'val NIL)
(put (cdar Psh) 'val "$")
(prog1 (go (append (cddr Psh) Res))
(setq # Undo move
*Pos (cadr Psh)
*Boxes (cons (caar Psh) (delq (cdar Psh) *Boxes)) )
(put (cdar Psh) 'val NIL)
(put (caar Psh) 'val "$") ) )
(pushes) )
(display) # Display solution
(pack (flip Res)) ) ) ) |
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
| #Perl | Perl | package KT_Locations;
# A sequence of locations on a 2-D board whose order might or might not
# matter. Suitable for representing a partial tour, a complete tour, or the
# required locations to visit.
use strict;
use overload '""' => "as_string";
use English;
# 'locations' must be a reference to an array of 2-element array references,
# where the first element is the rank index and the second is the file index.
use Class::Tiny qw(N locations);
use List::Util qw(all);
sub BUILD {
my $self = shift;
$self->{N} //= 8;
$self->{N} >= 3 or die "N must be at least 3";
all {ref($ARG) eq 'ARRAY' && scalar(@{$ARG}) == 2} @{$self->{locations}}
or die "At least one element of 'locations' is invalid";
return;
}
sub as_string {
my $self = shift;
my %idxs;
my $idx = 1;
foreach my $loc (@{$self->locations}) {
$idxs{join(q{K},@{$loc})} = $idx++;
}
my $str;
{
my $w = int(log(scalar(@{$self->locations}))/log(10.)) + 2;
my $fmt = "%${w}d";
my $N = $self->N;
my $non_tour = q{ } x ($w-1) . q{-};
for (my $r=0; $r<$N; $r++) {
for (my $f=0; $f<$N; $f++) {
my $k = join(q{K}, $r, $f);
$str .= exists($idxs{$k}) ? sprintf($fmt, $idxs{$k}) : $non_tour;
}
$str .= "\n";
}
}
return $str;
}
sub as_idx_hash {
my $self = shift;
my $N = $self->N;
my $result;
foreach my $pair (@{$self->locations}) {
my ($r, $f) = @{$pair};
$result->{$r * $N + $f}++;
}
return $result;
}
package KnightsTour;
use strict;
# If supplied, 'str' is parsed to set 'N', 'start_location', and
# 'locations_to_visit'. 'legal_move_idxs' is for improving performance.
use Class::Tiny qw( N start_location locations_to_visit str legal_move_idxs );
use English;
use Parallel::ForkManager;
use Time::HiRes qw( gettimeofday tv_interval );
sub BUILD {
my $self = shift;
if ($self->{str}) {
my ($n, $sl, $ltv) = _parse_input_string($self->{str});
$self->{N} = $n;
$self->{start_location} = $sl;
$self->{locations_to_visit} = $ltv;
}
$self->{N} //= 8;
$self->{N} >= 3 or die "N must be at least 3";
exists($self->{start_location}) or die "Must supply start_location";
die "start_location is invalid"
if ref($self->{start_location}) ne 'ARRAY' ||
scalar(@{$self->{start_location}}) != 2;
exists($self->{locations_to_visit}) or die "Must supply locations_to_visit";
ref($self->{locations_to_visit}) eq 'KT_Locations'
or die "locations_to_visit must be a KT_Locations instance";
$self->{N} == $self->{locations_to_visit}->N
or die "locations_to_visit has mismatched board size";
$self->precompute_legal_moves();
return;
}
sub _parse_input_string {
my @rows = split(/[\r\n]+/s, shift);
my $N = scalar(@rows);
my ($start_location, @to_visit);
for (my $r=0; $r<$N; $r++) {
my $row_r = $rows[$r];
for (my $f=0; $f<$N; $f++) {
my $c = substr($row_r, $f, 1);
if ($c eq '1') { $start_location = [$r, $f]; }
elsif ($c eq '0') { push @to_visit, [$r, $f]; }
}
}
$start_location or die "No starting location provided";
return ($N,
$start_location,
KT_Locations->new(N => $N, locations => \@to_visit));
}
sub precompute_legal_moves {
my $self = shift;
my $N = $self->{N};
my $ktl_ixs = $self->{locations_to_visit}->as_idx_hash();
for (my $r=0; $r<$N; $r++) {
for (my $f=0; $f<$N; $f++) {
my $k = $r * $N + $f;
$self->{legal_move_idxs}->{$k} =
_precompute_legal_move_idxs($r, $f, $N, $ktl_ixs);
}
}
return;
}
sub _precompute_legal_move_idxs {
my ($r, $f, $N, $ktl_ixs) = @ARG;
my $r_plus_1 = $r + 1; my $r_plus_2 = $r + 2;
my $r_minus_1 = $r - 1; my $r_minus_2 = $r - 2;
my $f_plus_1 = $f + 1; my $f_plus_2 = $f + 2;
my $f_minus_1 = $f - 1; my $f_minus_2 = $f - 2;
my @result = grep { exists($ktl_ixs->{$ARG}) }
map { $ARG->[0] * $N + $ARG->[1] }
grep {$ARG->[0] >= 0 && $ARG->[0] < $N &&
$ARG->[1] >= 0 && $ARG->[1] < $N}
([$r_plus_2, $f_minus_1], [$r_plus_2, $f_plus_1],
[$r_minus_2, $f_minus_1], [$r_minus_2, $f_plus_1],
[$r_plus_1, $f_plus_2], [$r_plus_1, $f_minus_2],
[$r_minus_1, $f_plus_2], [$r_minus_1, $f_minus_2]);
return \@result;
}
sub find_tour {
my $self = shift;
my $num_to_visit = scalar(@{$self->locations_to_visit->locations});
my $N = $self->N;
my $start_loc_idx =
$self->start_location->[0] * $N + $self->start_location->[1];
my $visited; for (my $i=0; $i<$N*$N; $i++) { vec($visited, $i, 1) = 0; }
vec($visited, $start_loc_idx, 1) = 1;
# We unwind the search by one level and use Parallel::ForkManager to search
# the top-level sub-trees concurrently, assuming there are enough cores.
my @next_loc_idxs = @{$self->legal_move_idxs->{$start_loc_idx}};
my $pm = new Parallel::ForkManager(scalar(@next_loc_idxs));
foreach my $next_loc_idx (@next_loc_idxs) {
$pm->start and next; # Do the fork
my $t0 = [gettimeofday];
vec($visited, $next_loc_idx, 1) = 1; # (The fork cloned $visited.)
my $tour = _find_tour_helper($N,
$num_to_visit - 1,
$next_loc_idx,
$visited,
$self->legal_move_idxs);
my $elapsed = tv_interval($t0);
my ($r, $f) = _idx_to_rank_and_file($next_loc_idx, $N);
if (defined $tour) {
my @tour_locs =
map { [_idx_to_rank_and_file($ARG, $N)] }
($start_loc_idx, $next_loc_idx, split(/\s+/s, $tour));
my $kt_locs = KT_Locations->new(N => $N, locations => \@tour_locs);
print "Found a tour after first move ($r, $f) ",
"in $elapsed seconds:\n", $kt_locs, "\n";
}
else {
print "No tour found after first move ($r, $f). ",
"Took $elapsed seconds.\n";
}
$pm->finish; # Do the exit in the child process
}
$pm->wait_all_children;
return;
}
sub _idx_to_rank_and_file {
my ($idx, $N) = @ARG;
my $f = $idx % $N;
my $r = ($idx - $f) / $N;
return ($r, $f);
}
sub _find_tour_helper {
my ($N, $num_to_visit, $current_loc_idx, $visited, $legal_move_idxs) = @ARG;
# The performance hot spot.
local *inner_helper = sub {
my ($num_to_visit, $current_loc_idx, $visited) = @ARG;
if ($num_to_visit == 0) {
return q{ }; # Solution found.
}
my @next_loc_idxs = @{$legal_move_idxs->{$current_loc_idx}};
my $num_to_visit2 = $num_to_visit - 1;
foreach my $loc_idx2 (@next_loc_idxs) {
next if vec($visited, $loc_idx2, 1);
my $visited2 = $visited;
vec($visited2, $loc_idx2, 1) = 1;
my $recursion = inner_helper($num_to_visit2, $loc_idx2, $visited2);
return $loc_idx2 . q{ } . $recursion if defined $recursion;
}
return;
};
return inner_helper($num_to_visit, $current_loc_idx, $visited);
}
package main;
use strict;
solve_size_8_problem();
solve_size_13_problem();
exit 0;
sub solve_size_8_problem {
my $problem = <<"END_SIZE_8_PROBLEM";
--000---
--0-00--
-0000000
000--0-0
0-0--000
1000000-
--00-0--
---000--
END_SIZE_8_PROBLEM
my $kt = KnightsTour->new(str => $problem);
print "Finding a tour for an 8x8 problem...\n";
$kt->find_tour();
return;
}
sub solve_size_13_problem {
my $problem = <<"END_SIZE_13_PROBLEM";
-----1-0-----
-----0-0-----
----00000----
-----000-----
--0--0-0--0--
00000---00000
--00-----00--
00000---00000
--0--0-0--0--
-----000-----
----00000----
-----0-0-----
-----0-0-----
END_SIZE_13_PROBLEM
my $kt = KnightsTour->new(str => $problem);
print "Finding a tour for a 13x13 problem...\n";
$kt->find_tour();
return;
} |
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Sort an array of composite structures by a key.
For example, if you define a composite structure that presents a name-value pair (in pseudo-code):
Define structure pair such that:
name as a string
value as a string
and an array of such pairs:
x: array of pairs
then define a sort routine that sorts the array x by the key name.
This task can always be accomplished with Sorting Using a Custom Comparator.
If your language is not listed here, please see the other article.
| #Frink | Frink | class Pair
{
var name
var value
new[name is string, value is string] :=
{
this.name = name
this.value = value
}
}
a = [new Pair["one", "1"], new Pair["two", "2"], new Pair["three", "3"]]
sort[a, {|a,b| lexicalCompare[a.name, b.name]}]
|
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.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"sort"
)
type pair struct {
name, value string
}
type csArray []pair
// three methods satisfy sort.Interface
func (a csArray) Less(i, j int) bool { return a[i].name < a[j].name }
func (a csArray) Len() int { return len(a) }
func (a csArray) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
var x = csArray{
pair{"joe", "120"},
pair{"foo", "31"},
pair{"bar", "251"},
}
func main() {
sort.Sort(x)
for _, p := range x {
fmt.Printf("%5s: %s\n", p.name, p.value)
}
} |
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).
| #Perl | Perl | #!/usr/bin/perl
use strict;
use warnings;
my $gap = qr/.{3}/s;
find( <<terminator );
-AB-
CDEF
-GH-
terminator
sub find
{
my $p = shift;
$p =~ /(\d)$gap.{0,2}(\d)(??{abs $1 - $2 <= 1 ? '' : '(*F)'})/ ||
$p =~ /^.*\n.*(\d)(\d)(??{abs $1 - $2 <= 1 ? '' : '(*F)'})/ and return;
if( $p =~ /[A-H]/ )
{
find( $p =~ s/[A-H]/$_/r ) for grep $p !~ $_, 1 .. 8;
}
else
{
print $p =~ tr/-/ /r;
exit;
}
} |
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.
| #GAP | GAP | a := [ 8, 2, 5, 9, 1, 3, 6, 7, 4 ];
# Make a copy (with "b := a;", b and a would point to the same list)
b := ShallowCopy(a);
# Sort in place
Sort(a);
a;
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
# Sort without changing the argument
SortedList(b);
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
b;
# [ 8, 2, 5, 9, 1, 3, 6, 7, 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.
| #Go | Go | package main
import "fmt"
import "sort"
func main() {
nums := []int {2, 4, 3, 1, 2}
sort.Ints(nums)
fmt.Println(nums)
} |
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers | Sort a list of object identifiers |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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
Object identifiers (OID)
Task
Show how to sort a list of OIDs, in their natural sort order.
Details
An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number.
Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields.
Test case
Input (list of strings)
Output (list of strings)
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11150.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11150.3.4.0
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11150.3.4.0
1.3.6.1.4.1.11150.3.4.0.1
Related tasks
Natural sorting
Sort using a custom comparator
| #Sidef | Sidef | func sort_OIDs(ids) {
ids.sort_by { |id|
id.split('.').map { Num(_) }
}
}
var OIDs = %w(
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11150.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11150.3.4.0
)
sort_OIDs(OIDs).each { .say } |
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers | Sort a list of object identifiers |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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
Object identifiers (OID)
Task
Show how to sort a list of OIDs, in their natural sort order.
Details
An OID consists of one or more non-negative integers in base 10, separated by dots. It starts and ends with a number.
Their natural sort order is lexicographical with regard to the dot-separated fields, using numeric comparison between fields.
Test case
Input (list of strings)
Output (list of strings)
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11150.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11150.3.4.0
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11150.3.4.0
1.3.6.1.4.1.11150.3.4.0.1
Related tasks
Natural sorting
Sort using a custom comparator
| #Swift | Swift | import Foundation
public struct OID {
public var val: String
public init(_ val: String) {
self.val = val
}
}
extension OID: CustomStringConvertible {
public var description: String {
return val
}
}
extension OID: Comparable {
public static func < (lhs: OID, rhs: OID) -> Bool {
let split1 = lhs.val.components(separatedBy: ".").compactMap(Int.init)
let split2 = rhs.val.components(separatedBy: ".").compactMap(Int.init)
let minSize = min(split1.count, split2.count)
for i in 0..<minSize {
if split1[i] < split2[i] {
return true
} else if split1[i] > split2[i] {
return false
}
}
return split1.count < split2.count
}
public static func == (lhs: OID, rhs: OID) -> Bool {
return lhs.val == rhs.val
}
}
let ids = [
"1.3.6.1.4.1.11.2.17.19.3.4.0.10",
"1.3.6.1.4.1.11.2.17.5.2.0.79",
"1.3.6.1.4.1.11.2.17.19.3.4.0.4",
"1.3.6.1.4.1.11150.3.4.0.1",
"1.3.6.1.4.1.11.2.17.19.3.4.0.1",
"1.3.6.1.4.1.11150.3.4.0"
].map(OID.init)
for id in ids.sorted() {
print(id)
} |
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
| #Nial | Nial |
values := [7, 6, 5, 4, 3, 2, 1, 0]
indices := sortup [6, 1, 7]
values#indices := sortup values#indices
7 0 5 4 3 2 1 6
|
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
| #Nim | Nim | import algorithm
proc sortDisjoinSublist[T](data: var seq[T], indices: seq[int]) =
var indices = indices
sort indices, cmp[T]
var values: seq[T] = @[]
for i in indices: values.add data[i]
sort values, cmp[T]
for j, i in indices: data[i] = values[j]
var d = @[7, 6, 5, 4, 3, 2, 1, 0]
sortDisjoinSublist(d, @[6, 1, 7])
echo d |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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 (the values of) three variables (X, Y, and Z) that contain any value (numbers and/or literals).
If that isn't possible in your language, then just sort numbers (and note if they can be floating point, integer, or other).
I.E.: (for the three variables x, y, and z), where:
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
After sorting, the three variables would hold:
x = '(from the "Wizard of OZ")'
y = 'bears, oh my!'
z = 'lions, tigers, and'
For numeric value sorting, use:
I.E.: (for the three variables x, y, and z), where:
x = 77444
y = -12
z = 0
After sorting, the three variables would hold:
x = -12
y = 0
z = 77444
The variables should contain some form of a number, but specify if the algorithm
used can be for floating point or integers. Note any limitations.
The values may or may not be unique.
The method used for sorting can be any algorithm; the goal is to use the most idiomatic in the computer programming language used.
More than one algorithm could be shown if one isn't clearly the better choice.
One algorithm could be:
• store the three variables x, y, and z
into an array (or a list) A
• sort (the three elements of) the array A
• extract the three elements from the array and place them in the
variables x, y, and z in order of extraction
Another algorithm (only for numeric values):
x= 77444
y= -12
z= 0
low= x
mid= y
high= z
x= min(low, mid, high) /*determine the lowest value of X,Y,Z. */
z= max(low, mid, high) /* " " highest " " " " " */
y= low + mid + high - x - z /* " " middle " " " " " */
Show the results of the sort here on this page using at least the values of those shown above.
| #Wren | Wren | import "/sort" for Sort
import "/fmt" for Fmt
var sort3 = Fn.new { |x, y, z|
var a = [x, y, z]
Sort.insertion(a)
x = a[0]
y = a[1]
z = a[2]
Fmt.print(" x = $s\n y = $s\n z = $s", x, y, z)
}
System.print("After sorting strings:")
var x = "lions, tigers, and"
var y = "bears, oh my!"
var z = "(from the \"Wizard of OZ\")"
sort3.call(x, y, z)
System.print("\nAfter sorting integers:")
x = 77444
y = -12
z = 0
sort3.call(x, y, z)
System.print("\nAfter sorting floats:")
x = 11.3
y = -9.7
z = 11.17
sort3.call(x, y, z) |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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.
| #PARI.2FGP | PARI/GP | cmp(a,b)=if(#a<#b,1,if(#a>#b,-1,lex(a,b)));
vecsort(v,cmp) |
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.
| #Pascal | Pascal | use feature 'say';
@strings = qw/Here are some sample strings to be sorted/;
# with a subroutine:
sub mycmp { length $b <=> length $a || lc $a cmp lc $b }
say join ' ', sort mycmp @strings;
# inline:
say join ' ', sort {length $b <=> length $a || lc $a cmp lc $b} @strings
# for large inputs, can be faster with a 'Schwartzian' transform:
say join ' ', map { $_->[0] }
sort { $b->[1] <=> $a->[1] || $a->[2] cmp $b->[2] }
map { [ $_, length, lc ] }
@strings; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.