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/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
| #C.2B.2B | C++ | #include <iostream>
#include <cstdint>
using integer = uint32_t;
integer next_prime_digit_number(integer n) {
if (n == 0)
return 2;
switch (n % 10) {
case 2:
return n + 1;
case 3:
case 5:
return n + 2;
default:
return 2 + next_prime_digit_number(n/10) * 10;
}
}
bool is_prime(integer n) {
if (n < 2)
return false;
if (n % 2 == 0)
return n == 2;
if (n % 3 == 0)
return n == 3;
if (n % 5 == 0)
return n == 5;
constexpr integer wheel[] = { 4,2,4,2,4,6,2,6 };
integer p = 7;
for (;;) {
for (integer w : wheel) {
if (p * p > n)
return true;
if (n % p == 0)
return false;
p += w;
}
}
}
int main() {
std::cout.imbue(std::locale(""));
const integer limit = 1000000000;
integer n = 0, max = 0;
std::cout << "First 25 SPDS primes:\n";
for (int i = 0; n < limit; ) {
n = next_prime_digit_number(n);
if (!is_prime(n))
continue;
if (i < 25) {
if (i > 0)
std::cout << ' ';
std::cout << n;
}
else if (i == 25)
std::cout << '\n';
++i;
if (i == 100)
std::cout << "Hundredth SPDS prime: " << n << '\n';
else if (i == 1000)
std::cout << "Thousandth SPDS prime: " << n << '\n';
else if (i == 10000)
std::cout << "Ten thousandth SPDS prime: " << n << '\n';
max = n;
}
std::cout << "Largest SPDS prime less than " << limit << ": " << max << '\n';
return 0;
} |
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle | Solve a Hidato puzzle | The task is to write a program which solves Hidato (aka Hidoku) puzzles.
The rules are:
You are given a grid with some numbers placed in it. The other squares in the grid will be blank.
The grid is not necessarily rectangular.
The grid may have holes in it.
The grid is always connected.
The number “1” is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique.
It may be assumed that the difference between numbers present on the grid is not greater than lucky 13.
The aim is to place a natural number in each blank square so that in the sequence of numbered squares from “1” upwards, each square is in the wp:Moore neighborhood of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints).
Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order.
A square may only contain one number.
In a proper Hidato puzzle, the solution is unique.
For example the following problem
has the following solution, with path marked on it:
Related tasks
A* search algorithm
N-queens problem
Solve a Holy Knight's tour
Solve a Knight's tour
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle;
| #AutoHotkey | AutoHotkey | SolveHidato(Grid, Locked, Max, row, col, num:=1, R:="", C:=""){
if (R&&C) ; if neighbors (not first iteration)
{
Grid[R, C] := ">" num ; place num in current neighbor and mark it visited ">"
row:=R, col:=C ; move to current neighbor
}
num++ ; increment num
if (num=max) ; if reached end
return map(Grid) ; return solution
if locked[num] ; if current num is a locked value
{
row := StrSplit((StrSplit(locked[num], ",").1) , ":").1 ; find row of num
col := StrSplit((StrSplit(locked[num], ",").1) , ":").2 ; find col of num
if SolveHidato(Grid, Locked, Max, row, col, num) ; solve for current location and value
return map(Grid) ; if solved, return solution
}
else
{
for each, value in StrSplit(Neighbor(row,col), ",")
{
R := StrSplit(value, ":").1
C := StrSplit(value, ":").2
if (Grid[R,C] = "") ; a hole or out of bounds
|| InStr(Grid[R, C], ">") ; visited
|| Locked[num+1] && !(Locked[num+1]~= "\b" R ":" C "\b") ; not neighbor of locked[num+1]
|| Locked[num-1] && !(Locked[num-1]~= "\b" R ":" C "\b") ; not neighbor of locked[num-1]
|| Locked[num] ; locked value
|| Locked[Grid[R, C]] ; locked cell
continue
if SolveHidato(Grid, Locked, Max, row, col, num, R, C) ; solve for current location, neighbor and value
return map(Grid) ; if solved, return solution
}
}
num-- ; step back
for i, line in Grid
for j, element in line
if InStr(element, ">") && (StrReplace(element, ">") >= num)
Grid[i, j] := "Y"
}
;--------------------------------
;--------------------------------
;--------------------------------
Neighbor(row,col){
R := row-1
loop, 9
{
DeltaC := Mod(A_Index, 3) ? Mod(A_Index, 3)-2 : 1
res .= (R=row && !DeltaC) ? "" : R ":" col+DeltaC ","
R := Mod(A_Index, 3) ? R : R+1
}
return Trim(res, ",")
}
;--------------------------------
map(Grid){
for i, row in Grid
{
for j, element in row
line .= (A_Index > 1 ? "`t" : "") . element
map .= (map<>""?"`n":"") line
line := ""
}
return StrReplace(map, ">")
} |
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.
| #Elixir | Elixir | defmodule Sokoban do
defp setup(level) do
{leng, board} = normalize(level)
{player, goal} = check_position(board)
board = replace(board, [{".", " "}, {"+", " "}, {"*", "$"}])
lurd = [{-1, "l", "L"}, {-leng, "u", "U"}, {1, "r", "R"}, {leng, "d", "D"}]
dirs = [-1, -leng, 1, leng]
dead_zone = set_dead_zone(board, goal, dirs)
{board, player, goal, lurd, dead_zone}
end
defp normalize(level) do
board = String.split(level, "\n", trim: true)
|> Enum.map(&String.trim_trailing &1)
leng = Enum.map(board, &String.length &1) |> Enum.max
board = Enum.map(board, &String.pad_trailing(&1, leng)) |> Enum.join
{leng, board}
end
defp check_position(board) do
board = String.codepoints(board)
player = Enum.find_index(board, fn c -> c in ["@", "+"] end)
goal = Enum.with_index(board)
|> Enum.filter_map(fn {c,_} -> c in [".", "+", "*"] end, fn {_,i} -> i end)
{player, goal}
end
defp set_dead_zone(board, goal, dirs) do
wall = String.replace(board, ~r/[^#]/, " ")
|> String.codepoints
|> Enum.with_index
|> Enum.into(Map.new, fn {c,i} -> {i,c} end)
corner = search_corner(wall, goal, dirs)
set_dead_zone(wall, dirs, goal, corner, corner)
end
defp set_dead_zone(wall, dirs, goal, corner, dead) do
dead2 = Enum.reduce(corner, dead, fn pos,acc ->
Enum.reduce(dirs, acc, fn dir,acc2 ->
if wall[pos+dir] == "#", do: acc2,
else: acc2 ++ check_side(wall, dirs, pos+dir, dir, goal, dead, [])
end)
end)
if dead == dead2, do: :lists.usort(dead),
else: set_dead_zone(wall, dirs, goal, corner, dead2)
end
defp replace(string, replacement) do
Enum.reduce(replacement, string, fn {a,b},str ->
String.replace(str, a, b)
end)
end
defp search_corner(wall, goal, dirs) do
Enum.reduce(wall, [], fn {i,c},corner ->
if c == "#" or i in goal do
corner
else
case count_wall(wall, i, dirs) do
2 -> if wall[i-1] != wall[i+1], do: [i | corner], else: corner
3 -> [i | corner]
_ -> corner
end
end
end)
end
defp check_side(wall, dirs, pos, dir, goal, dead, acc) do
if wall[pos] == "#" or
count_wall(wall, pos, dirs) == 0 or
pos in goal do
[]
else
if pos in dead, do: acc, else: check_side(wall, dirs, pos+dir, dir, goal, dead, [pos|acc])
end
end
defp count_wall(wall, pos, dirs) do
Enum.count(dirs, fn dir -> wall[pos + dir] == "#" end)
end
defp push_box(board, pos, dir, route, goal, dead_zone) do
pos2dir = pos + 2 * dir
if String.at(board, pos2dir) == " " and not pos2dir in dead_zone do
board2 = board |> replace_at(pos, " ")
|> replace_at(pos+dir, "@")
|> replace_at(pos2dir, "$")
unless visited?(board2) do
if solved?(board2, goal) do
IO.puts route
exit(:normal)
else
queue_in({board2, pos+dir, route})
end
end
end
end
defp move_player(board, pos, dir) do
board |> replace_at(pos, " ") |> replace_at(pos+dir, "@")
end
defp replace_at(str, pos, c) do
{left, right} = String.split_at(str, pos)
{_, right} = String.split_at(right, 1)
left <> c <> right
# String.slice(str, 0, pos) <> c <> String.slice(str, pos+1..-1)
end
defp solved?(board, goal) do
Enum.all?(goal, fn g -> String.at(board, g) == "$" end)
end
@pattern :sokoban_pattern_set
@queue :sokoban_queue
defp start_link do
Agent.start_link(fn -> MapSet.new end, name: @pattern)
Agent.start_link(fn -> :queue.new end, name: @queue)
end
defp visited?(board) do
Agent.get_and_update(@pattern, fn set ->
{board in set, MapSet.put(set, board)}
end)
end
defp queue_in(data) do
Agent.update(@queue, fn queue -> :queue.in(data, queue) end)
end
defp queue_out do
Agent.get_and_update(@queue, fn q ->
case :queue.out(q) do
{{:value, data}, queue} -> {data, queue}
x -> x
end
end)
end
def solve(level) do
{board, player, goal, lurd, dead_zone} = setup(level)
start_link
visited?(board)
queue_in({board, player, ""})
solve(goal, lurd, dead_zone)
end
defp solve(goal, lurd, dead_zone) do
case queue_out do
{board, pos, route} ->
Enum.each(lurd, fn {dir,move,push} ->
case String.at(board, pos+dir) do
"$" -> push_box(board, pos, dir, route<>push, goal, dead_zone)
" " -> board2 = move_player(board, pos, dir)
unless visited?(board2) do
queue_in({board2, pos+dir, route<>move})
end
_ -> :not_move # wall
end
end)
_ ->
IO.puts "No solution"
exit(:normal)
end
solve(goal, lurd, dead_zone)
end
end
level = """
#######
# #
# #
#. # #
#. $$ #
#.$$ #
#.# @#
#######
"""
IO.puts level
Sokoban.solve(level) |
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.
| #Go | Go | package main
import (
"fmt"
"strings"
)
func main() {
level := `
#######
# #
# #
#. # #
#. $$ #
#.$$ #
#.# @#
#######`
fmt.Printf("level:%s\n", level)
fmt.Printf("solution:\n%s\n", solve(level))
}
func solve(board string) string {
buffer = make([]byte, len(board))
width := strings.Index(board[1:], "\n") + 1
dirs := []struct {
move, push string
dPos int
}{
{"u", "U", -width},
{"r", "R", 1},
{"d", "D", width},
{"l", "L", -1},
}
visited := map[string]bool{board: true}
open := []state{state{board, "", strings.Index(board, "@")}}
for len(open) > 0 {
s1 := &open[0]
open = open[1:]
for _, dir := range dirs {
var newBoard, newSol string
newPos := s1.pos + dir.dPos
switch s1.board[newPos] {
case '$', '*':
newBoard = s1.push(dir.dPos)
if newBoard == "" || visited[newBoard] {
continue
}
newSol = s1.cSol + dir.push
if strings.IndexAny(newBoard, ".+") < 0 {
return newSol
}
case ' ', '.':
newBoard = s1.move(dir.dPos)
if visited[newBoard] {
continue
}
newSol = s1.cSol + dir.move
default:
continue
}
open = append(open, state{newBoard, newSol, newPos})
visited[newBoard] = true
}
}
return "No solution"
}
type state struct {
board string
cSol string
pos int
}
var buffer []byte
func (s *state) move(dPos int) string {
copy(buffer, s.board)
if buffer[s.pos] == '@' {
buffer[s.pos] = ' '
} else {
buffer[s.pos] = '.'
}
newPos := s.pos + dPos
if buffer[newPos] == ' ' {
buffer[newPos] = '@'
} else {
buffer[newPos] = '+'
}
return string(buffer)
}
func (s *state) push(dPos int) string {
newPos := s.pos + dPos
boxPos := newPos + dPos
switch s.board[boxPos] {
case ' ', '.':
default:
return ""
}
copy(buffer, s.board)
if buffer[s.pos] == '@' {
buffer[s.pos] = ' '
} else {
buffer[s.pos] = '.'
}
if buffer[newPos] == '$' {
buffer[newPos] = '@'
} else {
buffer[newPos] = '+'
}
if buffer[boxPos] == ' ' {
buffer[boxPos] = '$'
} else {
buffer[boxPos] = '*'
}
return string(buffer)
} |
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
| #JavaScript | JavaScript | (() => {
'use strict';
// problems :: [[String]]
const problems = [
[
" 000 " //
, " 0 00 " //
, " 0000000" //
, "000 0 0" //
, "0 0 000" //
, "1000000 " //
, " 00 0 " //
, " 000 " //
],
[
"-----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-----" //
]
];
// GENERIC FUNCTIONS ------------------------------------------------------
// comparing :: (a -> b) -> (a -> a -> Ordering)
const comparing = f =>
(x, y) => {
const
a = f(x),
b = f(y);
return a < b ? -1 : a > b ? 1 : 0
};
// concat :: [[a]] -> [a] | [String] -> String
const concat = xs =>
xs.length > 0 ? (() => {
const unit = typeof xs[0] === 'string' ? '' : [];
return unit.concat.apply(unit, xs);
})() : [];
// charColRow :: Char -> [String] -> Maybe (Int, Int)
const charColRow = (c, rows) =>
foldr((a, xs, iRow) =>
a.nothing ? (() => {
const mbiCol = elemIndex(c, xs);
return mbiCol.nothing ? mbiCol : {
just: [mbiCol.just, iRow],
nothing: false
};
})() : a, {
nothing: true
}, rows);
// 2 or more arguments
// curry :: Function -> Function
const curry = (f, ...args) => {
const go = xs => xs.length >= f.length ? (f.apply(null, xs)) :
function () {
return go(xs.concat(Array.from(arguments)));
};
return go([].slice.call(args, 1));
};
// elem :: Eq a => a -> [a] -> Bool
const elem = (x, xs) => xs.indexOf(x) !== -1;
// elemIndex :: Eq a => a -> [a] -> Maybe Int
const elemIndex = (x, xs) => {
const i = xs.indexOf(x);
return {
nothing: i === -1,
just: i
};
};
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = (m, n) =>
Array.from({
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
// filter :: (a -> Bool) -> [a] -> [a]
const filter = (f, xs) => xs.filter(f);
// findIndex :: (a -> Bool) -> [a] -> Maybe Int
const findIndex = (f, xs) => {
for (var i = 0, lng = xs.length; i < lng; i++) {
if (f(xs[i])) return {
nothing: false,
just: i
};
}
return {
nothing: true
};
};
// foldl :: (b -> a -> b) -> b -> [a] -> b
const foldl = (f, a, xs) => xs.reduce(f, a);
// foldr (a -> b -> b) -> b -> [a] -> b
const foldr = (f, a, xs) => xs.reduceRight(f, a);
// groupBy :: (a -> a -> Bool) -> [a] -> [[a]]
const groupBy = (f, xs) => {
const dct = xs.slice(1)
.reduce((a, x) => {
const
h = a.active.length > 0 ? a.active[0] : undefined,
blnGroup = h !== undefined && f(h, x);
return {
active: blnGroup ? a.active.concat([x]) : [x],
sofar: blnGroup ? a.sofar : a.sofar.concat([a.active])
};
}, {
active: xs.length > 0 ? [xs[0]] : [],
sofar: []
});
return dct.sofar.concat(dct.active.length > 0 ? [dct.active] : []);
};
// intercalate :: String -> [a] -> String
const intercalate = (s, xs) => xs.join(s);
// intersectBy::(a - > a - > Bool) - > [a] - > [a] - > [a]
const intersectBy = (eq, xs, ys) =>
(xs.length > 0 && ys.length > 0) ?
xs.filter(x => ys.some(curry(eq)(x))) : [];
// justifyRight :: Int -> Char -> Text -> Text
const justifyRight = (n, cFiller, strText) =>
n > strText.length ? (
(cFiller.repeat(n) + strText)
.slice(-n)
) : strText;
// length :: [a] -> Int
const length = xs => xs.length;
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) => xs.map(f);
// mappendComparing :: [(a -> b)] -> (a -> a -> Ordering)
const mappendComparing = fs => (x, y) =>
fs.reduce((ord, f) => {
if (ord !== 0) return ord;
const
a = f(x),
b = f(y);
return a < b ? -1 : a > b ? 1 : 0
}, 0);
// maximumBy :: (a -> a -> Ordering) -> [a] -> a
const maximumBy = (f, xs) =>
xs.reduce((a, x) => a === undefined ? x : (
f(x, a) > 0 ? x : a
), undefined);
// min :: Ord a => a -> a -> a
const min = (a, b) => b < a ? b : a;
// replicate :: Int -> a -> [a]
const replicate = (n, a) => {
let v = [a],
o = [];
if (n < 1) return o;
while (n > 1) {
if (n & 1) o = o.concat(v);
n >>= 1;
v = v.concat(v);
}
return o.concat(v);
};
// sortBy :: (a -> a -> Ordering) -> [a] -> [a]
const sortBy = (f, xs) => xs.slice()
.sort(f);
// splitOn :: String -> String -> [String]
const splitOn = (s, xs) => xs.split(s);
// take :: Int -> [a] -> [a]
const take = (n, xs) => xs.slice(0, n);
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
// until :: (a -> Bool) -> (a -> a) -> a -> a
const until = (p, f, x) => {
let v = x;
while (!p(v)) v = f(v);
return v;
};
// zip :: [a] -> [b] -> [(a,b)]
const zip = (xs, ys) =>
xs.slice(0, Math.min(xs.length, ys.length))
.map((x, i) => [x, ys[i]]);
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = (f, xs, ys) =>
Array.from({
length: min(xs.length, ys.length)
}, (_, i) => f(xs[i], ys[i]));
// HOLY KNIGHT's TOUR FUNCTIONS -------------------------------------------
// kmoves :: (Int, Int) -> [(Int, Int)]
const kmoves = ([x, y]) => map(
([a, b]) => [a + x, b + y], [
[1, 2],
[1, -2],
[-1, 2],
[-1, -2],
[2, 1],
[2, -1],
[-2, 1],
[-2, -1]
]);
// rowPosns :: Int -> String -> [(Int, Int)]
const rowPosns = (iRow, s) => {
return foldl((a, x, i) => (elem(x, ['0', '1']) ? (
a.concat([
[i, iRow]
])
) : a), [], splitOn('', s));
};
// hash :: (Int, Int) -> String
const hash = ([col, row]) => col.toString() + '.' + row.toString();
// Start node, and degree-sorted cache of moves from each node
// All node references are hash strings (for this cache)
// problemModel :: [[String]] -> {cache: {nodeKey: [nodeKey], start:String}}
const problemModel = boardLines => {
const
steps = foldl((a, xs, i) =>
a.concat(rowPosns(i, xs)), [], boardLines),
courseMoves = (xs, [x, y]) => intersectBy(
([a, b], [c, d]) => a === c && b === d, kmoves([x, y]), xs
),
maybeStart = charColRow('1', boardLines);
return {
start: maybeStart.nothing ? '' : hash(maybeStart.just),
boardWidth: boardLines.length > 0 ? boardLines[0].length : 0,
stepCount: steps.length,
cache: (() => {
const moveCache = foldl((a, xy) => (
a[hash(xy)] = map(hash, courseMoves(steps, xy)),
a
), {}, steps),
lstMoves = Object.keys(moveCache),
dctDegree = foldl((a, k) =>
(a[k] = moveCache[k].length,
a), {}, lstMoves);
return foldl((a, k) => (
a[k] = sortBy(comparing(x => dctDegree[x]), moveCache[k]),
a
), {}, lstMoves);
})()
};
};
// firstSolution :: {nodeKey: [nodeKey]} -> Int ->
// nodeKey -> nodeKey -> [nodeKey] ->
// -> {path::[nodeKey], pathLen::Int, found::Bool}
const firstSolution = (dctMoves, intTarget, strStart, strNodeKey, path) => {
const
intPath = path.length,
moves = dctMoves[strNodeKey];
if ((intTarget - intPath) < 2 && elem(strStart, moves)) {
return {
nothing: false,
just: [strStart, strNodeKey].concat(path),
pathLen: intTarget
};
}
const
nexts = filter(k => !elem(k, path), moves),
intNexts = nexts.length,
lstFullPath = [strNodeKey].concat(path);
// Until we find a full path back to start
return until(
x => (x.nothing === false || x.i >= intNexts),
x => {
const
idx = x.i,
dctSoln = firstSolution(
dctMoves, intTarget, strStart, nexts[idx], lstFullPath
);
return {
i: idx + 1,
nothing: dctSoln.nothing,
just: dctSoln.just,
pathLen: dctSoln.pathLen
};
}, {
nothing: true,
just: [],
i: 0
}
);
};
// maybeTour :: [String] -> {
// nothing::Bool, Just::[nodeHash], i::Int: pathLen::Int }
const maybeTour = trackLines => {
const
dctModel = problemModel(trackLines),
strStart = dctModel.start;
return strStart !== '' ? firstSolution(
dctModel.cache, dctModel.stepCount, strStart, strStart, []
) : {
nothing: true
};
};
// showLine :: Int -> Int -> String -> Maybe (Int, Int) ->
// [(Int, Int, String)] -> String
const showLine = curry((intCell, strFiller, maybeStart, xs) => {
const
blnSoln = maybeStart.nothing,
[startCol, startRow] = blnSoln ? [0, 0] : maybeStart.just;
return foldl((a, [iCol, iRow, sVal], i, xs) => ({
col: iCol + 1,
txt: a.txt +
concat(replicate((iCol - a.col) * intCell, strFiller)) +
justifyRight(
intCell, strFiller,
(blnSoln ? sVal : (
iRow === startRow &&
iCol === startCol ? '1' : '0')
)
)
}), {
col: 0,
txt: ''
},
xs
)
.txt
});
// solutionString :: [String] -> Int -> String
const solutionString = (boardLines, iProblem) => {
const
dtePre = Date.now(),
intCols = boardLines.length > 0 ? boardLines[0].length : 0,
soln = maybeTour(boardLines),
intMSeconds = Date.now() - dtePre;
if (soln.nothing) return 'No solution found …';
const
kCol = 0,
kRow = 1,
kSeq = 2,
steps = soln.just,
lstTriples = zipWith((h, n) => {
const [col, row] = map(
x => parseInt(x, 10), splitOn('.', h)
);
return [col, row, n.toString()];
},
steps,
enumFromTo(1, soln.pathLen)),
cellWidth = length(maximumBy(
comparing(x => length(x[kSeq])), lstTriples
)[kSeq]) + 1,
lstGroups = groupBy(
(a, b) => a[kRow] === b[kRow],
sortBy(
mappendComparing([x => x[kRow], x => x[kCol]]),
lstTriples
)),
startXY = take(2, lstTriples[0]),
strMap = 'PROBLEM ' + (parseInt(iProblem, 10) + 1) + '.\n\n' +
unlines(map(showLine(cellWidth, ' ', {
nothing: false,
just: startXY
}), lstGroups)),
strSoln = 'First solution found in c. ' +
intMSeconds + ' milliseconds:\n\n' +
unlines(map(showLine(cellWidth, ' ', {
nothing: true,
just: startXY
}), lstGroups)) + '\n\n';
console.log(strSoln);
return strMap + '\n\n' + strSoln;
};
// TEST -------------------------------------------------------------------
return unlines(map(solutionString, problems));
})(); |
http://rosettacode.org/wiki/SOAP | SOAP | In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ).
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
| #Tcl | Tcl | package require WS::Client
# Grok the service, and generate stubs
::WS::Client::GetAndParseWsdl http://example.com/soap/wsdl
::WS::Client::CreateStubs ExampleService ;# Assume that's the service name...
# Do the calls
set result1 [ExampleService::soapFunc "hello"]
set result2 [ExampleService::anotherSoapFunc 34234] |
http://rosettacode.org/wiki/SOAP | SOAP | In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ).
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
| #Uniface | Uniface |
variables
string result1, result2
endvariables
activate "webservice".soapFunc("hello", result1)
activate "webservice".anotherSoapFunc(34234, result2)
|
http://rosettacode.org/wiki/SOAP | SOAP | In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ).
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
| #VBScript | VBScript | Dim client
Dim result
Set client = CreateObject("MSSOAP.SoapClient")
client.MSSoapInit "http://example.com/soap/wsdl"
result = client.soapFunc("hello")
result = client.anotherSoapFunc(34234) |
http://rosettacode.org/wiki/SOAP | SOAP | In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ).
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
| #Visual_Objects | Visual Objects | LOCAL oSoapClient AS OBJECT //OLEAUTOOBJECT
LOCAL cUrl AS STRING
LOCAL uResult AS USUAL
oSoapClient := OLEAutoObject{"MSSOAP.SoapClient30"}
cUrl := "http://example.com/soap/wsdl"
IF oSoapClient:fInit
oSoapClient:mssoapinit(cUrl,"", "", "" )
uResult := oSoapClient:soapFunc("hello")
uResult := oSoapClient:anotherSoapFunc(34234)
ENDIF |
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
| #Racket | Racket | #lang racket
(require "hidato-family-solver.rkt")
(define hoppy-moore-neighbour-offsets
'((+3 0) (-3 0) (0 +3) (0 -3) (+2 +2) (-2 -2) (-2 +2) (+2 -2)))
(define solve-hopido (solve-hidato-family hoppy-moore-neighbour-offsets))
(displayln
(puzzle->string
(solve-hopido
#(#(_ 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 _ _ _)))))
|
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
| #Raku | Raku | my @adjacent = [3, 0],
[2, -2], [2, 2],
[0, -3], [0, 3],
[-2, -2], [-2, 2],
[-3, 0];
solveboard q:to/END/;
. _ _ . _ _ .
_ _ _ _ _ _ _
_ _ _ _ _ _ _
. _ _ _ _ _ .
. . _ _ _ . .
. . . 1 . . .
END
sub solveboard($board) {
my $max = +$board.comb(/\w+/);
my $width = $max.chars;
my @grid;
my @known;
my @neigh;
my @degree;
@grid = $board.lines.map: -> $line {
[ $line.words.map: { /^_/ ?? 0 !! /^\./ ?? Rat !! $_ } ]
}
sub neighbors($y,$x --> List) {
eager gather for @adjacent {
my $y1 = $y + .[0];
my $x1 = $x + .[1];
take [$y1,$x1] if defined @grid[$y1][$x1];
}
}
for ^@grid -> $y {
for ^@grid[$y] -> $x {
if @grid[$y][$x] -> $v {
@known[$v] = [$y,$x];
}
if @grid[$y][$x].defined {
@neigh[$y][$x] = neighbors($y,$x);
@degree[$y][$x] = +@neigh[$y][$x];
}
}
}
print "\e[0H\e[0J";
my $tries = 0;
try_fill 1, @known[1];
sub try_fill($v, $coord [$y,$x] --> Bool) {
return True if $v > $max;
$tries++;
my $old = @grid[$y][$x];
return False if +$old and $old != $v;
return False if @known[$v] and @known[$v] !eqv $coord;
@grid[$y][$x] = $v; # conjecture grid value
print "\e[0H"; # show conjectured board
for @grid -> $r {
say do for @$r {
when Rat { ' ' x $width }
when 0 { '_' x $width }
default { .fmt("%{$width}d") }
}
}
my @neighbors = @neigh[$y][$x][];
my @degrees;
for @neighbors -> \n [$yy,$xx] {
my $d = --@degree[$yy][$xx]; # conjecture new degrees
push @degrees[$d], n; # and categorize by degree
}
for @degrees.grep(*.defined) -> @ties {
for @ties.reverse { # reverse works better for this hidato anyway
return True if try_fill $v + 1, $_;
}
}
for @neighbors -> [$yy,$xx] {
++@degree[$yy][$xx]; # undo degree conjectures
}
@grid[$y][$x] = $old; # undo grid value conjecture
return False;
}
say "$tries tries";
} |
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.
| #Elena | Elena | import system'routines;
import extensions;
public program()
{
var elements := new object[]{
KeyValue.new("Krypton", 83.798r),
KeyValue.new("Beryllium", 9.012182r),
KeyValue.new("Silicon", 28.0855r),
KeyValue.new("Cobalt", 58.933195r),
KeyValue.new("Selenium", 78.96r),
KeyValue.new("Germanium", 72.64r)};
var sorted := elements.sort:(former,later => former.Key < later.Key );
sorted.forEach:(element)
{
console.printLine(element.Key," - ",element)
}
} |
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.
| #Elixir | Elixir | defmodule Person do
defstruct name: "", value: 0
end
list = [struct(Person, [name: "Joe", value: 3]),
struct(Person, [name: "Bill", value: 4]),
struct(Person, [name: "Alice", value: 20]),
struct(Person, [name: "Harry", value: 3])]
Enum.sort(list) |> Enum.each(fn x -> IO.inspect x end)
IO.puts ""
Enum.sort_by(list, &(&1.value)) |> Enum.each(&IO.inspect &1) |
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort | Sorting algorithms/Counting 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 Counting 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)
Task
Implement the Counting sort. This is a way of sorting integers when the minimum and maximum value are known.
Pseudocode
function countingSort(array, min, max):
count: array of (max - min + 1) elements
initialize count with 0
for each number in array do
count[number - min] := count[number - min] + 1
done
z := 0
for i from min to max do
while ( count[i - min] > 0 ) do
array[z] := i
z := z+1
count[i - min] := count[i - min] - 1
done
done
The min and max can be computed apart, or be known a priori.
Note: we know that, given an array of integers, its maximum and minimum values can be always found; but if we imagine the worst case for an array that can hold up to 32 bit integers, we see that in order to hold the counts, an array of up to 232 elements may be needed. I.E.: we need to hold a count value up to 232-1, which is a little over 4.2 Gbytes. So the counting sort is more practical when the range is (very) limited, and minimum and maximum values are known a priori. (However, as a counterexample, the use of sparse arrays minimizes the impact of the memory usage, as well as removing the need of having to know the minimum and maximum values a priori.)
| #Vlang | Vlang | fn counting_sort(mut arr []int, min int, max int) {
println('Input: ' + arr.str())
mut count := [0].repeat(max - min + 1)
for i in 0 .. arr.len {
nbr := arr[i]
ndx1 := nbr - min
count[ndx1] = count[ndx1] + 1
}
mut z := 0
for i in min .. max {
curr := i - min
for count[curr] > 0 {
arr[z] = i
z++
count[curr]--
}
}
println('Output: ' + arr.str())
}
fn main() {
mut arr := [6, 2, 1, 7, 6, 8]
counting_sort(mut arr, 1, 8)
} |
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort | Sorting algorithms/Counting 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 Counting 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)
Task
Implement the Counting sort. This is a way of sorting integers when the minimum and maximum value are known.
Pseudocode
function countingSort(array, min, max):
count: array of (max - min + 1) elements
initialize count with 0
for each number in array do
count[number - min] := count[number - min] + 1
done
z := 0
for i from min to max do
while ( count[i - min] > 0 ) do
array[z] := i
z := z+1
count[i - min] := count[i - min] - 1
done
done
The min and max can be computed apart, or be known a priori.
Note: we know that, given an array of integers, its maximum and minimum values can be always found; but if we imagine the worst case for an array that can hold up to 32 bit integers, we see that in order to hold the counts, an array of up to 232 elements may be needed. I.E.: we need to hold a count value up to 232-1, which is a little over 4.2 Gbytes. So the counting sort is more practical when the range is (very) limited, and minimum and maximum values are known a priori. (However, as a counterexample, the use of sparse arrays minimizes the impact of the memory usage, as well as removing the need of having to know the minimum and maximum values a priori.)
| #Wren | Wren | var countingSort = Fn.new { |a, min, max|
var count = List.filled(max - min + 1, 0)
for (n in a) count[n - min] = count[n - min] + 1
var z = 0
for (i in min..max) {
while (count[i - min] > 0) {
a[z] = i
z = z + 1
count[i - min] = count[i - min] - 1
}
}
}
var a = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]
System.print("Unsorted: %(a)")
var min = a.reduce { |min, i| (i < min) ? i : min }
var max = a.reduce { |max, i| (i > max) ? i : max }
countingSort.call(a, min, max)
System.print("Sorted : %(a)") |
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle | Solve the no connection puzzle | You are given a box with eight holes labelled A-to-H, connected by fifteen straight lines in the pattern as shown below:
A B
/│\ /│\
/ │ X │ \
/ │/ \│ \
C───D───E───F
\ │\ /│ /
\ │ X │ /
\│/ \│/
G H
You 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).
| #Java | Java | import static java.lang.Math.abs;
import java.util.*;
import static java.util.stream.Collectors.toList;
import static java.util.stream.IntStream.range;
public class NoConnection {
// adopted from Go
static int[][] links = {
{2, 3, 4}, // A to C,D,E
{3, 4, 5}, // B to D,E,F
{2, 4}, // D to C, E
{5}, // E to F
{2, 3, 4}, // G to C,D,E
{3, 4, 5}, // H to D,E,F
};
static int[] pegs = new int[8];
public static void main(String[] args) {
List<Integer> vals = range(1, 9).mapToObj(i -> i).collect(toList());
do {
Collections.shuffle(vals);
for (int i = 0; i < pegs.length; i++)
pegs[i] = vals.get(i);
} while (!solved());
printResult();
}
static boolean solved() {
for (int i = 0; i < links.length; i++)
for (int peg : links[i])
if (abs(pegs[i] - peg) == 1)
return false;
return true;
}
static void printResult() {
System.out.printf(" %s %s%n", pegs[0], pegs[1]);
System.out.printf("%s %s %s %s%n", pegs[2], pegs[3], pegs[4], pegs[5]);
System.out.printf(" %s %s%n", pegs[6], pegs[7]);
}
} |
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle | Solve a Numbrix puzzle | Numbrix puzzles are similar to Hidato.
The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood).
Published puzzles also tend not to have holes in the grid and may not always indicate the end node.
Two examples follow:
Example 1
Problem.
0 0 0 0 0 0 0 0 0
0 0 46 45 0 55 74 0 0
0 38 0 0 43 0 0 78 0
0 35 0 0 0 0 0 71 0
0 0 33 0 0 0 59 0 0
0 17 0 0 0 0 0 67 0
0 18 0 0 11 0 0 64 0
0 0 24 21 0 1 2 0 0
0 0 0 0 0 0 0 0 0
Solution.
49 50 51 52 53 54 75 76 81
48 47 46 45 44 55 74 77 80
37 38 39 40 43 56 73 78 79
36 35 34 41 42 57 72 71 70
31 32 33 14 13 58 59 68 69
30 17 16 15 12 61 60 67 66
29 18 19 20 11 62 63 64 65
28 25 24 21 10 1 2 3 4
27 26 23 22 9 8 7 6 5
Example 2
Problem.
0 0 0 0 0 0 0 0 0
0 11 12 15 18 21 62 61 0
0 6 0 0 0 0 0 60 0
0 33 0 0 0 0 0 57 0
0 32 0 0 0 0 0 56 0
0 37 0 1 0 0 0 73 0
0 38 0 0 0 0 0 72 0
0 43 44 47 48 51 76 77 0
0 0 0 0 0 0 0 0 0
Solution.
9 10 13 14 19 20 63 64 65
8 11 12 15 18 21 62 61 66
7 6 5 16 17 22 59 60 67
34 33 4 3 24 23 58 57 68
35 32 31 2 25 54 55 56 69
36 37 30 1 26 53 74 73 70
39 38 29 28 27 52 75 72 71
40 43 44 47 48 51 76 77 78
41 42 45 46 49 50 81 80 79
Task
Write a program to solve puzzles of this ilk,
demonstrating your program by solving the above examples.
Extra credit for other interesting examples.
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 the no connection puzzle
| #Tcl | Tcl | # Loop over adjacent pairs in a list.
# Example:
# % eachpair {a b} {1 2 3} {puts $a $b}
# 1 2
# 2 3
proc eachpair {varNames ls script} {
if {[lassign $varNames _i _j] ne ""} {
return -code error "Must supply exactly two arguments"
}
tailcall foreach $_i [lrange $ls 0 end-1] $_j [lrange $ls 1 end] $script
}
namespace eval numbrix {
namespace path {::tcl::mathop ::tcl::mathfunc}
proc parse {txt} {
set map [split [string trim $txt] \n]
}
proc print {map} {
join [lmap row $map {
join [lmap val $row {
format %2d $val
}] " "
}] \n
}
proc mark {map x y i} {
lset map $x $y $i
}
proc moves {x y} {
foreach {dx dy} {
0 1
-1 0 1 0
0 -1
} {
lappend r [+ $dx $x] [+ $dy $y]
}
return $r
}
proc rmap {map} { ;# generate a reverse map in a dict {val {x y} ..}
set rmap {}
set h [llength $map]
set w [llength [lindex $map 0]]
set x $w
while {[incr x -1]>=0} {
set y $h
while {[incr y -1]>=0} {
set i [lindex $map $x $y]
if {$i} {
dict set rmap [lindex $map $x $y] [list $x $y]
}
}
}
return $rmap
}
proc gaps {rmap} { ;# list all the gaps to be filled
set known [lsort -integer [dict keys $rmap]]
set gaps {}
eachpair {i j} $known {
if {$j > $i+1} {
lappend gaps $i $j
}
}
return $gaps
}
proc fixgaps {map rmap gaps} { ;# add a "tail" gap if needed
set w [llength $map]
set h [llength [lindex $map 0]]
set size [* $h $w]
set max [max {*}[dict keys $rmap]]
if {$max ne $size} {
lappend gaps $max Inf
}
return $gaps
}
proc paths {map x0 y0 n} { ;# generate all the maps with a single path filled legally
if {$n == 0} {return [list $map]}
set i [lindex $map $x0 $y0]
set paths {}
foreach {x y} [moves $x0 $y0] {
set j [lindex $map $x $y]
if {$j eq ""} {
continue
} elseif {$j == 0 && $n == $n+1} {
return [list [mark $map $x $y [+ $i 1]]]
} elseif {$j == $i+1} {
lappend paths $map
continue
} elseif {$j || ($n == 1)} {
continue
} else {
lappend paths {*}[
paths [
mark $map $x $y [+ $i 1]
] $x $y [- $n 1]
]
}
}
return $paths
}
proc solve {map} {
# fixpoint map
while 1 { ;# first we iteratively fill in paths with distinct solutions
set rmap [rmap $map]
set gaps [gaps $rmap]
set gaps [fixgaps $map $rmap $gaps]
if {$gaps eq ""} {
return $map
}
set oldmap $map
foreach {i j} $gaps {
lassign [dict get $rmap $i] x0 y0
set n [- $j $i]
set paths [paths $map $x0 $y0 $n]
if {$paths eq ""} {
return ""
} elseif {[llength $paths] == 1} {
#puts "solved $i..$j"
#puts [print $map]
set map [lindex $paths 0]
}
;# we could intersect the paths to maybe get some tiles
}
if {$map eq $oldmap} {
break
}
}
#puts "unique paths exhausted - going DFS"
try { ;# for any left over paths, go DFS
;# we might want to sort the gaps first
foreach {i j} $gaps {
lassign [dict get $rmap $i] x0 y0
set n [- $j $i]
set paths [paths $map $x0 $y0 $n]
foreach path $paths {
#puts "recursing on $i..$j"
set sol [solve $path]
if {$sol ne ""} {
return $sol
}
}
}
}
}
namespace export {[a-z]*}
namespace ensemble create
}
set puzzles {
{
0 0 0 0 0 0 0 0 0
0 0 46 45 0 55 74 0 0
0 38 0 0 43 0 0 78 0
0 35 0 0 0 0 0 71 0
0 0 33 0 0 0 59 0 0
0 17 0 0 0 0 0 67 0
0 18 0 0 11 0 0 64 0
0 0 24 21 0 1 2 0 0
0 0 0 0 0 0 0 0 0
}
{
0 0 0 0 0 0 0 0 0
0 11 12 15 18 21 62 61 0
0 6 0 0 0 0 0 60 0
0 33 0 0 0 0 0 57 0
0 32 0 0 0 0 0 56 0
0 37 0 1 0 0 0 73 0
0 38 0 0 0 0 0 72 0
0 43 44 47 48 51 76 77 0
0 0 0 0 0 0 0 0 0
}
}
foreach puzzle $puzzles {
set map [numbrix parse $puzzle]
puts "\n== Puzzle [incr i] =="
puts [numbrix print $map]
set sol [numbrix solve $map]
if {$sol ne ""} {
puts "\n== Solution $i =="
puts [numbrix print $sol]
} else {
puts "\n== No Solution for Puzzle $i =="
}
} |
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.
| #Euphoria | Euphoria | include sort.e
print(1,sort({20, 7, 65, 10, 3, 0, 8, -60})) |
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.23 | F# | // sorting an array in place
let nums = [| 2; 4; 3; 1; 2 |]
Array.sortInPlace nums
// create a sorted copy of a list
let nums2 = [2; 4; 3; 1; 2]
let sorted = List.sort nums2 |
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
| #PicoLisp | PicoLisp | (for I
(by
'((L) (mapcar format (split (chop L) ".")))
sort
(quote
"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" ) )
(prinl I) ) |
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
| #Prolog | Prolog | main:-
sort_oid_list(["1.3.6.1.4.1.11.2.17.19.3.4.0.10",
"1.3.6.1.4.1.11.2.17.5.2.0.79",
"1.3.6.1.4.1.11.2.17.19.3.4.0.4",
"1.3.6.1.4.1.11150.3.4.0.1",
"1.3.6.1.4.1.11.2.17.19.3.4.0.1",
"1.3.6.1.4.1.11150.3.4.0"], Sorted_list),
foreach(member(oid(_, Oid), Sorted_list), writeln(Oid)).
sort_oid_list(Oid_list, Sorted_list):-
parse_oid_list(Oid_list, Parsed),
sort(1, @=<, Parsed, Sorted_list).
parse_oid_list([], []):-!.
parse_oid_list([Oid|Oid_list], [oid(Numbers, Oid)|Parsed]):-
parse_oid(Oid, Numbers),
parse_oid_list(Oid_list, Parsed).
parse_oid(Oid, Numbers):-
split_string(Oid, ".", ".", Strings),
number_strings(Numbers, Strings).
number_strings([], []):-!.
number_strings([Number|Numbers], [String|Strings]):-
number_string(Number, String),
number_strings(Numbers, Strings). |
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
| #JavaScript | JavaScript | function sort_disjoint(values, indices) {
var sublist = [];
indices.sort(function(a, b) { return a > b; });
for (var i = 0; i < indices.length; i += 1) {
sublist.push(values[indices[i]]);
}
sublist.sort(function(a, b) { return a < b; });
for (var i = 0; i < indices.length; i += 1) {
values[indices[i]] = sublist.pop();
}
return 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.
| #Red | Red | foreach [x y z] [
"lions, tigers, and"
"bears, oh my!"
{(from the "Wizard of OZ")}
77444 -12 0
3.1416 3.1415926 3.141592654
#"z" #"0" #"A"
216.239.36.21 172.67.134.114 127.0.0.1
[email protected] [email protected] [email protected]
potato carrot cabbage
][
set [x y z] sort reduce [x y z]
print ["x:" mold x "y:" mold y "z:" mold 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.
| #REXX | REXX | /*REXX program sorts three (any value) variables (X, Y, and Z) into ascending order.*/
parse arg x y z . /*obtain the three variables from C.L. */
if x=='' | x=="," then x= 'lions, tigers, and' /*Not specified? Use the default*/
if y=='' | y=="," then y= 'bears, oh my!' /* " " " " " */
if z=='' | z=="," then z= '(from "The Wizard of Oz")' /* " " " " " */
say '───── original value of X: ' x
say '───── original value of Y: ' y
say '───── original value of Z: ' z
if x>y then do; _= x; x= y; y= _; end /*swap the values of X and Y. */ /* ◄─── sorting.*/
if y>z then do; _= y; y= z; z= _; end /* " " " " Y " Z. */ /* ◄─── sorting.*/
if x>y then do; _= x; x= y; y= _; end /* " " " " X " Y. */ /* ◄─── sorting */
say /*stick a fork in it, we're all done. */
say '═════ sorted value of X: ' x
say '═════ sorted value of Y: ' y
say '═════ sorted value of 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.
| #Objeck | Objeck | use Collection;
class Test {
function : Main(args : String[]) ~ Nil {
v := CreateHolders(["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]);
"unsorted: "->Print(); Show(v);
v->Sort();
"sorted: "->Print(); Show(v);
}
function : CreateHolders(strings : String[]) ~ CompareVector {
vector := CompareVector->New();
each(i : strings) {
vector->AddBack(StringHolder->New(strings[i]));
};
return vector;
}
function : Show(v : CompareVector) ~ Nil {
each(i : v) {
s := v->Get(i)->As(StringHolder);
s->ToString()->Print();
if(i + 1 < v->Size()) {
','->Print();
};
};
'\n'->Print();
}
}
class StringHolder implements Compare {
@s : String;
New(s : String) {
@s := s;
}
method : public : Compare(c : Compare) ~ Int {
h := c->As(StringHolder);
r := h->ToString();
size := r->Size() - @s->Size();
if(size = 0) {
size := @s->ToUpper()->Compare(r->ToUpper());
};
return size;
}
method : public : HashID() ~ Int {
return @s->HashID();
}
method : public : ToString() ~ String {
return @s;
}
} |
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.
| #SNOBOL4 | SNOBOL4 | * Library for random()
-include 'Random.sno'
* # String -> array
define('s2a(str,n)i') :(s2a_end)
s2a s2a = array(n); str = str ' '
sa1 str break(' ') . s2a<i = i + 1> span(' ') = :s(sa1)f(return)
s2a_end
* # Array -> string
define('a2s(a)i') :(a2s_end)
a2s a2s = a2s a<i = i + 1> ' ' :s(a2s)f(return)
a2s_end
* # Knuth shuffle in-place
define('shuffle(a)alen,n,k,tmp') :(shuffle_end)
shuffle n = alen = prototype(a);
sh1 k = convert(random() * alen,'integer') + 1
eq(a<n>,a<k>) :s(sh2)
tmp = a<n>; a<n> = a<k>; a<k> = tmp
sh2 n = gt(n,1) n - 1 :s(sh1)
shuffle = a :(return)
shuffle_end
* # sorted( ) predicate -> Succeed/Fail
define('sorted(a)alen,i') :(sorted_end)
sorted alen = prototype(a); i = 1
std1 i = lt(i,alen) i + 1 :f(return)
gt(a<i - 1>,a<i>) :s(freturn)f(std1)
sorted_end
* # Bogosort
define('bogo(a)') :(bogo_end)
bogo output = (i = i + 1) ': ' a2s(a)
bogo = sorted(a) a :s(return)
shuffle(a) :(bogo)
bogo_end
* # Test and display
bogo(s2a('5 4 3 2 1',5))
end |
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.
| #F.23 | F# | let BubbleSort (lst : list<int>) =
let rec sort accum rev lst =
match lst, rev with
| [], true -> accum |> List.rev
| [], false -> accum |> List.rev |> sort [] true
| x::y::tail, _ when x > y -> sort (y::accum) false (x::tail)
| head::tail, _ -> sort (head::accum) rev tail
sort [] true lst
|
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.
| #PARI.2FGP | PARI/GP | gnomeSort(v)={
my(i=2,j=3,n=#v,t);
while(i<=n,
if(v[i-1]>v[i],
t=v[i];
v[i]=v[i-1];
v[i--]=t;
if(i==1, i=j; j++);
,
i=j;
j++
)
);
v
}; |
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
| #Objeck | Objeck | bundle Default {
class Cocktail {
function : Main(args : String[]) ~ Nil {
values := [5, -1, 101, -4, 0, 1, 8, 6, 2, 3 ];
CocktailSort(values);
each(i : values) {
values[i]->PrintLine();
};
}
function : CocktailSort(a : Int[]) ~ Nil {
swapped : Bool;
do {
swapped := false;
continue := true;
for (i := 0; i <= a->Size() - 2 & continue; i += 1;) {
if(a[i] > a[i + 1]) {
temp := a[i];
a[i] := a[i+1];
a[i+1] := temp;
swapped := true;
};
};
if(swapped <> true) {
continue := false;
};
swapped := false;
for(i := a->Size() - 2; i >= 0; i -= 1;){
if(a[i] > a[i + 1]) {
temp := a[i];
a[i] := a[i+1];
a[i + 1] := temp;
swapped := true;
};
};
}
while(swapped);
}
}
} |
http://rosettacode.org/wiki/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #Cind | Cind |
var libsocket = @("lib","socket");
// connect
int socket = libsocket.connect("localhost",256);
// send data
{
sheet data = (sheet)"hello socket world";
int datalen = data.size();
int was = libsocket.send(socket,data,0,datalen);
// assuming here that all data has been sent (if not, send them in some loop)
}
// close socket
libsocket.close(socket);
|
http://rosettacode.org/wiki/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #Clojure | Clojure | (ns socket-example
(:import (java.net Socket)
(java.io PrintWriter)))
(defn send-data [host msg]
(with-open [sock (Socket. host 256)
printer (PrintWriter. (.getOutputStream sock))]
(.println printer msg)))
(send-data "localhost" "hello socket world") |
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.
| #F.23 | F# |
// Sleeping Beauty: Nigel Galloway. May 16th., 2021
let heads,woken=let n=System.Random() in {1..1000}|>Seq.fold(fun(h,w) g->match n.Next(2) with 0->(h+1,w+1) |_->(h,w+2))(0,0)
printfn "During 1000 tosses Sleeping Beauty woke %d times, %d times the toss was heads. %.0f%% of times heads had been tossed when she awoke" woken heads (100.0*float(heads)/float(woken))
|
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.
| #Factor | Factor | USING: combinators.random io kernel math prettyprint ;
: sleeping ( n -- heads wakenings )
0 0 rot [ 1 + .5 [ [ 1 + ] dip ] [ 1 + ] ifp ] times ;
"Wakenings over 1,000,000 experiments: " write
1e6 sleeping dup . /f
"Sleeping Beauty should estimate a credence of: " write . |
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.
| #Go | Go | package main
import (
"fmt"
"math/rand"
"rcu"
"time"
)
func sleepingBeauty(reps int) float64 {
wakings := 0
heads := 0
for i := 0; i < reps; i++ {
coin := rand.Intn(2) // heads = 0, tails = 1 say
wakings++
if coin == 0 {
heads++
} else {
wakings++
}
}
fmt.Printf("Wakings over %s repetitions = %s\n", rcu.Commatize(reps), rcu.Commatize(wakings))
return float64(heads) / float64(wakings) * 100
}
func main() {
rand.Seed(time.Now().UnixNano())
pc := sleepingBeauty(1e6)
fmt.Printf("Percentage probability of heads on waking = %f%%\n", pc)
} |
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
| #F.23 | F# |
// Generate Smarandache prime-digital sequence. Nigel Galloway: May 31st., 2019
let rec spds g=seq{yield! g; yield! (spds (Seq.collect(fun g->[g*10+2;g*10+3;g*10+5;g*10+7]) g))}|>Seq.filter(isPrime)
spds [2;3;5;7] |> Seq.take 25 |> Seq.iter(printfn "%d")
printfn "\n\n100th item of this sequence is %d" (spds [2;3;5;7] |> Seq.item 99)
printfn "1000th item of this sequence is %d" (spds [2;3;5;7] |> Seq.item 999)
|
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;
| #Bracmat | Bracmat | (
( hidato
= Line solve lowest Ncells row column rpad
, Board colWidth maxDigits start curCol curRow
, range head line cellN solution output tail
. out$!arg
& @(!arg:? ((%@:>" ") ?:?arg))
& 0:?row:?column
& :?Board
& ( Line
= token
. whl
' ( @(!arg:?token [3 ?arg)
& ( ( @(!token:? "_" ?)
& :?token
| @(!token:? #?token (|" " ?))
)
& (!token.!row.!column) !Board:?Board
|
)
& 1+!column:?column
)
)
& whl
' ( @(!arg:?line \n ?arg)
& Line$!line
& 1+!row:?row
& 0:?column
)
& Line$!arg
& ( range
= hi lo
. (!arg+1:?hi)+-2:?lo
& '($lo|$arg|$hi)
)
& ( solve
= ToDo cellN row column head tail remainder
, candCell Solved rowCand colCand pattern recurse
. !arg:(?ToDo.?cellN.?row.?column)
& range$!row:(=?row)
& range$!column:(=?column)
&
' ( ?head ($cellN.?rowCand.?colCand) ?tail
& (!rowCand.!colCand):($row.$column)
& !recurse
| ?head
(.($row.$column):(?rowCand.?colCand))
(?tail&!recurse)
. ((!rowCand.!colCand).$cellN)
: ?candCell
& ( !head !tail:
& out$found!
& !candCell
| solve
$ ( !head !tail
. $cellN+1
. !rowCand
. !colCand
)
: ?remainder
& !candCell+!remainder
)
: ?Solved
)
: (=?pattern.?recurse)
& !ToDo:!pattern
& !Solved
)
& infinity:?lowest
& ( !Board
: ? (<!lowest:#%?lowest.?start) (?&~)
| solve$(!Board.!lowest.!start):?solution
)
& :?output
& 0:?curCol
& !solution:((?curRow.?).?)+?+[?Ncells
& @(!Ncells:? [?maxDigits)
& 1+!maxDigits:?colWidth
& ( rpad
= len
. !arg:(?arg.?len)
& @(str$(!arg " "):?arg [!len ?)
& !arg
)
& whl
' ( !solution:((?row.?column).?cellN)+?solution
& ( !row:>!curRow:?curRow
& !output \n:?output
& 0:?curCol
|
)
& whl
' ( !curCol+1:~>!column:?curCol
& !output rpad$(.!colWidth):?output
)
& !output rev$(rpad$(rev$(str$(!cellN " ")).!colWidth))
: ?output
& !curCol+1:?curCol
)
& str$!output
)
& "
__ 33 35 __ __
__ __ 24 22 __
__ __ __ 21 __ __
__ 26 __ 13 40 11
27 __ __ __ 9 __ 1
__ __ 18 __ __
__ 7 __ __
5 __"
: ?board
& out$(hidato$!board)
); |
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.
| #Haskell | Haskell | import Control.Monad (liftM)
import Data.Array
import Data.List (transpose)
import Data.Maybe (mapMaybe)
import qualified Data.Sequence as Seq
import qualified Data.Set as Set
import Prelude hiding (Left, Right)
data Field = Space | Wall | Goal
deriving (Eq)
data Action = Up | Down | Left | Right | PushUp | PushDown | PushLeft | PushRight
instance Show Action where
show Up = "u"
show Down = "d"
show Left = "l"
show Right = "r"
show PushUp = "U"
show PushDown = "D"
show PushLeft = "L"
show PushRight = "R"
type Index = (Int, Int)
type FieldArray = Array Index Field
type BoxArray = Array Index Bool
type PlayerPos = Index
type GameState = (BoxArray, PlayerPos)
type Game = (FieldArray, GameState)
toField :: Char -> Field
toField '#' = Wall
toField ' ' = Space
toField '@' = Space
toField '$' = Space
toField '.' = Goal
toField '+' = Goal
toField '*' = Goal
toPush :: Action -> Action
toPush Up = PushUp
toPush Down = PushDown
toPush Left = PushLeft
toPush Right = PushRight
toPush n = n
toMove :: Action -> Index
toMove PushUp = ( 0, -1)
toMove PushDown = ( 0, 1)
toMove PushLeft = (-1, 0)
toMove PushRight = ( 1, 0)
toMove n = toMove $ toPush n
-- Parse the string-based game board into an easier-to-use format.
-- Assume that the board is valid (rectangular, one player, etc).
parseGame :: [String] -> Game
parseGame fieldStrs = (field, (boxes, player))
where
width = length $ head fieldStrs
height = length fieldStrs
bound = ((0, 0), (width - 1, height - 1))
flatField = concat $ transpose fieldStrs
charField = listArray bound flatField
field = fmap toField charField
boxes = fmap (`elem` "$*") charField
player = fst $ head $ filter (flip elem "@+" . snd) $ assocs charField
add :: (Num a, Num b) => (a, b) -> (a, b) -> (a, b)
add (a, b) (x, y) = (a + x, b + y)
-- Attempt to perform an action, returning the updated game and adjusted
-- action if the action was legal.
tryAction :: Game -> Action -> Maybe (Game, Action)
tryAction (field, (boxes, player)) action
| field ! vec == Wall = Nothing
| boxes ! vec =
if boxes ! vecB || field ! vecB == Wall
then Nothing
else Just ((field, (boxes // [(vec, False), (vecB, True)], vec)),
toPush action)
| otherwise = Just ((field, (boxes, vec)), action)
where
actionVec = toMove action
vec = player `add` actionVec
vecB = vec `add` actionVec
-- Search the game for a solution.
solveGame :: Game -> Maybe [Action]
solveGame (field, initState) =
liftM reverse $ bfs (Seq.singleton (initState, [])) (Set.singleton initState)
where
goals = map fst $ filter ((== Goal) . snd) $ assocs field
isSolved st = all (st !) goals
possibleActions = [Up, Down, Left, Right]
-- Breadth First Search of the game tree.
bfs :: Seq.Seq (GameState, [Action]) -> Set.Set GameState -> Maybe [Action]
bfs queue visited =
case Seq.viewl queue of
Seq.EmptyL -> Nothing
(game@(boxes, _), actions) Seq.:< queueB ->
if isSolved boxes
then Just actions
else
let newMoves = filter (flip Set.notMember visited . fst) $
map (\((_, g), a) -> (g, a)) $
mapMaybe (tryAction (field, game)) possibleActions
visitedB = foldl (flip Set.insert) visited $
map fst newMoves
queueC = foldl (Seq.|>) queueB $
map (\(g, a) -> (g, a:actions)) newMoves
in bfs queueC visitedB
exampleA :: [String]
exampleA =
["#######"
,"# #"
,"# #"
,"#. # #"
,"#. $$ #"
,"#.$$ #"
,"#.# @#"
,"#######"]
main :: IO ()
main =
case solveGame $ parseGame exampleA of
Nothing -> putStrLn "Unsolvable"
Just solution -> do
mapM_ putStrLn exampleA
putStrLn ""
putStrLn $ concatMap show solution |
http://rosettacode.org/wiki/Solve_a_Holy_Knight%27s_tour | Solve a Holy Knight's tour |
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies.
This kind of knight's tour puzzle is similar to Hidato.
The present task is to produce a solution to such problems. At least demonstrate your program by solving the following:
Example
0 0 0
0 0 0
0 0 0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
1 0 0 0 0 0 0
0 0 0
0 0 0
Note that the zeros represent the available squares, not the pennies.
Extra credit is available for other interesting examples.
Related tasks
A* search algorithm
Knight's tour
N-queens problem
Solve a Hidato puzzle
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle
| #Julia | Julia | using .Hidato # Note that the . here means to look locally for the module rather than in the libraries
const holyknight = """
. 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 . . """
const knightmoves = [[-2, -1], [-2, 1], [-1, -2], [-1, 2], [1, -2], [1, 2], [2, -1], [2, 1]]
board, maxmoves, fixed, starts = hidatoconfigure(holyknight)
printboard(board, " 0", " ")
hidatosolve(board, maxmoves, knightmoves, fixed, starts[1][1], starts[1][2], 1)
printboard(board)
|
http://rosettacode.org/wiki/SOAP | SOAP | In this task, the goal is to create a SOAP client which accesses functions defined at http://example.com/soap/wsdl, and calls the functions soapFunc( ) and anotherSoapFunc( ).
This task has been flagged for clarification. Code on this page in its current state may be flagged incorrect once this task has been clarified. See this page's Talk page for discussion.
| #Wren | Wren | /* soap.wren */
var CURLOPT_URL = 10002
var CURLOPT_POST = 47
var CURLOPT_READFUNCTION = 20012
var CURLOPT_READDATA = 10009
var CURLOPT_WRITEFUNCTION = 20011
var CURLOPT_WRITEDATA = 10001
var CURLOPT_HTTPHEADER = 10023
var CURLOPT_POSTFIELDSIZE_LARGE = 30120
var CURLOPT_VERBOSE = 41
foreign class File {
foreign static url
foreign static readFile
foreign static writeFile
construct open(filename, mode) {}
}
foreign class CurlSlist {
construct new() {}
foreign append(s)
}
foreign class Curl {
construct easyInit() {}
foreign easySetOpt(opt, param)
foreign easyPerform()
foreign easyCleanup()
}
var soap = Fn.new { |url, inFile, outFile|
var rfp = File.open(inFile, "r")
if (rfp == 0) Fiber.abort("Error opening read file.")
var wfp = File.open(outFile, "w+")
if (wfp == 0) Fiber.abort("Error opening write file.")
var header = CurlSlist.new()
header = header.append("Content-Type:text/xml")
header = header.append("SOAPAction: rsc")
header = header.append("Transfer-Encoding: chunked")
header = header.append("Expect:")
var curl = Curl.easyInit()
if (curl == 0) Fiber.abort("Error initializing cURL.")
curl.easySetOpt(CURLOPT_URL, url)
curl.easySetOpt(CURLOPT_POST, 1)
curl.easySetOpt(CURLOPT_READFUNCTION, 0) // read function to be supplied by C
curl.easySetOpt(CURLOPT_READDATA, rfp)
curl.easySetOpt(CURLOPT_WRITEFUNCTION, 0) // write function to be supplied by C
curl.easySetOpt(CURLOPT_WRITEDATA, wfp)
curl.easySetOpt(CURLOPT_HTTPHEADER, header)
curl.easySetOpt(CURLOPT_POSTFIELDSIZE_LARGE, -1)
curl.easySetOpt(CURLOPT_VERBOSE, 1)
curl.easyPerform()
curl.easyCleanup()
}
soap.call(File.url, File.readFile, File.writeFile) |
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
| #REXX | REXX | /*REXX program solves a Hopido puzzle, it also displays the puzzle and the solution. */
call time 'Reset' /*reset the REXX elapsed timer to zero.*/
maxR=0; maxC=0; maxX=0; minR=9e9; minC=9e9; minX=9e9; cells=0; @.=
parse arg xxx /*get the cell definitions from the CL.*/
xxx=translate(xxx, , "/\;:_", ',') /*also allow other characters as comma.*/
do while xxx\=''; parse var xxx r c marks ',' xxx
do while marks\=''; [email protected]
parse var marks x marks
if datatype(x,'N') then x=x/1 /*normalize X. */
minR=min(minR,r); maxR=max(maxR,r); minC=min(minC,c); maxC=max(maxC,c)
if x==1 then do; !r=r; !c=c; end /*the START cell. */
if _\=='' then call err "cell at" r c 'is already occupied with:' _
@.r.c=x; c=c+1; cells=cells+1 /*assign a mark. */
if x==. then iterate /*is a hole? Skip*/
if \datatype(x,'W') then call err 'illegal marker specified:' x
minX=min(minX,x); maxX=max(maxX,x) /*min and max X. */
end /*while marks¬='' */
end /*while xxx ¬='' */
call show /* [↓] is used for making fast moves. */
Nr = '0 3 0 -3 -2 2 2 -2' /*possible row for the next move. */
Nc = '3 0 -3 0 2 -2 2 -2' /* " column " " " " */
pMoves=words(Nr) /*the number of possible moves. */
do i=1 for pMoves; Nr.i=word(Nr, i); Nc.i=word(Nc,i); end /*i*/
if \next(2,!r,!c) then call err 'No solution possible for this Hopido puzzle.'
say 'A solution for the Hopido exists.'; say; call show
etime= format(time('Elapsed'), , 2) /*obtain the elapsed time (in seconds).*/
if etime<.1 then say 'and took less than 1/10 of a second.'
else say 'and took' etime "seconds."
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say; say '***error*** (from Hopido): ' arg(1); say; exit 13
/*──────────────────────────────────────────────────────────────────────────────────────*/
next: procedure expose @. Nr. Nc. cells pMoves; parse arg #,r,c; ##=#+1
do t=1 for pMoves /* [↓] try some moves. */
parse value r+Nr.t c+Nc.t with nr nc /*next move coördinates*/
if @.nr.nc==. then do; @.nr.nc=# /*let's try this move. */
if #==cells then leave /*is this the last move?*/
if next(##,nr,nc) then return 1
@.nr.nc=. /*undo the above move. */
iterate /*go & try another move.*/
end
if @.nr.nc==# then do /*this a fill-in move ? */
if #==cells then return 1 /*this is the last move.*/
if next(##,nr,nc) then return 1 /*a fill-in move. */
end
end /*t*/
return 0 /*This ain't working. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: if maxR<1 | maxC<1 then call err 'no legal cell was specified.'
if minX<1 then call err 'no 1 was specified for the puzzle start'
w=max(2,length(cells)); do r=maxR to minR by -1; _=
do c=minC to maxC; _=_ right(@.r.c,w); end /*c*/
say _
end /*r*/
say; 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.
| #Erlang | Erlang | 1> lists:sort([{{2006,2007},"Ducks"},
{{2000,2001},"Avalanche"},
{{2002,2003},"Devils"},
{{2001,2002},"Red Wings"},
{{2003,2004},"Lightning"},
{{2004,2005},"N/A: lockout"},
{{2005,2006},"Hurricanes"},
{{1999,2000},"Devils"},
{{2007,2008},"Red Wings"},
{{2008,2009},"Penguins"}]).
[{{1999,2000},"Devils"},
{{2000,2001},"Avalanche"},
{{2001,2002},"Red Wings"},
{{2002,2003},"Devils"},
{{2003,2004},"Lightning"},
{{2004,2005},"N/A: lockout"},
{{2005,2006},"Hurricanes"},
{{2006,2007},"Ducks"},
{{2007,2008},"Red Wings"},
{{2008,2009},"Penguins"}] |
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort | Sorting algorithms/Counting 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 Counting 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)
Task
Implement the Counting sort. This is a way of sorting integers when the minimum and maximum value are known.
Pseudocode
function countingSort(array, min, max):
count: array of (max - min + 1) elements
initialize count with 0
for each number in array do
count[number - min] := count[number - min] + 1
done
z := 0
for i from min to max do
while ( count[i - min] > 0 ) do
array[z] := i
z := z+1
count[i - min] := count[i - min] - 1
done
done
The min and max can be computed apart, or be known a priori.
Note: we know that, given an array of integers, its maximum and minimum values can be always found; but if we imagine the worst case for an array that can hold up to 32 bit integers, we see that in order to hold the counts, an array of up to 232 elements may be needed. I.E.: we need to hold a count value up to 232-1, which is a little over 4.2 Gbytes. So the counting sort is more practical when the range is (very) limited, and minimum and maximum values are known a priori. (However, as a counterexample, the use of sparse arrays minimizes the impact of the memory usage, as well as removing the need of having to know the minimum and maximum values a priori.)
| #XPL0 | XPL0 | include c:\cxpl\codes;
proc CountingSort(Array, Min, Max, Size); \Sort Array
int Array, Min, Max, Size; \minimum, maximum values, number of elements
int Count, I, Z;
[Count:= Reserve((Max-Min+1)*4); \Reserve Count with 4 bytes per integer
for I:= 0 to Max-Min do Count(I):= 0; \initialize Count with 0
for I:= 0 to Size-1 do \for each number count its occurrences
Count(Array(I)-Min):= Count(Array(I)-Min) + 1;
Z:= 0;
for I:= Min to Max do
while Count(I-Min) > 0 do
[Array(Z):= I;
Z:= Z+1;
Count(I-Min):= Count(I-Min) - 1;
];
];
int A, I;
[A:= [3, 1, 4, 1, -5, 9, 2, 6, 5, 4];
CountingSort(A, -5, 9, 10);
for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )];
] |
http://rosettacode.org/wiki/Sorting_algorithms/Counting_sort | Sorting algorithms/Counting 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 Counting 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)
Task
Implement the Counting sort. This is a way of sorting integers when the minimum and maximum value are known.
Pseudocode
function countingSort(array, min, max):
count: array of (max - min + 1) elements
initialize count with 0
for each number in array do
count[number - min] := count[number - min] + 1
done
z := 0
for i from min to max do
while ( count[i - min] > 0 ) do
array[z] := i
z := z+1
count[i - min] := count[i - min] - 1
done
done
The min and max can be computed apart, or be known a priori.
Note: we know that, given an array of integers, its maximum and minimum values can be always found; but if we imagine the worst case for an array that can hold up to 32 bit integers, we see that in order to hold the counts, an array of up to 232 elements may be needed. I.E.: we need to hold a count value up to 232-1, which is a little over 4.2 Gbytes. So the counting sort is more practical when the range is (very) limited, and minimum and maximum values are known a priori. (However, as a counterexample, the use of sparse arrays minimizes the impact of the memory usage, as well as removing the need of having to know the minimum and maximum values a priori.)
| #zkl | zkl | fcn countingSort(array, min, max){ // modifies array
count:=(max - min + 1).pump(List().write,0); // array of (max - min + 1) zeros
foreach number in (array){
count[number - min] += 1;
}
z:=-1;
foreach i in ([min .. max]){
do(count[i - min]){ array[z += 1] = i }
}
array
} |
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).
| #JavaScript | JavaScript | (() => {
'use strict';
// -------------- NO CONNECTION PUZZLE ---------------
// solvedPuzzle :: () -> [Int]
const solvedPuzzle = () => {
// universe :: [[Int]]
const universe = permutations(enumFromTo(1)(8));
// isSolution :: [Int] -> Bool
const isSolution = ([a, b, c, d, e, f, g, h]) =>
all(x => abs(x) > 1)([
a - d, c - d, g - d, e - d, a - c, c - g,
g - e, e - a, b - e, d - e, h - e, f - e,
b - d, d - h, h - f, f - b
]);
return universe[
until(i => isSolution(universe[i]))(
succ
)(0)
];
}
// ---------------------- TEST -----------------------
const main = () => {
const
firstSolution = solvedPuzzle(),
[a, b, c, d, e, f, g, h] = firstSolution;
return unlines(
zipWith(
a => n => a + ' = ' + n.toString()
)(enumFromTo('A')('H'))(firstSolution)
.concat([
[],
[a, b],
[c, d, e, f],
[g, h]
].map(
xs => unwords(xs.map(show))
.padStart(5, ' ')
))
);
}
// ---------------- GENERIC FUNCTIONS ----------------
// abs :: Num -> Num
const abs =
// Absolute value of a given number - without the sign.
Math.abs;
// all :: (a -> Bool) -> [a] -> Bool
const all = p =>
// True if p(x) holds for every x in xs.
xs => [...xs].every(p);
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (...fs) =>
// A function defined by the right-to-left
// composition of all the functions in fs.
fs.reduce(
(f, g) => x => f(g(x)),
x => x
);
// enumFromTo :: Enum a => a -> a -> [a]
const enumFromTo = m => n => {
const [x, y] = [m, n].map(fromEnum),
b = x + (isNaN(m) ? 0 : m - x);
return Array.from({
length: 1 + (y - x)
}, (_, i) => toEnum(m)(b + i));
};
// fromEnum :: Enum a => a -> Int
const fromEnum = x =>
typeof x !== 'string' ? (
x.constructor === Object ? (
x.value
) : parseInt(Number(x))
) : x.codePointAt(0);
// length :: [a] -> Int
const length = xs =>
// Returns Infinity over objects without finite
// length. This enables zip and zipWith to choose
// the shorter argument when one is non-finite,
// like cycle, repeat etc
'GeneratorFunction' !== xs.constructor
.constructor.name ? (
xs.length
) : Infinity;
// list :: StringOrArrayLike b => b -> [a]
const list = xs =>
// xs itself, if it is an Array,
// or an Array derived from xs.
Array.isArray(xs) ? (
xs
) : Array.from(xs || []);
// permutations :: [a] -> [[a]]
const permutations = xs => (
ys => ys.reduceRight(
(a, y) => a.flatMap(
ys => Array.from({
length: 1 + ys.length
}, (_, i) => i)
.map(n => ys.slice(0, n)
.concat(y)
.concat(ys.slice(n))
)
), [
[]
]
)
)(list(xs));
// show :: a -> String
const show = x =>
JSON.stringify(x);
// succ :: Enum a => a -> a
const succ = x =>
1 + x;
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n =>
// The first n elements of a list,
// string of characters, or stream.
xs => 'GeneratorFunction' !== xs
.constructor.constructor.name ? (
xs.slice(0, n)
) : [].concat.apply([], Array.from({
length: n
}, () => {
const x = xs.next();
return x.done ? [] : [x.value];
}));
// toEnum :: a -> Int -> a
const toEnum = e =>
// The first argument is a sample of the type
// allowing the function to make the right mapping
x => ({
'number': Number,
'string': String.fromCodePoint,
'boolean': Boolean,
'object': v => e.min + v
} [typeof e])(x);
// unlines :: [String] -> String
const unlines = xs =>
// A single string formed by the intercalation
// of a list of strings with the newline character.
xs.join('\n');
// until :: (a -> Bool) -> (a -> a) -> a -> a
const until = p =>
f => x => {
let v = x;
while (!p(v)) v = f(v);
return v;
};
// unwords :: [String] -> String
const unwords = xs =>
// A space-separated string derived
// from a list of words.
xs.join(' ');
// zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
const zipWith = f =>
// Use of `take` and `length` here allows
// zipping with non-finite lists
// i.e. generators like cycle, repeat, iterate.
xs => ys => {
const n = Math.min(length(xs), length(ys));
return Infinity > n ? (
(([as, bs]) => Array.from({
length: n
}, (_, i) => f(as[i])(
bs[i]
)))([xs, ys].map(
compose(take(n), list)
))
) : zipWithGen(f)(xs)(ys);
};
return main();
})(); |
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle | Solve a Numbrix puzzle | Numbrix puzzles are similar to Hidato.
The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood).
Published puzzles also tend not to have holes in the grid and may not always indicate the end node.
Two examples follow:
Example 1
Problem.
0 0 0 0 0 0 0 0 0
0 0 46 45 0 55 74 0 0
0 38 0 0 43 0 0 78 0
0 35 0 0 0 0 0 71 0
0 0 33 0 0 0 59 0 0
0 17 0 0 0 0 0 67 0
0 18 0 0 11 0 0 64 0
0 0 24 21 0 1 2 0 0
0 0 0 0 0 0 0 0 0
Solution.
49 50 51 52 53 54 75 76 81
48 47 46 45 44 55 74 77 80
37 38 39 40 43 56 73 78 79
36 35 34 41 42 57 72 71 70
31 32 33 14 13 58 59 68 69
30 17 16 15 12 61 60 67 66
29 18 19 20 11 62 63 64 65
28 25 24 21 10 1 2 3 4
27 26 23 22 9 8 7 6 5
Example 2
Problem.
0 0 0 0 0 0 0 0 0
0 11 12 15 18 21 62 61 0
0 6 0 0 0 0 0 60 0
0 33 0 0 0 0 0 57 0
0 32 0 0 0 0 0 56 0
0 37 0 1 0 0 0 73 0
0 38 0 0 0 0 0 72 0
0 43 44 47 48 51 76 77 0
0 0 0 0 0 0 0 0 0
Solution.
9 10 13 14 19 20 63 64 65
8 11 12 15 18 21 62 61 66
7 6 5 16 17 22 59 60 67
34 33 4 3 24 23 58 57 68
35 32 31 2 25 54 55 56 69
36 37 30 1 26 53 74 73 70
39 38 29 28 27 52 75 72 71
40 43 44 47 48 51 76 77 78
41 42 45 46 49 50 81 80 79
Task
Write a program to solve puzzles of this ilk,
demonstrating your program by solving the above examples.
Extra credit for other interesting examples.
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 the no connection puzzle
| #Wren | Wren | import "/sort" for Sort
import "/fmt" for Fmt
var example1 = [
"00,00,00,00,00,00,00,00,00",
"00,00,46,45,00,55,74,00,00",
"00,38,00,00,43,00,00,78,00",
"00,35,00,00,00,00,00,71,00",
"00,00,33,00,00,00,59,00,00",
"00,17,00,00,00,00,00,67,00",
"00,18,00,00,11,00,00,64,00",
"00,00,24,21,00,01,02,00,00",
"00,00,00,00,00,00,00,00,00"
]
var example2 = [
"00,00,00,00,00,00,00,00,00",
"00,11,12,15,18,21,62,61,00",
"00,06,00,00,00,00,00,60,00",
"00,33,00,00,00,00,00,57,00",
"00,32,00,00,00,00,00,56,00",
"00,37,00,01,00,00,00,73,00",
"00,38,00,00,00,00,00,72,00",
"00,43,44,47,48,51,76,77,00",
"00,00,00,00,00,00,00,00,00"
]
var moves = [ [1, 0], [0, 1], [-1, 0], [0, -1] ]
var board = []
var grid = []
var clues = []
var totalToFill = 0
var solve // recursive
solve = Fn.new { |r, c, count, nextClue|
if (count > totalToFill) return true
var back = grid[r][c]
if (back != 0 && back != count) return false
if (back == 0 && nextClue < clues.count && clues[nextClue] == count) {
return false
}
if (back == count) nextClue = nextClue + 1
grid[r][c] = count
for (m in moves) {
if (solve.call(r + m[1], c + m[0], count + 1, nextClue)) return true
}
grid[r][c] = back
return false
}
var printResult = Fn.new { |n|
System.print("Solution for example %(n):")
for (row in grid) {
for (i in row) if (i != -1) Fmt.write("$2d ", i)
System.print()
}
}
var n = 0
for (ex in [example1, example2]) {
board = ex
var nRows = board.count + 2
var nCols = board[0].split(",").count + 2
var startRow = 0
var startCol = 0
grid = List.filled(nRows, null)
for (i in 0...nRows) grid[i] = List.filled(nCols, -1)
totalToFill = (nRows - 2) * (nCols - 2)
var lst = []
for (r in 0...nRows) {
if (r >= 1 && r < nRows - 1) {
var row = board[r - 1].split(",")
for (c in 1...nCols - 1) {
var value = Num.fromString(row[c - 1])
if (value > 0) lst.add(value)
if (value == 1) {
startRow = r
startCol = c
}
grid[r][c] = value
}
}
}
Sort.quick(lst)
clues = lst
if (solve.call(startRow, startCol, 1, 0)) printResult.call(n + 1)
n = n + 1
} |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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.
| #Factor | Factor | { 1 4 9 2 3 0 5 } natural-sort . |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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.
| #Fantom | Fantom | fansh> a := [5, 1, 4, 2, 3]
[5, 1, 4, 2, 3]
fansh> a.sort
[1, 2, 3, 4, 5]
fansh> a
[1, 2, 3, 4, 5]
|
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
| #Python | Python |
data = [
'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'
]
for s in sorted(data, key=lambda x: list(map(int, x.split('.')))):
print(s)
|
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
| #Racket | Racket | #lang racket
(require data/order)
;; allows for key caching
(define (oid->oid-key o)
(map string->number (string-split o ".")))
(define oid-key< (order-<? datum-order))
(module+ test
(require rackunit)
(check-equal?
(sort
'("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")
oid-key<
#:key oid->oid-key
#:cache-keys? #t)
'("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"))) |
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
| #jq | jq | def setpaths(indices; values):
reduce range(0; indices|length) as $i
(.; .[indices[$i]] = values[$i]);
def disjointSort(indices):
(indices|unique) as $ix # "unique" sorts
# Set $sorted to the sorted array of values at $ix:
| ([ .[ $ix[] ] ] | sort) as $sorted
| setpaths( $ix; $sorted) ; |
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
| #Julia | Julia | function sortselected(a::AbstractVector{<:Real}, s::AbstractVector{<:Integer})
sel = unique(sort(s))
if sel[1] < 1 || length(a) < sel[end]
throw(BoundsError())
end
b = collect(copy(a))
b[sel] = sort(b[sel])
return b
end
a = [7, 6, 5, 4, 3, 2, 1, 0]
sel = [7, 2, 8]
b = sortselected(a, sel)
println("Original: $a\n\tsorted on $sel\n -> sorted array: $b") |
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.
| #Ring | Ring | # Project : Sort three variables
x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
sortthree(x,y,z)
x = 77444
y = -12
z = 0
sortthree(x,y,z)
func sortthree(x,y,z)
str = []
add(str,x)
add(str,y)
add(str,z)
str = sort(str)
see "x = " + str[1] + nl
see "y = " + str[2] + nl
see "z = " + str[3] + nl
see nl
|
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.
| #Ruby | Ruby | x = 'lions, tigers, and'
y = 'bears, oh my!'
z = '(from the "Wizard of OZ")'
x, y, z = [x, y, z].sort
puts x, y, z
x, y, z = 7.7444e4, -12, 18/2r # Float, Integer, Rational; taken from Perl 6
x, y, z = [x, y, z].sort
puts 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.
| #Objective-C | Objective-C | #import <Foundation/Foundation.h>
#define esign(X) (((X)>0)?1:(((X)<0)?-1:0))
int main()
{
@autoreleasepool {
NSMutableArray *arr =
[NSMutableArray
arrayWithArray: [@"this is a set of strings to sort"
componentsSeparatedByString: @" "]
];
[arr sortUsingComparator: ^NSComparisonResult(id obj1, id obj2){
NSComparisonResult l = esign((int)([obj1 length] - [obj2 length]));
return l ? -l // reverse the ordering
: [obj1 caseInsensitiveCompare: obj2];
}];
for( NSString *str in arr )
{
NSLog(@"%@", str);
}
}
return EXIT_SUCCESS;
} |
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.
| #Swift | Swift | import Darwin
func shuffle<T>(inout array: [T]) {
for i in 1..<array.count {
let j = Int(arc4random_uniform(UInt32(i)))
(array[i], array[j]) = (array[j], array[i])
}
}
func issorted<T:Comparable>(ary: [T]) -> Bool {
for i in 0..<(ary.count-1) {
if ary[i] > ary[i+1] {
return false
}
}
return true
}
func bogosort<T:Comparable>(inout ary: [T]) {
while !issorted(ary) {
shuffle(&ary)
}
} |
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.
| #Tcl | Tcl | package require Tcl 8.5
proc shuffleInPlace {listName} {
upvar 1 $listName list
set len [set len2 [llength $list]]
for {set i 0} {$i < $len-1} {incr i; incr len2 -1} {
# Pick cell to swap with
set n [expr {int($i + $len2 * rand())}]
# Perform swap
set temp [lindex $list $i]
lset list $i [lindex $list $n]
lset list $n $temp
}
}
proc inOrder {list} {
set prev [lindex $list 0]
foreach item [lrange $list 1 end] {
if {$prev > $item} {
return false
}
set prev $item
}
return true
}
proc bogosort {list} {
while { ! [inOrder $list]} {
shuffleInPlace list
}
return $list
} |
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.
| #Factor | Factor | USING: fry kernel locals math math.order sequences
sequences.private ;
IN: rosetta.bubble
<PRIVATE
:: ?exchange ( i seq quot -- ? )
i i 1 + [ seq nth-unsafe ] bi@ quot call +gt+ = :> doit?
doit? [ i i 1 + seq exchange ] when
doit? ; inline
: 1pass ( seq quot -- ? )
[ [ length 1 - iota ] keep ] dip
'[ _ _ ?exchange ] [ or ] map-reduce ; inline
PRIVATE>
: sort! ( seq quot -- )
over empty?
[ 2drop ] [ '[ _ _ 1pass ] loop ] if ; inline
: natural-sort! ( seq -- )
[ <=> ] 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.
| #Pascal | Pascal | procedure gnomesort(var arr : Array of Integer; size : Integer);
var
i, j, t : Integer;
begin
i := 1;
j := 2;
while i < size do begin
if arr[i-1] <= arr[i] then
begin
i := j;
j := j + 1
end
else begin
t := arr[i-1];
arr[i-1] := arr[i];
arr[i] := t;
i := i - 1;
if i = 0 then begin
i := j;
j := j + 1
end
end
end;
end; |
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
| #OCaml | OCaml | let swap a i j =
let tmp = a.(i) in
a.(i) <- a.(j);
a.(j) <- tmp;
;;
let cocktail_sort a =
let begin_ = ref(-1)
and end_ = ref(Array.length a - 2) in
let swapped = ref true in
try while !swapped do
swapped := false;
incr begin_;
for i = !begin_ to !end_ do
if a.(i) > a.(i+1) then begin
swap a (i) (i+1);
swapped := true;
end;
done;
if !swapped = false then raise Exit;
swapped := false;
decr end_;
for i = !end_ downto !begin_ do
if a.(i) > a.(i+1) then begin
swap a (i) (i+1);
swapped := true
end;
done;
done with Exit -> ()
;;
let () =
let a = [| 3; 7; 4; 9; 6; 1; 8; 5; 2; |] in
cocktail_sort a;
Array.iter (Printf.printf " %d") a;
print_newline();
;; |
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.
| #Common_Lisp | Common Lisp | CL-USER> (usocket:with-client-socket (socket stream "localhost" 256)
(write-line "hello socket world" stream)
(values))
; No value |
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.
| #D | D | module socket ;
import std.stdio ;
import std.socket ;
version(Win32) {
// For Win32 systems, need to link with ws2_32.lib.
pragma(lib, "ws2_32.lib") ;
}
void main() {
long res;
auto socket = new Socket(AddressFamily.INET, SocketType.STREAM) ;
socket.connect(new InternetAddress("localhost",256)) ;
res = socket.send(cast(void[])"hello socket world") ;
writefln("Socket %d bytes sent.", res) ;
socket.close() ;
} |
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin 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.
| #Haskell | Haskell | import Data.Monoid (Sum(..))
import System.Random (randomIO)
import Control.Monad (replicateM)
import Data.Bool (bool)
data Toss = Heads | Tails deriving Show
anExperiment toss =
moreWakenings <>
case toss of
Heads -> headsOnWaking
Tails -> moreWakenings
where
moreWakenings = (1,0)
headsOnWaking = (0,1)
main = do
tosses <- map (bool Heads Tails) <$> replicateM 1000000 randomIO
let (Sum w, Sum h) = foldMap anExperiment tosses
let ratio = fromIntegral h / fromIntegral w
putStrLn $ "Ratio: " ++ show ratio |
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.
| #Julia | Julia | """
Run the Sleeping Beauty Problem experiment `repetitions` times, checking to see
how often we had heads on waking Sleeping Beauty.
"""
function sleeping_beauty_experiment(repetitions)
gotheadsonwaking = 0
wakenings = 0
for _ in 1:repetitions
coin_result = rand(["heads", "tails"])
# On Monday, we check if we got heads.
wakenings += 1
if coin_result == "heads"
gotheadsonwaking += 1
end
# 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
end
end
end
# Show the number of times she was wakened.
println("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
end
CREDENCE = sleeping_beauty_experiment(1_000_000)
println("Results of experiment: Sleeping Beauty should estimate a credence of: ", CREDENCE)
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[SleepingBeautyExperiment]
SleepingBeautyExperiment[reps_Integer] := Module[{gotheadsonwaking, wakenings, coinresult},
gotheadsonwaking = 0;
wakenings = 0;
Do[
coinresult = RandomChoice[{"heads", "tails"}];
wakenings++;
If[coinresult === "heads",
gotheadsonwaking++;
,
wakenings++;
]
,
{reps}
];
Print["Wakenings over ", reps, " experiments: ", wakenings];
gotheadsonwaking/wakenings
]
out = N@SleepingBeautyExperiment[10^6];
Print["Results of experiment: Sleeping Beauty should estimate a credence of: ", out] |
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
| #Factor | Factor | USING: combinators.short-circuit io lists lists.lazy math
math.parser math.primes prettyprint sequences ;
IN: rosetta-code.smarandache-naive
: smarandache? ( n -- ? )
{
[ number>string string>digits [ prime? ] all? ]
[ prime? ]
} 1&& ;
: smarandache ( -- list ) 1 lfrom [ smarandache? ] lfilter ;
: smarandache-demo ( -- )
"First 25 members of the Smarandache prime-digital sequence:"
print 25 smarandache ltake list>array .
"100th member: " write smarandache 99 [ cdr ] times car . ;
MAIN: smarandache-demo |
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
| #Forth | Forth | : is_prime? ( n -- flag )
dup 2 < if drop false exit then
dup 2 mod 0= if 2 = exit then
dup 3 mod 0= if 3 = exit then
5
begin
2dup dup * >=
while
2dup mod 0= if 2drop false exit then
2 +
2dup mod 0= if 2drop false exit then
4 +
repeat
2drop true ;
: next_prime_digit_number ( n -- n )
dup 0= if drop 2 exit then
dup 10 mod
dup 2 = if drop 1+ exit then
dup 3 = if drop 2 + exit then
5 = if 2 + exit then
10 / recurse 10 * 2 + ;
: spds_next ( n -- n )
begin
next_prime_digit_number
dup is_prime?
until ;
: spds_print ( n -- )
0 swap 0 do
spds_next dup .
loop
drop cr ;
: spds_nth ( n -- n )
0 swap 0 do spds_next loop ;
." First 25 SPDS primes:" cr
25 spds_print
." 100th SPDS prime: "
100 spds_nth . cr
." 1000th SPDS prime: "
1000 spds_nth . cr
bye |
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
| #FreeBASIC | FreeBASIC |
function isprime( n as ulongint ) as boolean
if n < 2 then return false
if n = 2 then return true
if n mod 2 = 0 then return false
for i as uinteger = 3 to int(sqr(n))+1 step 2
if n mod i = 0 then return false
next i
return true
end function
dim as integer smar(1 to 100), count = 1, i = 1, digit, j
smar(1) = 2
print 1, 2
while count < 100
i += 2
if not isprime(i) then continue while
for j = 1 to len(str(i))
digit = val(mid(str(i),j,1))
if not isprime(digit) then continue while
next j
count += 1
smar(count) = i
if count = 100 orelse count <=25 then
print count, smar(count)
end if
wend |
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.
| #Ada | Ada |
-- This code is a basic implementation of snake in Ada using the command prompt
-- feel free to improve it!
-- Snake.ads
with Ada.Containers; use Ada.Containers;
with Ada.Containers.Vectors;
package Snake is
-- copy from 2048 game (
-- Keyboard management
type directions is (Up, Down, Right, Left, Quit, Restart, Invalid);
-- Redefining this standard procedure as function to allow Get_Keystroke as an expression function
function Get_Immediate return Character;
Arrow_Prefix : constant Character := Character'Val(224); -- works for windows
function Get_Keystroke return directions;
-- )
-- The container for game data
type gameBoard is array (Natural range <>, Natural range <>) of Character;
-- Initilize the board
procedure init;
-- Run the game
procedure run;
-- Displaying the board
procedure Display_Board;
-- Clear the board from content
procedure ClearBoard;
-- coordinates data structure
type coord is tagged record
X,Y : Integer;
end record;
-- list of coordinate (one coordinate for each body part of the snake)
package snakeBody is new Ada.Containers.Vectors (Natural, coord);
use snakeBody;
-- update snake's part depending on the snakeDirection and checking colicion (with borders and snak's part)
function moveSnake return Boolean;
-- generate food if it was eaten
procedure generateFood;
-- Add snake and food to the board
procedure addDataToBoard;
-- generate random integer between 1 and upperBound to generate random food position
function getRandomInteger(upperBound : Integer) return Integer;
private
width, height : Positive := 10;
board : gameBoard := (0 .. (width+1) => (0 .. (height+1) => ' '));
snake : Vector := (1,1) & (2,1) & (3,1);
snakeDirection : directions := Right;
food : coord := (5,5);
end Snake;
-- Snake.adb
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;
package body Snake is
-----------------------------------------------------------------------------
-- Redefining this standard procedure as function to allow Get_Keystroke as an expression function (copy from 2048 game)
function Get_Immediate return Character is
begin
return Answer : Character do Ada.Text_IO.Get_Immediate(Answer);
end return;
end Get_Immediate;
-----------------------------------------------------------------------------
-- (copy from 2048 game)
function Get_Keystroke return directions is
(case Get_Immediate is
when 'Q' | 'q' => Quit,
when 'R' | 'r' => Restart,
when 'W' | 'w' => Left,
when 'A' | 'a' => Up,
when 'S' | 's' => Down,
when 'D' | 'd' => Right,
-- Windows terminal
when Arrow_Prefix => (case Character'Pos(Get_Immediate) is
when 72 => Up,
when 75 => Left,
when 77 => Right,
when 80 => Down,
when others => Invalid),
-- Unix escape sequences
when ASCII.ESC => (case Get_Immediate is
when '[' => (case Get_Immediate is
when 'A' => Up,
when 'B' => Down,
when 'C' => Right,
when 'D' => Left,
when others => Invalid),
when others => Invalid),
when others => Invalid);
-----------------------------------------------------------------------------
procedure init is
begin
for Row in 0 .. width+1 loop
for Column in 0 .. height+1 loop
if Row = 0 or Row = width+1 then
board(Row,Column) := '#';
-- Insert(board(Row,0), Column, '#');
else
if Column = 0 or Column = height+1 then
board(Row,Column) := '#';
-- Insert(board, board(Row, Column), "#");
else
board(Row,Column) := ' ';
-- Insert(board, board(Row, Column), " ");
end if;
end if;
end loop;
end loop;
end;
-----------------------------------------------------------------------------
procedure run is
task T;
task body T is
begin
loop
snakeDirection := Get_Keystroke;
end loop;
end T;
begin
init;
loop
exit when snakeDirection = Quit;
if moveSnake = False then
Put_Line("GAME OVER!!!");
Put_Line("Your score is:" & Length(snake)'Image);
exit;
end if;
Display_Board;
delay 0.7;
end loop;
end run;
-----------------------------------------------------------------------------
procedure Display_Board is
begin
for Row in 0 .. width+1 loop
for Column in 0 .. height+1 loop
Put(board(Row, Column));
end loop;
New_Line;
end loop;
end Display_Board;
-----------------------------------------------------------------------------
procedure ClearBoard is
begin
for Row in 1 .. width loop
for Column in 1 .. height loop
board(Row, Column) := ' ';
end loop;
end loop;
end ClearBoard;
-----------------------------------------------------------------------------
function moveSnake return Boolean is
colision : Boolean := False;
headCoord : coord := Snake.First_Element;
addSnakePart : Boolean := False;
begin
case snakeDirection is
when Up => headCoord.X := headCoord.X - 1;
when Down => headCoord.X := headCoord.X + 1;
when Right => headCoord.Y := headCoord.Y + 1;
when Left => headCoord.Y := headCoord.Y - 1;
when others => null;
end case;
if headCoord.Y = height+1 then
return False;
end if;
if headCoord.Y = 0 then
return False;
end if;
if headCoord.X = width+1 then
return False;
end if;
if headCoord.X = 0 then
return False;
end if;
for index in snake.Iterate loop
if headCoord = snake(To_Index(index)) then
return False;
end if;
end loop;
snake.Prepend(headCoord);
if headCoord /= food then
snake.Delete_Last;
else
food := (0,0);
generateFood;
end if;
addDataToBoard;
return True;
end moveSnake;
-----------------------------------------------------------------------------
procedure generateFood is
begin
if food.X = 0 or food.Y = 0 then
food := (getRandomInteger(width), getRandomInteger(height));
end if;
end generateFood;
-----------------------------------------------------------------------------
procedure addDataToBoard is
begin
ClearBoard;
board(food.X, food.Y) := '*';
for index in snake.Iterate loop
board(snake(To_Index(index)).X, snake(To_Index(index)).Y) := 'o';
end loop;
end addDataToBoard;
-----------------------------------------------------------------------------
function getRandomInteger(upperBound : Integer) return Integer is
subtype Random_Range is Integer range 1 .. upperBound;
package R is new
Ada.Numerics.Discrete_Random (Random_Range);
use R;
G : Generator;
begin
Reset (G);
return Random (G);
end getRandomInteger;
end Snake;
-- main.adb
with Snake;
procedure Main is
begin
Snake.run;
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].
| #11l | 11l | F factors(=n)
[Int] rt
V f = 2
I n == 1
rt.append(1)
E
L
I 0 == (n % f)
rt.append(f)
n I/= f
I n == 1
R rt
E
f++
R rt
F sum_digits(=n)
V sum = 0
L n > 0
V m = n % 10
sum += m
n -= m
n I/= 10
R sum
F add_all_digits(lst)
V sum = 0
L(i) 0 .< lst.len
sum += sum_digits(lst[i])
R sum
F list_smith_numbers(cnt)
[Int] r
L(i) 4 .< cnt
V fac = factors(i)
I fac.len > 1
I sum_digits(i) == add_all_digits(fac)
r.append(i)
R r
V sn = list_smith_numbers(10'000)
print(‘Count of Smith Numbers below 10k: ’sn.len)
print()
print(‘First 15 Smith Numbers:’)
print_elements(sn[0.<15])
print()
print(‘Last 12 Smith Numbers below 10000:’)
print_elements(sn[(len)-12..]) |
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 | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int *board, *flood, *known, top = 0, w, h;
static inline int idx(int y, int x) { return y * w + x; }
int neighbors(int c, int *p)
/*
@c cell
@p list of neighbours
@return amount of neighbours
*/
{
int i, j, n = 0;
int y = c / w, x = c % w;
for (i = y - 1; i <= y + 1; i++) {
if (i < 0 || i >= h) continue;
for (j = x - 1; j <= x + 1; j++)
if (!(j < 0 || j >= w
|| (j == x && i == y)
|| board[ p[n] = idx(i,j) ] == -1))
n++;
}
return n;
}
void flood_fill(int c)
/*
fill all free cells around @c with “1” and write output to variable “flood”
@c cell
*/
{
int i, n[8], nei;
nei = neighbors(c, n);
for (i = 0; i < nei; i++) { // for all neighbours
if (board[n[i]] || flood[n[i]]) continue; // if cell is not free, choose another neighbour
flood[n[i]] = 1;
flood_fill(n[i]);
}
}
/* Check all empty cells are reachable from higher known cells.
Should really do more checks to make sure cell_x and cell_x+1
share enough reachable empty cells; I'm lazy. Will implement
if a good counter example is presented. */
int check_connectity(int lowerbound)
{
int c;
memset(flood, 0, sizeof(flood[0]) * w * h);
for (c = lowerbound + 1; c <= top; c++)
if (known[c]) flood_fill(known[c]); // mark all free cells around known cells
for (c = 0; c < w * h; c++)
if (!board[c] && !flood[c]) // if there are free cells which could not be reached from flood_fill
return 0;
return 1;
}
void make_board(int x, int y, const char *s)
{
int i;
w = x, h = y;
top = 0;
x = w * h;
known = calloc(x + 1, sizeof(int));
board = calloc(x, sizeof(int));
flood = calloc(x, sizeof(int));
while (x--) board[x] = -1;
for (y = 0; y < h; y++)
for (x = 0; x < w; x++) {
i = idx(y, x);
while (isspace(*s)) s++;
switch (*s) {
case '_': board[i] = 0;
case '.': break;
default:
known[ board[i] = strtol(s, 0, 10) ] = i;
if (board[i] > top) top = board[i];
}
while (*s && !isspace(*s)) s++;
}
}
void show_board(const char *s)
{
int i, j, c;
printf("\n%s:\n", s);
for (i = 0; i < h; i++, putchar('\n'))
for (j = 0; j < w; j++) {
c = board[ idx(i, j) ];
printf(!c ? " __" : c == -1 ? " " : " %2d", c);
}
}
int fill(int c, int n)
{
int i, nei, p[8], ko, bo;
if ((board[c] && board[c] != n) || (known[n] && known[n] != c))
return 0;
if (n == top) return 1;
ko = known[n];
bo = board[c];
board[c] = n;
if (check_connectity(n)) {
nei = neighbors(c, p);
for (i = 0; i < nei; i++)
if (fill(p[i], n + 1))
return 1;
}
board[c] = bo;
known[n] = ko;
return 0;
}
int main()
{
make_board(
#define USE_E 0
#if (USE_E == 0)
8,8, " __ 33 35 __ __ .. .. .."
" __ __ 24 22 __ .. .. .."
" __ __ __ 21 __ __ .. .."
" __ 26 __ 13 40 11 .. .."
" 27 __ __ __ 9 __ 1 .."
" . . __ __ 18 __ __ .."
" . .. . . __ 7 __ __"
" . .. .. .. . . 5 __"
#elif (USE_E == 1)
3, 3, " . 4 ."
" _ 7 _"
" 1 _ _"
#else
50, 3,
" 1 _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . 74"
" . . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ . _ ."
" . . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ . . _ _ ."
#endif
);
show_board("Before");
fill(known[1], 1);
show_board("After"); /* "40 lbs in two weeks!" */
return 0;
} |
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.
| #Java | Java | import java.util.*;
public class Sokoban {
String destBoard, currBoard;
int playerX, playerY, nCols;
Sokoban(String[] board) {
nCols = board[0].length();
StringBuilder destBuf = new StringBuilder();
StringBuilder currBuf = new StringBuilder();
for (int r = 0; r < board.length; r++) {
for (int c = 0; c < nCols; c++) {
char ch = board[r].charAt(c);
destBuf.append(ch != '$' && ch != '@' ? ch : ' ');
currBuf.append(ch != '.' ? ch : ' ');
if (ch == '@') {
this.playerX = c;
this.playerY = r;
}
}
}
destBoard = destBuf.toString();
currBoard = currBuf.toString();
}
String move(int x, int y, int dx, int dy, String trialBoard) {
int newPlayerPos = (y + dy) * nCols + x + dx;
if (trialBoard.charAt(newPlayerPos) != ' ')
return null;
char[] trial = trialBoard.toCharArray();
trial[y * nCols + x] = ' ';
trial[newPlayerPos] = '@';
return new String(trial);
}
String push(int x, int y, int dx, int dy, String trialBoard) {
int newBoxPos = (y + 2 * dy) * nCols + x + 2 * dx;
if (trialBoard.charAt(newBoxPos) != ' ')
return null;
char[] trial = trialBoard.toCharArray();
trial[y * nCols + x] = ' ';
trial[(y + dy) * nCols + x + dx] = '@';
trial[newBoxPos] = '$';
return new String(trial);
}
boolean isSolved(String trialBoard) {
for (int i = 0; i < trialBoard.length(); i++)
if ((destBoard.charAt(i) == '.')
!= (trialBoard.charAt(i) == '$'))
return false;
return true;
}
String solve() {
class Board {
String cur, sol;
int x, y;
Board(String s1, String s2, int px, int py) {
cur = s1;
sol = s2;
x = px;
y = py;
}
}
char[][] dirLabels = {{'u', 'U'}, {'r', 'R'}, {'d', 'D'}, {'l', 'L'}};
int[][] dirs = {{0, -1}, {1, 0}, {0, 1}, {-1, 0}};
Set<String> history = new HashSet<>();
LinkedList<Board> open = new LinkedList<>();
history.add(currBoard);
open.add(new Board(currBoard, "", playerX, playerY));
while (!open.isEmpty()) {
Board item = open.poll();
String cur = item.cur;
String sol = item.sol;
int x = item.x;
int y = item.y;
for (int i = 0; i < dirs.length; i++) {
String trial = cur;
int dx = dirs[i][0];
int dy = dirs[i][1];
// are we standing next to a box ?
if (trial.charAt((y + dy) * nCols + x + dx) == '$') {
// can we push it ?
if ((trial = push(x, y, dx, dy, trial)) != null) {
// or did we already try this one ?
if (!history.contains(trial)) {
String newSol = sol + dirLabels[i][1];
if (isSolved(trial))
return newSol;
open.add(new Board(trial, newSol, x + dx, y + dy));
history.add(trial);
}
}
// otherwise try changing position
} else if ((trial = move(x, y, dx, dy, trial)) != null) {
if (!history.contains(trial)) {
String newSol = sol + dirLabels[i][0];
open.add(new Board(trial, newSol, x + dx, y + dy));
history.add(trial);
}
}
}
}
return "No solution";
}
public static void main(String[] a) {
String level = "#######,# #,# #,#. # #,#. $$ #,"
+ "#.$$ #,#.# @#,#######";
System.out.println(new Sokoban(level.split(",")).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
| #Kotlin | Kotlin | // version 1.1.3
val moves = arrayOf(
intArrayOf(-1, -2), intArrayOf( 1, -2), intArrayOf(-1, 2), intArrayOf(1, 2),
intArrayOf(-2, -1), intArrayOf(-2, 1), intArrayOf( 2, -1), intArrayOf(2, 1)
)
val board1 =
" xxx " +
" x xx " +
" xxxxxxx" +
"xxx x x" +
"x x xxx" +
"sxxxxxx " +
" xx x " +
" xxx "
val 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....."
fun solve(pz: Array<IntArray>, sz: Int, sx: Int, sy: Int, idx: Int, cnt: Int): Boolean {
if (idx > cnt) return true
for (i in 0 until moves.size) {
val x = sx + moves[i][0]
val y = sy + moves[i][1]
if ((x in 0 until sz) && (y in 0 until sz) && pz[x][y] == 0) {
pz[x][y] = idx
if (solve(pz, sz, x, y, idx + 1, cnt)) return true
pz[x][y] = 0
}
}
return false
}
fun findSolution(b: String, sz: Int) {
val pz = Array(sz) { IntArray(sz) { -1 } }
var x = 0
var y = 0
var idx = 0
var cnt = 0
for (j in 0 until sz) {
for (i in 0 until sz) {
if (b[idx] == 'x') {
pz[i][j] = 0
cnt++
}
else if (b[idx] == 's') {
pz[i][j] = 1
cnt++
x = i
y = j
}
idx++
}
}
if (solve(pz, sz, x, y, 2, cnt)) {
for (j in 0 until sz) {
for (i in 0 until sz) {
if (pz[i][j] != -1)
print("%02d ".format(pz[i][j]))
else
print("-- ")
}
println()
}
}
else println("Cannot solve this puzzle!")
}
fun main(args: Array<String>) {
findSolution(board1, 8)
println()
findSolution(board2, 13)
} |
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
| #Ruby | Ruby | require 'HLPsolver'
ADJACENT = [[-3, 0], [0, -3], [0, 3], [3, 0], [-2, -2], [-2, 2], [2, -2], [2, 2]]
board1 = <<EOS
. 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 . .
. . . 1 . . .
EOS
t0 = Time.now
HLPsolver.new(board1).solve
puts " #{Time.now - t0} sec" |
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
| #Tcl | Tcl | package require Tcl 8.6
oo::class create HopidoSolver {
variable grid start limit
constructor {puzzle} {
set grid $puzzle
for {set y 0} {$y < [llength $grid]} {incr y} {
for {set x 0} {$x < [llength [lindex $grid $y]]} {incr x} {
if {[set cell [lindex $grid $y $x]] == 1} {
set start [list $y $x]
}
incr limit [expr {$cell>=0}]
}
}
if {![info exist start]} {
return -code error "no starting position found"
}
}
method moves {} {
return {
0 -3
-2 -2 -2 2
-3 0 3 0
-2 2 2 2
0 3
}
}
method Moves {g r c} {
set valid {}
foreach {dr dc} [my moves] {
set R [expr {$r + $dr}]
set C [expr {$c + $dc}]
if {[lindex $g $R $C] == 0} {
lappend valid $R $C
}
}
return $valid
}
method Solve {g r c v} {
lset g $r $c [incr v]
if {$v >= $limit} {return $g}
foreach {r c} [my Moves $g $r $c] {
return [my Solve $g $r $c $v]
}
return -code continue
}
method solve {} {
while {[incr i]==1} {
set grid [my Solve $grid {*}$start 0]
return
}
return -code error "solution not possible"
}
method solution {} {return $grid}
}
proc parsePuzzle {str} {
foreach line [split $str "\n"] {
if {[string trim $line] eq ""} continue
lappend rows [lmap {- c} [regexp -all -inline {(.)\s?} $line] {
string map {" " -1 "." -1} $c
}]
}
set len [tcl::mathfunc::max {*}[lmap r $rows {llength $r}]]
for {set i 0} {$i < [llength $rows]} {incr i} {
while {[llength [lindex $rows $i]] < $len} {
lset rows $i end+1 -1
}
}
return $rows
}
proc showPuzzle {grid name} {
foreach row $grid {foreach cell $row {incr c [expr {$cell>=0}]}}
set len [string length $c]
set u [string repeat "_" $len]
puts "$name with $c cells"
foreach row $grid {
puts [format " %s" [join [lmap c $row {
format "%*s" $len [if {$c==-1} list elseif {$c==0} {set u} {set c}]
}]]]
}
}
set puzzle [parsePuzzle {
. 0 0 . 0 0 .
0 0 0 0 0 0 0
0 0 0 0 0 0 0
. 0 0 0 0 0 .
. . 0 0 0 . .
. . . 1 . . .
}]
showPuzzle $puzzle "Input"
HopidoSolver create hop $puzzle
hop solve
showPuzzle [hop solution] "Output" |
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Sort an array of composite structures by a key.
For example, if you define a composite structure that presents a name-value pair (in pseudo-code):
Define structure pair such that:
name as a string
value as a string
and an array of such pairs:
x: array of pairs
then define a sort routine that sorts the array x by the key name.
This task can always be accomplished with Sorting Using a Custom Comparator.
If your language is not listed here, please see the other article.
| #Euphoria | Euphoria | include sort.e
include misc.e
constant NAME = 1
function compare_names(sequence a, sequence b)
return compare(a[NAME],b[NAME])
end function
sequence s
s = { { "grass", "green" },
{ "snow", "white" },
{ "sky", "blue" },
{ "cherry", "red" } }
pretty_print(1,custom_sort(routine_id("compare_names"),s),{2}) |
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).
| #jq | jq | # Short-circuit determination of whether (a|condition)
# is true for all a in array:
def forall(array; condition):
def check:
. as $ix
| if $ix == (array|length) then true
elif (array[$ix] | condition) then ($ix + 1) | check
else false
end;
0 | check;
# permutations of 0 .. (n-1)
def permutations(n):
# Given a single array, generate a stream by inserting n at different positions:
def insert(m;n):
if m >= 0 then (.[0:m] + [n] + .[m:]), insert(m-1;n) else empty end;
if n==0 then []
elif n == 1 then [1]
else
permutations(n-1) | insert(n-1; n)
end;
# Count the number of items in a stream
def count(f): reduce f as $_ (0; .+1); |
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).
| #Julia | Julia |
using Combinatorics
const HOLES = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
const PEGS = [1, 2, 3, 4, 5, 6, 7, 8]
const EDGES = [('A', 'C'), ('A', 'D'), ('A', 'E'),
('B', 'D'), ('B', 'E'), ('B', 'F'),
('C', 'G'), ('C', 'D'), ('D', 'G'),
('D', 'E'), ('D', 'H'), ('E', 'F'),
('E', 'G'), ('E', 'H'), ('F', 'H')]
goodperm(p) = all(e->abs(p[e[1]-'A'+1] - p[e[2]-'A'+1]) > 1, EDGES)
goodplacements() = [p for p in permutations(PEGS) if goodperm(p)]
const BOARD = raw"""
A B
/|\ /|\
/ | X | \
/ |/ \| \
C - D - E - F
\ |\ /| /
\ | X | /
\|/ \|/
G H
"""
function printsolutions()
solutions = goodplacements()
println("Found $(length(solutions)) solutions.")
for soln in solutions
board = BOARD
for (i, n) in enumerate(soln)
board = replace(board, string('A' + i - 1) => string(n))
end
println(board); exit(1) # remove this exit for all solutions
end
end
printsolutions()
|
http://rosettacode.org/wiki/Solve_a_Numbrix_puzzle | Solve a Numbrix puzzle | Numbrix puzzles are similar to Hidato.
The most important difference is that it is only possible to move 1 node left, right, up, or down (sometimes referred to as the Von Neumann neighborhood).
Published puzzles also tend not to have holes in the grid and may not always indicate the end node.
Two examples follow:
Example 1
Problem.
0 0 0 0 0 0 0 0 0
0 0 46 45 0 55 74 0 0
0 38 0 0 43 0 0 78 0
0 35 0 0 0 0 0 71 0
0 0 33 0 0 0 59 0 0
0 17 0 0 0 0 0 67 0
0 18 0 0 11 0 0 64 0
0 0 24 21 0 1 2 0 0
0 0 0 0 0 0 0 0 0
Solution.
49 50 51 52 53 54 75 76 81
48 47 46 45 44 55 74 77 80
37 38 39 40 43 56 73 78 79
36 35 34 41 42 57 72 71 70
31 32 33 14 13 58 59 68 69
30 17 16 15 12 61 60 67 66
29 18 19 20 11 62 63 64 65
28 25 24 21 10 1 2 3 4
27 26 23 22 9 8 7 6 5
Example 2
Problem.
0 0 0 0 0 0 0 0 0
0 11 12 15 18 21 62 61 0
0 6 0 0 0 0 0 60 0
0 33 0 0 0 0 0 57 0
0 32 0 0 0 0 0 56 0
0 37 0 1 0 0 0 73 0
0 38 0 0 0 0 0 72 0
0 43 44 47 48 51 76 77 0
0 0 0 0 0 0 0 0 0
Solution.
9 10 13 14 19 20 63 64 65
8 11 12 15 18 21 62 61 66
7 6 5 16 17 22 59 60 67
34 33 4 3 24 23 58 57 68
35 32 31 2 25 54 55 56 69
36 37 30 1 26 53 74 73 70
39 38 29 28 27 52 75 72 71
40 43 44 47 48 51 76 77 78
41 42 45 46 49 50 81 80 79
Task
Write a program to solve puzzles of this ilk,
demonstrating your program by solving the above examples.
Extra credit for other interesting examples.
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 the no connection puzzle
| #zkl | zkl | // Solve Hidato/Hopido/Numbrix puzzles
class Puzzle{ // hold info concerning this puzzle
var board, nrows,ncols, cells,
start, // (r,c) where 1 is located, Void if no 1
terminated, // if board holds highest numbered cell
given, // all the pre-loaded cells
adj, // a list of (r,c) that are valid next cells
;
fcn print_board{
d:=Dictionary(-1," ", 0,"__");
foreach r in (board){
r.pump(String,'wrap(c){ "%2s ".fmt(d.find(c,c)) }).println();
}
}
fcn init(s,adjacent){
adj=adjacent;
lines:=s.split("\n");
ncols,nrows=lines[0].split().len(),lines.len();
board=nrows.pump(List(), ncols.pump(List(),-1).copy);
given,start=List(),Void;
cells,terminated=0,True;
foreach r,row in (lines.enumerate()){
foreach c,cell in (row.split().enumerate()){
if(cell=="X") continue; // X == not in play, leave at -1
cells+=1;
val:=cell.toInt();
board[r][c]=val;
given.append(val);
if(val==1) start=T(r,c);
}
}
println("Number of cells = ",cells);
if(not given.holds(cells)){ given.append(cells); terminated=False; }
given=given.filter().sort();
}
fcn solve{ //-->Bool
if(start) return(_solve(start.xplode()));
foreach r,c in (nrows,ncols){
if(board[r][c]==0 and _solve(r,c)) return(True);
}
False
}
fcn [private] _solve(r,c,n=1, next=0){
if(n>given[-1]) return(True);
if(not ( (0<=r<nrows) and (0<=c<ncols) )) return(False);
if(board[r][c] and board[r][c]!=n) return(False);
if(terminated and board[r][c]==0 and given[next]==n) return(False);
back:=0;
if(board[r][c]==n){ next+=1; back=n; }
board[r][c]=n;
foreach i,j in (adj){ if(self.fcn(r+i,c+j,n+1, next)) return(True) }
board[r][c]=back;
False
}
} // 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.
| #Forth | Forth | create test-data 2 , 4 , 3 , 1 , 2 ,
test-data 5 cell-sort
|
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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.
| #Fortran | Fortran | CALL ISORT@(b, a, n)
! n = number of elements
! a = array to be sorted
! b = array of indices of a. b(1) 'points' to the minimum value etc. |
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
| #Raku | Raku | .say for sort *.comb(/\d+/)».Int, <
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
>; |
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
| #K | K |
{@[x;y@<y;:;a@<a:x@y]}[7 6 5 4 3 2 1 0;6 1 7]
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
| #Kotlin | Kotlin | // version 1.1.51
/* in place sort */
fun IntArray.sortDisjoint(indices: Set<Int>) {
val sortedSubset = this.filterIndexed { index, _ -> index in indices }.sorted()
if (sortedSubset.size < indices.size)
throw IllegalArgumentException("Argument set contains out of range indices")
indices.sorted().forEachIndexed { index, value -> this[value] = sortedSubset[index] }
}
fun main(args: Array<String>) {
val values = intArrayOf(7, 6, 5, 4, 3, 2, 1, 0)
val indices = setOf(6, 1, 7)
println("Original array : ${values.asList()} sorted on indices $indices")
values.sortDisjoint(indices)
println("Sorted array : ${values.asList()}")
}
|
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.
| #Rust | Rust | fn main() {
let mut array = [5, 1, 3];
array.sort();
println!("Sorted: {:?}", array);
array.sort_by(|a, b| b.cmp(a));
println!("Reverse sorted: {:?}", array);
}
|
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.
| #Scala | Scala | $ 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_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.
| #OCaml | OCaml | let mycmp s1 s2 =
if String.length s1 <> String.length s2 then
compare (String.length s2) (String.length s1)
else
String.compare (String.lowercase s1) (String.lowercase s2) |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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.
| #Oforth | Oforth | String method: customCmp(s)
s size self size > ifTrue: [ true return ]
s size self size < ifTrue: [ false return ]
s toUpper self toUpper <= ;
["this", "is", "a", "set", "of", "strings", "to", "sort", "This", "Is", "A", "Set", "Of", "Strings", "To", "Sort"]
sortWith(#customCmp) println |
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.
| #TI-83_BASIC | TI-83 BASIC | :"BOGO"
:L1→L2
:Lbl A
:dim(L2)→A
:For(B,1,dim(L2)-1)
:randInt(1,A)→C
:L2(C)→D
:L2(A)→L2(C)
:D→L2(A)
:A-1→A
:End
:For(D,1,dim(L2)-1)
:If L2(D)>L2(D+1)
:Goto A
:End
:DelVar A
:DelVar B
:DelVar C
:DelVar D
:Return
|
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.
| #Fish | Fish | v Sorts the (pre-loaded) stack
with bubblesort.
v <
\l0=?;l&
>&:1=?v1-&2[$:{:{](?${
>~{ao ^
>~}l &{ v
o","{n:&-1^?=0:&< |
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.
| #Perl | Perl | use strict;
sub gnome_sort
{
my @a = @_;
my $size = scalar(@a);
my $i = 1;
my $j = 2;
while($i < $size) {
if ( $a[$i-1] <= $a[$i] ) {
$i = $j;
$j++;
} else {
@a[$i, $i-1] = @a[$i-1, $i];
$i--;
if ($i == 0) {
$i = $j;
$j++;
}
}
}
return @a;
} |
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort | Sorting algorithms/Cocktail sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Cocktail sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
The cocktail shaker sort is an improvement on the Bubble Sort.
The improvement is basically that values "bubble" both directions through the array, because on each iteration the cocktail shaker sort bubble sorts once forwards and once backwards. Pseudocode for the algorithm (from wikipedia):
function cocktailSort( A : list of sortable items )
do
swapped := false
for each i in 0 to length( A ) - 2 do
if A[ i ] > A[ i+1 ] then // test whether the two
// elements are in the wrong
// order
swap( A[ i ], A[ i+1 ] ) // let the two elements
// change places
swapped := true;
if swapped = false then
// we can exit the outer loop here if no swaps occurred.
break do-while loop;
swapped := false
for each i in length( A ) - 2 down to 0 do
if A[ i ] > A[ i+1 ] then
swap( A[ i ], A[ i+1 ] )
swapped := true;
while swapped; // if no elements have been swapped,
// then the list is sorted
Related task
cocktail sort with shifting bounds
| #Octave | Octave | function sl = cocktailsort(l)
swapped = true;
while(swapped)
swapped = false;
for i = 1:(length(l)-1)
if ( l(i) > l(i+1) )
t = l(i);
l(i) = l(i+1);
l(i+1) = t;
swapped = true;
endif
endfor
if ( !swapped )
break;
endif
swapped = false;
for i = (length(l)-1):-1:1
if ( l(i) > l(i+1) )
t = l(i);
l(i) = l(i+1);
l(i+1) = t;
swapped = true;
endif
endfor
endwhile
sl = l;
endfunction |
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.
| #Delphi | Delphi | program Sockets;
{$APPTYPE CONSOLE}
uses IdTCPClient;
var
lTCPClient: TIdTCPClient;
begin
lTCPClient := TIdTCPClient.Create(nil);
try
lTCPClient.Host := '127.0.0.1';
lTCPClient.Port := 256;
lTCPClient.Connect;
lTCPClient.IOHandler.WriteLn('hello socket world');
finally
lTCPClient.Free;
end;
end. |
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.
| #Elena | Elena | import system'net;
import system'text;
import extensions'text;
import system'io;
public program()
{
var socket := new Socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
socket.connect("127.0.0.1",256);
var s := "hello socket world";
socket.write(AnsiEncoder.toByteArray(0, s.Length, s));
socket.close()
} |
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin 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.
| #Nim | Nim | import random
const N = 1_000_000
type Side {.pure.} = enum Heads, Tails
const Sides = [Heads, Tails]
randomize()
var onHeads, wakenings = 0
for _ in 1..N:
let side = sample(Sides)
inc wakenings
if side == Heads:
inc onHeads
else:
inc wakenings
echo "Wakenings over ", N, " experiments: ", wakenings
echo "Sleeping Beauty should estimate a credence of: ", onHeads / wakenings |
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.
| #Pascal | Pascal |
program sleepBeau;
uses
sysutils; //Format
const
iterations = 1000*1000;
fmt = 'Wakings over %d repetitions = %d'+#13#10+
'Percentage probability of heads on waking = %8.5f%%';
var
i,
heads,
wakings,
flip: Uint32;
begin
randomize;
for i :=1 to iterations do
Begin
flip := random(2)+1;//-- 1==heads, 2==tails
inc(wakings,1 + Ord(flip=2));
inc(heads,Ord(flip=1));
end;
writeln(Format(fmt,[iterations,wakings,heads/wakings*100]));
end. |
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.
| #Perl | Perl | use strict;
use warnings;
sub sleeping_beauty {
my($trials) = @_;
my($gotheadsonwaking,$wakenings);
$wakenings++ and rand > .5 ? $gotheadsonwaking++ : $wakenings++ for 1..$trials;
$wakenings, $gotheadsonwaking/$wakenings
}
my $trials = 1_000_000;
printf "Wakenings over $trials experiments: %d\nSleeping Beauty should estimate a credence of: %.4f\n", sleeping_beauty($trials); |
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
| #F.C5.8Drmul.C3.A6 | Fōrmulæ | 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.
| #Amazing_Hopper | Amazing Hopper |
/* Snake */
/* Implementing this task in Hopper-FLOW-MATIC++ */
/* The snake must catch a bite before time runs out, which decreases by
10 points every 800 milliseconds.
The remaining time will be added to your total score. */
#include <flow.h>
#include <flow-term.h>
#include <keys.h>
#enum 1,N,E,S,W
#enum 1,SPACE,FOOD,BORDER
DEF-MAIN(argv, argc)
BREAK-ON
STACK 16
CLR-SCR
MSET(C, quit, nHead, dir, Size, SCORE, counter, T,TPlay,ConsPrey )
SET( symbol, " $@" )
SET( w, 50 ) //50
SET( h, 28 ) // 24
SET( TIME, 100 )
LET( Size := MUL(w,h) )
SET( TLimit := 100 )
VOID( big number, numL1, numL2, numL3 )
GOSUB( set score )
DIM( Size ) AS-ONES( board )
HIDE-CURSOR
GOSUB( put titles )
GOSUB( start )
GOSUB( show )
GOSUB( ready ), SLEEP(3)
TIC( T ), TIC( TPlay )
WHILE( NOT (quit) )
DEVIATE-IF( TLimit ~= TPlay ){
GOSUB( show )
WHEN( KEY-PRESSED? ){
SCAN-CODE( C )
SWITCH( C )
CASE( K_UP ) { dir = N, EXIT }
CASE( K_RIGHT ){ dir = E, EXIT }
CASE( K_DOWN ) { dir = S, EXIT }
CASE( K_LEFT ) { dir = W, EXIT }
CASE( K_ESC ) { quit = 1, EXIT }
CASE( 32 ) { PAUSE, EXIT }
SWEND
}
GOSUB( step )
}
DEVIATE-IF( 800 ~= T ) {
TIME-=10, CLAMP(0,100,TIME)
{TIME, 12, 52} GOSUB( put time )
}
WEND
GOSUB(you lost), SLEEP(1)
GOSUB(game over ), SLEEP(2)
LOCATE(ADD(h,1),1) PRNL
SHOW-CURSOR
PRNL
END
RUTINES
// initialize the board, plant a very first food item
DEF-FUN( start )
SET( i,1 )
[1:w] {BORDER} CPUT(board) // top
[ SUB(MUL(h,w),MINUS-ONE(w)) : end] {BORDER} CPUT(board) // bottom
[1:w:end] {BORDER} CPUT(board) // left
SET(i, 1)
FOR( LE?(i, h), ++i )
[ MUL(i, w )] {BORDER} PUT(board) // right
NEXT
LET( nHead := MUL( w, SUB( SUB( h, 1 ), MOD(h,2) )) DIV-INTO(2) )
[ nHead ] {-5} CPUT( board )
LET( dir := N )
SRAND( ~SECONDS)
GOSUB( plant )
RET
DEF-FUN( you lost )
SET(i,1), SET(k,0), SET(n,1)
LOCATE(1,1)
FOR( LE?(i, h), ++i)
SET(j,1)
FOR( LE?(j, w), ++j)
LET( k := [ n ] GET(board) )
COND( IS-NEG?( k ))
LOCATE(i,j)
PRNL("\033[38;15;3m\033[48;5;9m~\OFF")
CEND
++n
NEXT
NEXT
RET
DEF-FUN( show )
SET(i,1)
MSET(j, k)
SET(n,1)
LOCATE(1,1)
FOR( LE?(i, h), ++i)
SET(j,1),
FOR( LE?(j, w), ++j)
LET( k := [ n ] GET(board) )
COND( IS-NEG?( k ))
PRN("\033[38;5;3m\033[48;5;15m~\OFF")
ELS-COND( {k} IS-EQ?(BORDER))
{"\033[38;5;4m\033[48;5;2m"}
PRN( [k] GET(symbol),"\OFF")
ELS-COND( {k}IS-EQ?(FOOD) )
{"\033[38;5;15m\033[48;5;9m"}
PRN( [k] GET(symbol),"\OFF")
ELS
{"\033[48;5;28m"}
PRN( [k] GET(symbol),"\OFF")
CEND
++n
NEXT
PRNL
NEXT
RET
// negative values denote the snake (a negated time-to-live in given cell)
// reduce a time-to-live, effectively erasing the tail
DEF-FUN( age )
MSET( r, jAge, jR )
CART( IS-NEG?( board ) ) »» (r), SET-RANGE(r)
GET( board ) PLUS(1) »» (jAge)
// this is necessary, because Hopper arrays begining in 1
CART( IS-ZERO?(jAge) ) »» (jR)
COND( IS-ARRAY?(jR) )
SET-RANGE(jR), SET(jAge, 1), SET-RANGE(r)
CEND
// ******
{jAge} PUT(board), CLR-RANGE
RET
DEF-FUN( step )
SET(len,0)
LET( len := [nHead] GET(board) )
SWITCH(dir)
CASE (N){ nHead -= w, EXIT }
CASE (S){ nHead += w, EXIT }
CASE (W){ --nHead, EXIT }
CASE (E){ ++nHead, EXIT }
SWEND
SWITCH( [nHead]CGET(board))
CASE (SPACE){
--len, LET( len := IF( IS-ZERO?(len), 1, len) )
[nHead] { len }, CPUT(board) // keep in mind len is negative
GOSUB( age )
EXIT
}
CASE (FOOD){
--len, LET( len := IF( IS-ZERO?(len), 1, len) )
[nHead] { len }, CPUT(board)
GOSUB( plant )
ADD(SCORE,TIME), MOVE-TO(SCORE)
{SCORE, 4, 52} GOSUB( put score )
LET( TIME := 100 )
++counter, COND( GT?( counter, 5 ) )
LET( TLimit := SUB( TLimit,5 ))
CLAMP(30,100,TLimit)
LET( counter := 0 )
CEND
++ConsPrey
COLOR-FG(10)
LOCATE(20,52) PRNL("SPEED: ")
LOC-ROW(21), SET-ROUND(2)
PRNL( MUL(INV(TLimit),100), " M/S" )
SET-ROUND(-1)
LOC-ROW(23) PRNL("CONSUMED PREY:")
LOC-ROW(24) PRNL(ConsPrey,"\OFF")
TIC( T ),{TIME, 12, 52} GOSUB( put time )
EXIT
}
LET( quit := 1 )
SWEND
RET
// put a piece of food at random empty position
DEF-FUN( plant )
SET(r, 0)
LOOP( search position )
LET( r := MOD( CEIL(RAND(MINUS-ONE(Size))), Size ) )
BACK-IF-NOT-EQ( [r] GET(board), SPACE, search position)
[r] {FOOD} CPUT( board )
RET
DEF-FUN( put titles )
LOCATE(2,52) PRNL("\033[38;5;15mSCORE\OFF")
{SCORE, 4, 52} GOSUB( put score )
LOCATE(10,52) PRNL("\033[38;5;11mTIME\OFF")
{TIME, 12, 52} GOSUB( put time )
COLOR-FG(15)
LOCATE(26,52) SET-ITALIC, PRNL(" S P E E D")
LOC-ROW(27) PRNL("S N A K E!\OFF")
RET
DEF-FUN( put time, B, posx, posy )
MSET( i,j,x )
MSET( sb, lsb,nB, p4 )
SET( k,1 )
LOCATE (posx, posy) FILL-BOX(" ",5,20)
LET( sb := STR(B) )
LET( lsb := LEN(sb) )
SET( rx, posy )
LET( p4 := ADD( posx, 4 ))
{"\033[38;5;11m\ENF"}
PERF-UP(k, lsb, 1)
LET( nB := VAL( MID( 1, k, sb )) )
SET(x, 1), SET( i, posx )
FOR( LE?(i, p4), ++i )
SET( j, rx )
FOR( LE?(j, ADD( rx, 2 ) ), ++j )
LOCATE(i, j) PRNL( STR-TO-UTF8(CHAR( [ PLUS-ONE(nB), x] CGET(big number) MUL-BY(219) )))
++x
NEXT
NEXT
rx += 4
NEXT
PRNL("\OFF")
RET
DEF-FUN( put score, SCORE, posx, posy )
MSET( ln,s, sp )
LET( sp := STR( SCORE ))
LET( ln := LEN(sp))
LOCATE ( posx, posy ) FILL-BOX(" ",4,20)
SET(i, 1)
{"\033[38;5;15m"}
PERF-UP( i, ln, 1)
LET( s := VAL( MID( 1, i, sp )) )
[ PLUS-ONE(s) ] // set interval to read element of arrays
LOCATE( posx, posy )
PRNL ( STR-TO-UTF8( GET(numL1) ))
LOCATE( PLUS-ONE(posx),posy )
PRNL ( STR-TO-UTF8( GET(numL2) ))
LOCATE( PLUS-TWO(posx),posy )
PRNL ( STR-TO-UTF8( GET(numL3) ))
posy += 2
NEXT
PRNL("\OFF")
RET
DEF-FUN( set score )
{"┌┐"," ┐","┌┐","┌┐","┐┐","┌┐","┌┐","┌┐","┌┐","┌┐"} APND-LST(numL1)
{"││"," │","┌┘"," ┤","└┤","└┐","├┐"," │","├┤","└┤"} APND-LST(numL2)
{"└┘"," ┴","└┘","└┘"," ┘","└┘","└┘"," ┴","└┘","└┘"} APND-LST(numL3)
{1,1,1,1,0,1,1,0,1,1,0,1,1,1,1} APND-ROW( big number )
{1,1,0,0,1,0,0,1,0,0,1,0,1,1,1} APND-ROW( big number )
{1,1,1,0,0,1,1,1,1,1,0,0,1,1,1} APND-ROW( big number )
{1,1,1,0,0,1,0,1,1,0,0,1,1,1,1} APND-ROW( big number )
{1,0,1,1,0,1,1,1,1,0,0,1,0,0,1} APND-ROW( big number )
{1,1,1,1,0,0,1,1,1,0,0,1,1,1,1} APND-ROW( big number )
{1,0,0,1,0,0,1,1,1,1,0,1,1,1,1} APND-ROW( big number )
{1,1,1,0,0,1,0,0,1,0,0,1,0,0,1} APND-ROW( big number )
{1,1,1,1,0,1,1,1,1,1,0,1,1,1,1} APND-ROW( big number )
{1,1,1,1,0,1,1,1,1,0,0,1,0,0,1} APND-ROW( big number )
RET
DEF-FUN( ready )
{"\033[38;5;4m\033[48;5;11m"}
LOC-COL(16)
LOC-ROW(13); PRNL( STR-TO-UTF8(" ▄ ▄▄ ▄ ▄▄ ▄ ▄ "))
LOC-ROW(14); PRNL( STR-TO-UTF8(" █▄▀ █▀ █▄█ █ █ ▀▄▀ "))
LOC-ROW(15); PRNL( STR-TO-UTF8(" ▀ ▀ ▀▀ ▀ ▀ ▀▄▀ ▀ "))
PRNL("\OFF")
RET
DEF-FUN( game over )
{"\033[38;5;15m\033[48;5;9m"}
LOC-COL(17)
LOC-ROW(12); PRNL( STR-TO-UTF8(" ▄▄ ▄ ▄ ▄ ▄▄ "))
LOC-ROW(13); PRNL( STR-TO-UTF8(" █ ▄ █▄█ █ █ █ █▀ "))
LOC-ROW(14); PRNL( STR-TO-UTF8(" ▀▀ ▀ ▀ ▀ ▀ ▀ ▀▀ "))
LOC-ROW(15); PRNL( STR-TO-UTF8(" ▄ ▄ ▄ ▄▄ ▄ "))
LOC-ROW(16); PRNL( STR-TO-UTF8(" █ █ █ █ █▀ █▄▀ "))
LOC-ROW(17); PRNL( STR-TO-UTF8(" ▀ ▀ ▀▀ ▀ ▀ "))
PRNL("\OFF")
RET
|
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].
| #360_Assembly | 360 Assembly | * Smith numbers - 02/05/2017
SMITHNUM CSECT
USING SMITHNUM,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R10,PG pgi=0
LA R6,4 i=4
DO WHILE=(C,R6,LE,N) do i=4 to n
LR R1,R6 i
BAL R14,SUMD call sumd(i)
ST R0,SS ss=sumd(i)
LR R1,R6 i
BAL R14,SUMFACTR call sumfactr(i)
IF C,R0,EQ,SS THEN if sumd(i)=sumfactr(i) then
L R2,NN nn
LA R2,1(R2) nn+1
ST R2,NN nn=nn+1
XDECO R6,XDEC i
MVC 0(5,R10),XDEC+7 output i
LA R10,5(R10) pgi+=5
L R4,IPG ipg
LA R4,1(R4) ipg+1
ST R4,IPG ipg=ipg+1
IF C,R4,EQ,=F'16' THEN if ipg=16 then
XPRNT PG,80 print buffer
MVC PG,=CL80' ' clear buffer
LA R10,PG pgi=0
MVC IPG,=F'0' ipg=0
ENDIF , endif
ENDIF , endif
LA R6,1(R6) i++
ENDDO , enddo i
L R4,IPG ipg
IF LTR,R4,NZ,R4 THEN if ipg<>0 then
XPRNT PG,80 print buffer
ENDIF , endif
L R1,NN nn
XDECO R1,XDEC edit nn
MVC PGT(4),XDEC+8 output nn
L R1,N n
XDECO R1,XDEC edit n
MVC PGT+28(5),XDEC+7 output n
XPRNT PGT,80 print
L R13,4(0,R13) restore previous savearea pointer
LM R14,R12,12(R13) restore previous context
XR R15,R15 rc=0
BR R14 exit
*------- ---- ----------------------------------------
SUMD EQU * sumd(x)
SR R0,R0 s=0
DO WHILE=(LTR,R1,NZ,R1) do while x<>0
LR R2,R1 x
SRDA R2,32 ~
D R2,=F'10' x/10
LR R1,R3 x=x/10
AR R0,R2 s=s+x//10
ENDDO , enddo while
BR R14 return s
*------- ---- ----------------------------------------
SUMFACTR EQU * sumfactr(z)
ST R14,SAVER14 store r14
ST R1,ZZ z
SR R8,R8 m=0
SR R9,R9 f=0
L R4,ZZ z
SRDA R4,32 ~
D R4,=F'2' z/2
DO WHILE=(LTR,R4,Z,R4) do while z//2=0
LA R8,2(R8) m=m+2
LA R9,1(R9) f=f+1
L R5,ZZ z
SRA R5,1 z/2
ST R5,ZZ z=z/2
LA R4,0 z
D R4,=F'2' z/2
ENDDO , enddo while
L R4,ZZ z
SRDA R4,32 ~
D R4,=F'3' z/3
DO WHILE=(LTR,R4,Z,R4) do while z//3=0
LA R8,3(R8) m=m+3
LA R9,1(R9) f=f+1
L R4,ZZ z
SRDA R4,32 ~
D R4,=F'3' z/3
ST R5,ZZ z=z/3
LA R4,0 z
D R4,=F'3' z/3
ENDDO , enddo while
LA R7,5 do j=5 by 2 while j<=z and j*j<=n
WHILEJ C R7,ZZ if j>z
BH EWHILEJ then leave while
LR R5,R7 j
MR R4,R7 *j
C R5,N if j*j>n
BH EWHILEJ then leave while
LR R4,R7 j
SRDA R4,32 ~
D R4,=F'3' j/3
LTR R4,R4 if j//3=0
BZ ITERJ then goto iterj
L R4,ZZ z
SRDA R4,32 ~
DR R4,R7 z/j
DO WHILE=(LTR,R4,Z,R4) do while z//j=0
LA R9,1(R9) f=f+1
LR R1,R7 j
BAL R14,SUMD call sumd(j)
AR R8,R0 m=m+sumd(j)
L R4,ZZ z
SRDA R4,32 ~
DR R4,R7 z/j
ST R5,ZZ z=z/j
LA R4,0 ~
DR R4,R7 z/j
ENDDO , enddo while
ITERJ LA R7,2(R7) j+=2
B WHILEJ enddo
EWHILEJ L R4,ZZ z
IF C,R4,NE,=F'1' THEN if z<>1 then
LA R9,1(R9) f=f+1
L R1,ZZ z
BAL R14,SUMD call sumd(z)
AR R8,R0 m=m+sumd(z)
ENDIF , endif
IF C,R9,LT,=F'2' THEN if f<2 then
SR R8,R8 mm=0
ENDIF , endif
LR R0,R8 return m
L R14,SAVER14 restore r14
BR R14 return
SAVER14 DS A save r14
* ---- ----------------------------------------
N DC F'10000' n
NN DC F'0' nn
IPG DC F'0' ipg
SS DS F ss
ZZ DS F z
PG DC CL80' ' buffer
PGT DC CL80'xxxx smith numbers found <= xxxxx'
XDEC DS CL12 temp
YREGS
END SMITHNUM |
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].
| #Action.21 | Action! | CARD FUNC SumDigits(CARD n)
CARD res,a
res=0
WHILE n#0
DO
res==+n MOD 10
n==/10
OD
RETURN (res)
CARD FUNC PrimeFactors(CARD n CARD ARRAY f)
CARD a,count
a=2 count=0
DO
IF n MOD a=0 THEN
f(count)=a
count==+1
n==/a
IF n=1 THEN
RETURN (count)
FI
ELSE
a==+1
FI
OD
RETURN (0)
PROC Main()
CARD n,i,s1,s2,count,tmp
CARD ARRAY f(100)
FOR n=4 TO 10000
DO
count=PrimeFactors(n,f)
IF count>=2 THEN
s1=SumDigits(n)
s2=0
FOR i=0 TO count-1
DO
tmp=f(i)
s2==+SumDigits(tmp)
OD
IF s1=s2 THEN
PrintC(n) Put(32)
FI
FI
Poke(77,0) ;turn off the attract mode
OD
RETURN |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.