task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Sorting_algorithms/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
|
#Run_BASIC
|
Run BASIC
|
for i = 1 to 100 ' fill array
a(i) = rnd(0) * 100
next i
' ------- sort -------
beg = 2
siz = 100
whatWay = 1
changed = 1
while changed
changed = 0
FOR i = beg TO siz STEP whatWay
IF a(i-1) > a(i) THEN
hold = a(i)
a(i) = a(i-1)
a(i-1) = hold
changed = i
end if
NEXT i
siz = beg
beg = changed - whatWay
whatWay = 0 - whatWay
wend
' ------ print result --------
for i = 1 to 100
print i;" ";a(i)
next i
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.
|
#Pike
|
Pike
|
import Stdio;
int main(){
object con = File();
con->connect("127.0.0.1",256);
con->write("hello socket world");
con->close();
}
|
http://rosettacode.org/wiki/Sockets
|
Sockets
|
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
|
#Prolog
|
Prolog
|
start(Port) :- socket('AF_INET',Socket),
socket_connect(Socket, 'AF_INET'(localhost,Port), Input, Output),
write(Output, 'hello socket world'),
flush_output(Output),
close(Output),
close(Input).
|
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.
|
#Rust
|
Rust
|
/* add to file Cargo.toml:
[dependencies]
winsafe = "0.0.8"
rand = "0.8.4"
*/
#![windows_subsystem = "windows"]
use rand::Rng;
use std::{cell::RefCell, rc::Rc};
use winsafe::{co, gui, prelude::*, COLORREF, HBRUSH, HPEN, SIZE};
const STEP: i32 = 3; // px, motion per frame. STEP and FPS determine the smoothness and speed of the animation.
const FPS: u32 = 90;
const CELL: i32 = 21; // px, game grid (logical step). Will be aligned by STEP
const FIELD_W: i32 = 20; // width of the square field in CELLs
const SNAKE_W: i32 = 20; // px
const ROUNDING: SIZE = SIZE::new(SNAKE_W / 2, SNAKE_W / 2);
const RATIO: i32 = CELL / STEP;
const START_CELL: i32 = FIELD_W / 2 * RATIO;
/// total field width (with overlap for collisions) in STEPs
const TW: i32 = (FIELD_W + 2) * RATIO;
#[derive(Clone, Copy)]
#[repr(i32)]
enum Direction {
Start = 0,
A = -1,
D = 1,
W = -TW,
S = TW,
}
use Direction::*;
struct Context {
wnd: gui::WindowMain,
snake: Vec<i32>, // [ids_rect] where id_rect = y * TW + x (where x, y: nSTEPs)
id_r: [i32; 6], // ID 6 rectangles to color in next frame (bg, tail, turn, body, food, head)
gap: i32, // gap in STEPs between animation and logic cell (negative - remove tail)
dir: Direction,
ordered_dir: Direction,
}
impl Context {
fn new(wnd: gui::WindowMain, len: usize) -> Self {
Self {
wnd,
snake: vec![START_CELL; len.saturating_sub(RATIO as usize)],
id_r: [START_CELL; 6],
gap: 0,
dir: Start,
ordered_dir: S,
}
}
}
pub fn main() {
let [bg, tail, turn, body, food, head] = [0usize, 1, 2, 3, 4, 5];
let mut colors = [(0x00, 0xF0, 0xA0); 6]; // color tail, turn, body
colors[bg] = (0x00, 0x50, 0x90);
colors[food] = (0xFF, 0x50, 0x00);
colors[head] = (0xFF, 0xFF, 0x00);
let brushes = COLORREF::new_array(&colors).map(|c| HBRUSH::CreateSolidBrush(c).unwrap());
let wnd = gui::WindowMain::new(gui::WindowMainOpts {
title: "Snake - Start: Space, then press W-A-S-D".to_string(),
size: winsafe::SIZE::new(FIELD_W * RATIO * STEP, FIELD_W * RATIO * STEP),
ex_style: co::WS_EX::CLIENTEDGE,
class_bg_brush: brushes[bg],
..Default::default()
});
let context = Rc::new(RefCell::new(Context::new(wnd.clone(), 0)));
wnd.on().wm_key_down({
let context = Rc::clone(&context);
move |k| {
let mut ctx = context.borrow_mut();
match (ctx.dir, k.char_code as u8) {
(Start, bt @ (b' ' | 113)) => {
let len = ctx.snake.len(); // 113 == F2 key
*ctx = Context::new(ctx.wnd.clone(), if bt == b' ' { len } else { 0 });
ctx.wnd.hwnd().InvalidateRect(None, true)?; // call .wm_paint() with erase
ctx.wnd.hwnd().SetTimer(1, 1000 / FPS, None)?;
}
(W | S, bt @ (b'A' | b'D')) => ctx.ordered_dir = if bt == b'A' { A } else { D },
(A | D, bt @ (b'S' | b'W')) => ctx.ordered_dir = if bt == b'S' { S } else { W },
_ => (),
}
Ok(())
}
});
wnd.on().wm_timer(1, {
let context = Rc::clone(&context);
let cells: Vec<i32> = (1..=FIELD_W)
.flat_map(|y| (1..=FIELD_W).map(move |x| (y * TW + x) * RATIO))
.collect();
move || {
let mut ctx = context.borrow_mut();
let new_h = ctx.id_r[head] + ctx.dir as i32;
ctx.id_r[body] = ctx.id_r[head];
ctx.id_r[head] = new_h;
if ctx.gap < 0 {
ctx.id_r[bg] = ctx.snake.remove(0);
ctx.id_r[tail] = ctx.snake[0];
ctx.id_r[turn] = ctx.snake[RATIO as usize / 2];
}
ctx.gap -= ctx.gap.signum();
if ctx.gap == 0 {
ctx.dir = ctx.ordered_dir;
let hw = ctx.wnd.hwnd();
let eat = new_h == ctx.id_r[food];
if !eat && (cells.binary_search(&new_h).is_err() || ctx.snake.contains(&&new_h)) {
hw.KillTimer(1)?;
hw.SetWindowText(&(hw.GetWindowText()? + " Restart: F2 (with save - Space)"))?;
ctx.dir = Start;
return Ok(());
} else if eat || ctx.id_r[food] == 0 && ctx.id_r[tail] != START_CELL {
let mut snk_cells: Vec<_> = ctx.snake.iter().step_by(RATIO as usize).collect();
if eat && snk_cells.len() == cells.len() - 2 {
hw.SetWindowText(&format!("Snake - EATEN ALL: {} !!!", snk_cells.len()))?
} else if eat {
hw.SetWindowText(&format!("Snake - Eaten: {}.", snk_cells.len()))?
}
if ctx.id_r[tail] == START_CELL || eat && snk_cells.len() == cells.len() - 2 {
ctx.id_r[food] = 0; // hide food if not all of the saved snake has come out or everything is eaten
} else if snk_cells.len() + 1 < cells.len() {
snk_cells.sort();
ctx.id_r[food] = *(cells.iter())
.filter(|i| **i != new_h && snk_cells.binary_search(i).is_err())
.nth(rand::thread_rng().gen_range(0..cells.len() - snk_cells.len() - 1))
.unwrap();
}
}
ctx.gap = if eat { RATIO } else { -RATIO }
}
ctx.snake.push(new_h);
ctx.wnd.hwnd().InvalidateRect(None, false)?; // call .wm_paint() without erase
Ok(())
}
});
wnd.on().wm_paint(move || {
let ctx = context.borrow();
let mut ps = winsafe::PAINTSTRUCT::default();
let hdc = ctx.wnd.hwnd().BeginPaint(&mut ps)?;
hdc.SelectObjectPen(HPEN::CreatePen(co::PS::NULL, 0, COLORREF::new(0, 0, 0))?)?;
for (&id_rect, &brush) in ctx.id_r.iter().zip(&brushes) {
hdc.SelectObjectBrush(brush)?;
let left = id_rect % TW * STEP - (STEP * RATIO + SNAKE_W) / 2;
let top = id_rect / TW * STEP - (STEP * RATIO + SNAKE_W) / 2;
hdc.RoundRect(
winsafe::RECT {
left,
top,
right: left + SNAKE_W,
bottom: top + SNAKE_W,
},
ROUNDING,
)?;
}
ctx.wnd.hwnd().EndPaint(&ps);
Ok(())
});
if let Err(e) = wnd.run_main(None) {
winsafe::HWND::NULL
.MessageBox(&e.to_string(), "Uncaught error", co::MB::ICONERROR)
.unwrap();
}
}
|
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].
|
#JavaScript
|
JavaScript
|
(() => {
'use strict';
// isSmith :: Int -> Bool
const isSmith = n => {
const pfs = primeFactors(n);
return (1 < pfs.length || n !== pfs[0]) && (
sumDigits(n) === pfs.reduce(
(a, x) => a + sumDigits(x),
0
)
);
};
// TEST -----------------------------------------------
// main :: IO ()
const main = () => {
// lowSmiths :: [Int]
const lowSmiths = enumFromTo(2)(9999)
.filter(isSmith);
// lowSmithCount :: Int
const lowSmithCount = lowSmiths.length;
return [
"Count of Smith Numbers below 10k:",
show(lowSmithCount),
"\nFirst 15 Smith Numbers:",
unwords(take(15)(lowSmiths)),
"\nLast 12 Smith Numbers below 10000:",
unwords(drop(lowSmithCount - 12)(lowSmiths))
].join('\n');
};
// SMITH ----------------------------------------------
// primeFactors :: Int -> [Int]
const primeFactors = x => {
const go = n => {
const fs = take(1)(
dropWhile(x => 0 != n % x)(
enumFromTo(2)(
floor(sqrt(n))
)
)
);
return 0 === fs.length ? [n] : fs.concat(
go(floor(n / fs[0]))
);
};
return go(x);
};
// sumDigits :: Int -> Int
const sumDigits = n =>
unfoldl(
x => 0 === x ? (
Nothing()
) : Just(quotRem(x)(10))
)(n).reduce((a, x) => a + x, 0);
// GENERIC --------------------------------------------
// Nothing :: Maybe a
const Nothing = () => ({
type: 'Maybe',
Nothing: true,
});
// Just :: a -> Maybe a
const Just = x => ({
type: 'Maybe',
Nothing: false,
Just: x
});
// Tuple (,) :: a -> b -> (a, b)
const Tuple = a => b => ({
type: 'Tuple',
'0': a,
'1': b,
length: 2
});
// drop :: Int -> [a] -> [a]
// drop :: Int -> String -> String
const drop = n => xs =>
xs.slice(n)
// dropWhile :: (a -> Bool) -> [a] -> [a]
// dropWhile :: (Char -> Bool) -> String -> String
const dropWhile = p => xs => {
const lng = xs.length;
return 0 < lng ? xs.slice(
until(i => i === lng || !p(xs[i]))(
i => 1 + i
)(0)
) : [];
};
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m => n =>
Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// floor :: Num -> Int
const floor = Math.floor;
// quotRem :: Int -> Int -> (Int, Int)
const quotRem = m => n =>
Tuple(Math.floor(m / n))(
m % n
);
// show :: a -> String
const show = x => JSON.stringify(x, null, 2);
// sqrt :: Num -> Num
const sqrt = n =>
(0 <= n) ? Math.sqrt(n) : undefined;
// sum :: [Num] -> Num
const sum = xs => xs.reduce((a, x) => a + x, 0);
// take :: Int -> [a] -> [a]
// take :: Int -> String -> String
const take = n => 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];
}));
// unfoldl :: (b -> Maybe (b, a)) -> b -> [a]
const unfoldl = f => v => {
let
xr = [v, v],
xs = [];
while (true) {
const mb = f(xr[0]);
if (mb.Nothing) {
return xs
} else {
xr = mb.Just;
xs = [xr[1]].concat(xs);
}
}
};
// 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 => xs.join(' ');
return main();
})();
|
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;
|
#Python
|
Python
|
board = []
given = []
start = None
def setup(s):
global board, given, start
lines = s.splitlines()
ncols = len(lines[0].split())
nrows = len(lines)
board = [[-1] * (ncols + 2) for _ in xrange(nrows + 2)]
for r, row in enumerate(lines):
for c, cell in enumerate(row.split()):
if cell == "__" :
board[r + 1][c + 1] = 0
continue
elif cell == ".":
continue # -1
else:
val = int(cell)
board[r + 1][c + 1] = val
given.append(val)
if val == 1:
start = (r + 1, c + 1)
given.sort()
def solve(r, c, n, next=0):
if n > given[-1]:
return True
if board[r][c] and board[r][c] != n:
return False
if 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
for i in xrange(-1, 2):
for j in xrange(-1, 2):
if solve(r + i, c + j, n + 1, next):
return True
board[r][c] = back
return False
def print_board():
d = {-1: " ", 0: "__"}
bmax = max(max(r) for r in board)
form = "%" + str(len(str(bmax)) + 1) + "s"
for r in board[1:-1]:
print "".join(form % d.get(c, str(c)) for c in r[1:-1])
hi = """\
__ 33 35 __ __ . . .
__ __ 24 22 __ . . .
__ __ __ 21 __ __ . .
__ 26 __ 13 40 11 . .
27 __ __ __ 9 __ 1 .
. . __ __ 18 __ __ .
. . . . __ 7 __ __
. . . . . . 5 __"""
setup(hi)
print_board()
solve(start[0], start[1], 1)
print
print_board()
|
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.
|
#ooRexx
|
ooRexx
|
a = .array~new
a~append(.pair~new("06-07", "Ducks"))
a~append(.pair~new("00-01", "Avalanche"))
a~append(.pair~new("02-03", "Devils"))
a~append(.pair~new("01-02", "Red Wings"))
a~append(.pair~new("03-04", "Lightning"))
a~append(.pair~new("04-05", "lockout"))
a~append(.pair~new("05-06", "Hurricanes"))
a~append(.pair~new("99-00", "Devils"))
a~append(.pair~new("07-08", "Red Wings"))
a~append(.pair~new("08-09", "Penguins"))
b = a~copy -- make a copy before sorting
b~sort
say "Sorted using direct comparison"
do pair over b
say pair
end
c = a~copy
-- this uses a custom comparator instead
c~sortWith(.paircomparator~new)
say
say "Sorted using a comparator (inverted)"
do pair over c
say pair
end
-- a name/value mapping class that directly support the sort comparisons
::class pair inherit comparable
::method init
expose name value
use strict arg name, value
::attribute name
::attribute value
::method string
expose name value
return name "=" value
-- the compareto method is a requirement brought in
-- by the
::method compareto
expose name
use strict arg other
return name~compareto(other~name)
-- a comparator that shows an alternate way of sorting
::class pairComparator subclass comparator
::method compare
use strict arg left, right
-- perform the comparison on the names
return -left~name~compareTo(right~name)
|
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.
|
#Nanoquery
|
Nanoquery
|
% import sort
% println sort({2,4,3,1,2})
[1, 2, 2, 3, 4]
|
http://rosettacode.org/wiki/Sort_an_integer_array
|
Sort an integer array
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
|
#Neko
|
Neko
|
/**
<doc><h2>Sort integer array, in Neko</h2>
<p>Array sort function modified from Haxe codegen with -D neko-source</p>
<p>The Neko target emits support code for Haxe basics, sort is included</p>
<p>Tectonics:<br />prompt$ nekoc sort.neko<br />prompt$ neko sort</p>
</doc>
**/
var sort = function(a) {
var i = 0;
var len = $asize(a);
while ( i < len ) {
var swap = false;
var j = 0;
var max = (len - i) - 1;
while ( j < max ) {
if ( (a[j] - a[j + 1]) > 0 ) {
var tmp = a[j + 1];
a[j + 1] = a[j];
a[j] = tmp;
swap = true;
}
j += 1;
}
if ( $not(swap) )
break;;
i += 1;
}
return a;
}
var arr = $array(5,3,2,1,4)
$print(arr, "\n")
/* Sorts in place */
sort(arr)
$print(arr, "\n")
/* Also returns the sorted array for chaining */
$print(sort($array(3,1,4,1,5,9,2,6,5,3,5,8)), "\n")
|
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
|
#Scala
|
Scala
|
import scala.compat.Platform
object SortedDisjointSubList extends App {
val (list, subListIndex) = (List(7, 6, 5, 4, 3, 2, 1, 0), List(6, 1, 7))
def sortSubList[T: Ordering](indexList: List[Int], list: List[T]) = {
val subListIndex = indexList.sorted
val sortedSubListMap = subListIndex.zip(subListIndex.map(list(_)).sorted).toMap
list.zipWithIndex.map { case (value, index) =>
if (sortedSubListMap.isDefinedAt(index)) sortedSubListMap(index) else value
}
}
assert(sortSubList(subListIndex, list) == List(7, 0, 5, 4, 3, 2, 1, 6), "Incorrect sort")
println(s"List in sorted order.\nSuccessfully completed without errors. [total ${Platform.currentTime - executionStart} ms]")
}
|
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.
|
#Tcl
|
Tcl
|
proc sorter {a b} {
set la [string length $a]
set lb [string length $b]
if {$la < $lb} {
return 1
} elseif {$la > $lb} {
return -1
}
return [string compare [string tolower $a] [string tolower $b]]
}
set strings {here are Some sample strings to be sorted}
lsort -command sorter $strings ;# ==> strings sample sorted here Some are be to
|
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.
|
#Liberty_BASIC
|
Liberty BASIC
|
itemCount = 20
dim item(itemCount)
for i = 1 to itemCount
item(i) = int(rnd(1) * 100)
next i
print "Before Sort"
for i = 1 to itemCount
print item(i)
next i
print: print
counter = itemCount
do
hasChanged = 0
for i = 1 to counter - 1
if item(i) > item(i + 1) then
temp = item(i)
item(i) = item(i + 1)
item(i + 1) = temp
hasChanged = 1
end if
next i
counter =counter -1
loop while hasChanged = 1
print "After Sort"
for i = 1 to itemCount
print item(i)
next i
end
|
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
|
Sorting algorithms/Gnome sort
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort.
The pseudocode for the algorithm is:
function gnomeSort(a[0..size-1])
i := 1
j := 2
while i < size do
if a[i-1] <= a[i] then
// for descending sort, use >= for comparison
i := j
j := j + 1
else
swap a[i-1] and a[i]
i := i - 1
if i = 0 then
i := j
j := j + 1
endif
endif
done
Task
Implement the Gnome sort in your language to sort an array (or list) of numbers.
|
#Smalltalk
|
Smalltalk
|
Smalltalk at: #gnomesort put: nil.
"Utility"
OrderedCollection extend [
swap: a with: b [ |t|
t := self at: a.
self at: a put: b.
self at: b put: t
]
].
"Gnome sort as block closure"
gnomesort := [ :c |
|i j|
i := 2. j := 3.
[ i <= (c size) ]
whileTrue: [
(c at: (i-1)) <= (c at: i)
ifTrue: [
i := j copy.
j := j + 1.
]
ifFalse: [
c swap: (i-1) with: i.
i := i - 1.
i == 1
ifTrue: [
i := j copy.
j := j + 1
]
]
]
].
|
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
|
#Rust
|
Rust
|
fn cocktail_sort<T: PartialOrd>(a: &mut [T]) {
let len = a.len();
loop {
let mut swapped = false;
let mut i = 0;
while i + 1 < len {
if a[i] > a[i + 1] {
a.swap(i, i + 1);
swapped = true;
}
i += 1;
}
if swapped {
swapped = false;
i = len - 1;
while i > 0 {
if a[i - 1] > a[i] {
a.swap(i - 1, i);
swapped = true;
}
i -= 1;
}
}
if !swapped {
break;
}
}
}
fn main() {
let mut v = vec![10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6];
println!("before: {:?}", v);
cocktail_sort(&mut v);
println!("after: {:?}", v);
}
|
http://rosettacode.org/wiki/Sockets
|
Sockets
|
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
|
#PureBasic
|
PureBasic
|
InitNetwork()
ConnectionID = OpenNetworkConnection("localhost", 256)
SendNetworkString(ConnectionID, "hello socket world")
CloseNetworkConnection(ConnectionID)
|
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.
|
#Python
|
Python
|
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("localhost", 256))
sock.sendall("hello socket world")
sock.close()
|
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.
|
#Sidef
|
Sidef
|
class SnakeGame(w, h) {
const readkey = frequire('Term::ReadKey')
const ansi = frequire('Term::ANSIColor')
enum (VOID, HEAD, BODY, TAIL, FOOD)
define (
LEFT = [+0, -1],
RIGHT = [+0, +1],
UP = [-1, +0],
DOWN = [+1, +0],
)
define BG_COLOR = "on_black"
define FOOD_COLOR = ("red" + " " + BG_COLOR)
define SNAKE_COLOR = ("bold green" + " " + BG_COLOR)
define SLEEP_SEC = 0.02
const (
A_VOID = ansi.colored(' ', BG_COLOR),
A_FOOD = ansi.colored('❇', FOOD_COLOR),
A_BLOCK = ansi.colored('■', SNAKE_COLOR),
)
has dir = LEFT
has grid = [[]]
has head_pos = [0, 0]
has tail_pos = [0, 0]
method init {
grid = h.of { w.of { [VOID] } }
head_pos = [h//2, w//2]
tail_pos = [head_pos[0], head_pos[1]+1]
grid[head_pos[0]][head_pos[1]] = [HEAD, dir] # head
grid[tail_pos[0]][tail_pos[1]] = [TAIL, dir] # tail
self.make_food()
}
method make_food {
var (food_x, food_y)
do {
food_x = w.rand.int
food_y = h.rand.int
} while (grid[food_y][food_x][0] != VOID)
grid[food_y][food_x][0] = FOOD
}
method display {
print("\033[H", grid.map { |row|
row.map { |cell|
given (cell[0]) {
when (VOID) { A_VOID }
when (FOOD) { A_FOOD }
default { A_BLOCK }
}
}.join('')
}.join("\n")
)
}
method move {
var grew = false
# Move the head
var (y, x) = head_pos...
var new_y = (y+dir[0] % h)
var new_x = (x+dir[1] % w)
var cell = grid[new_y][new_x]
given (cell[0]) {
when (BODY) { die "\nYou just bit your own body!\n" }
when (TAIL) { die "\nYou just bit your own tail!\n" }
when (FOOD) { grew = true; self.make_food() }
}
# Create a new head
grid[new_y][new_x] = [HEAD, dir]
# Replace the current head with body
grid[y][x] = [BODY, dir]
# Update the head position
head_pos = [new_y, new_x]
# Move the tail
if (!grew) {
var (y, x) = tail_pos...
var pos = grid[y][x][1]
var new_y = (y+pos[0] % h)
var new_x = (x+pos[1] % w)
grid[y][x][0] = VOID # erase the current tail
grid[new_y][new_x][0] = TAIL # create a new tail
tail_pos = [new_y, new_x]
}
}
method play {
STDOUT.autoflush(true)
readkey.ReadMode(3)
try {
loop {
var key
while (!defined(key = readkey.ReadLine(-1))) {
self.move()
self.display()
Sys.sleep(SLEEP_SEC)
}
given (key) {
when ("\e[A") { if (dir != DOWN ) { dir = UP } }
when ("\e[B") { if (dir != UP ) { dir = DOWN } }
when ("\e[C") { if (dir != LEFT ) { dir = RIGHT } }
when ("\e[D") { if (dir != RIGHT) { dir = LEFT } }
}
}
}
catch {
readkey.ReadMode(0)
}
}
}
var w = `tput cols`.to_i
var h = `tput lines`.to_i
SnakeGame(w || 80, h || 24).play
|
http://rosettacode.org/wiki/Smith_numbers
|
Smith numbers
|
Smith numbers are numbers such that the sum of the decimal digits of the integers that make up that number is the same as the sum of the decimal digits of its prime factors excluding 1.
By definition, all primes are excluded as they (naturally) satisfy this condition!
Smith numbers are also known as joke numbers.
Example
Using the number 166
Find the prime factors of 166 which are: 2 x 83
Then, take those two prime factors and sum all their decimal digits: 2 + 8 + 3 which is 13
Then, take the decimal digits of 166 and add their decimal digits: 1 + 6 + 6 which is 13
Therefore, the number 166 is a Smith number.
Task
Write a program to find all Smith numbers below 10000.
See also
from Wikipedia: [Smith number].
from MathWorld: [Smith number].
from OEIS A6753: [OEIS sequence A6753].
from OEIS A104170: [Number of Smith numbers below 10^n].
from The Prime pages: [Smith numbers].
|
#jq
|
jq
|
def is_prime:
. as $n
| if ($n < 2) then false
elif ($n % 2 == 0) then $n == 2
elif ($n % 3 == 0) then $n == 3
elif ($n % 5 == 0) then $n == 5
elif ($n % 7 == 0) then $n == 7
elif ($n % 11 == 0) then $n == 11
elif ($n % 13 == 0) then $n == 13
elif ($n % 17 == 0) then $n == 17
elif ($n % 19 == 0) then $n == 19
else {i:23}
| until( (.i * .i) > $n or ($n % .i == 0); .i += 2)
| .i * .i > $n
end;
def sum(s): reduce s as $x (null; . + $x);
# emit a stream of the prime factors as per prime factorization
def prime_factors:
. as $num
| def m($p): # emit $p with appropriate multiplicity
$num | while( . % $p == 0; . / $p )
| $p ;
if (. % 2) == 0 then m(2) else empty end,
(range(3; 1 + (./2); 2)
| select(($num % .) == 0 and is_prime)
| m(.));
|
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].
|
#Julia
|
Julia
|
# v0.6
function sumdigits(n::Integer)
sum = 0
while n > 0
sum += n % 10
n = div(n, 10)
end
return sum
end
using Primes
issmith(n::Integer) = !isprime(n) && sumdigits(n) == sum(sumdigits(f) for f in factor(Vector, n))
smithnumbers = collect(n for n in 2:10000 if issmith(n))
println("Smith numbers up to 10000:\n$smithnumbers")
|
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;
|
#Racket
|
Racket
|
#lang racket
(require math/array)
;#f = not a legal position, #t = blank position
(define board
(array
#[#[#t 33 35 #t #t #f #f #f]
#[#t #t 24 22 #t #f #f #f]
#[#t #t #t 21 #t #t #f #f]
#[#t 26 #t 13 40 11 #f #f]
#[27 #t #t #t 9 #t 1 #f]
#[#f #f #t #t 18 #t #t #f]
#[#f #f #f #f #t 7 #t #t]
#[#f #f #f #f #f #f 5 #t]]))
;filters elements with the predicate, returning the element and its indices
(define (array-indices-of a f)
(for*/list ([i (range 0 (vector-ref (array-shape a) 0))]
[j (range 0 (vector-ref (array-shape a) 1))]
#:when (f (array-ref a (vector i j))))
(list (array-ref a (vector i j)) i j)))
;returns a list, each element is a list of the number followed by i and j indices
;sorted ascending by number
(define (goal-list v) (sort (array-indices-of v number?) (λ (a b) (< (car a) (car b)))))
;every direction + start position that's on the board
(define (legal-moves a i0 j0)
(for*/list ([i (range (sub1 i0) (+ i0 2))]
[j (range (sub1 j0) (+ j0 2))]
;cartesian product -1..1 and -1..1, except 0 0
#:when (and (not (and (= i i0) (= j j0)))
;make sure it's on the board
(<= 0 i (sub1 (vector-ref (array-shape a) 0)))
(<= 0 j (sub1 (vector-ref (array-shape a) 1)))
;make sure it's an actual position too (the real board isn't square)
(array-ref a (vector i j))))
(cons i j)))
;find path through array, returning list of coords from start to finish
(define (hidato-path a)
;get starting position as first goal
(match-let ([(cons (list n i j) goals) (goal-list a)])
(let hidato ([goals goals] [n n] [i i] [j j] [path '()])
(match goals
;no more goals, return path
['() (reverse (cons (cons i j) path))]
;get next goal
[(cons (list n-goal i-goal j-goal) _)
(let ([move (cons i j)])
;already visiting a spot or taking too many moves to reach the next goal is no good
(cond [(or (member move path) (> n n-goal)) #f]
;taking the right number of moves to be at the goal square is good
;so go to the next goal
[(and (= n n-goal) (= i i-goal) (= j j-goal))
(hidato (cdr goals) n i j path)]
;depth first search using every legal move to find next goal
[else (ormap (λ (m) (hidato goals (add1 n) (car m) (cdr m) (cons move path)))
(legal-moves a i j))]))]))))
;take a path and insert it into the array
(define (put-path a path)
(let ([a (array->mutable-array a)])
(for ([n (range 1 (add1 (length path)))] [move path])
(array-set! a (vector (car move) (cdr move)) n))
a))
;main function
(define (hidato board) (put-path board (hidato-path board)))
|
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.
|
#Oz
|
Oz
|
declare
People = [person(name:joe value:3)
person(name:bill value:4)
person(name:alice value:20)
person(name:harry value:3)]
SortedPeople = {Sort People
fun {$ P1 P2}
P1.name < P2.name
end
}
in
{ForAll SortedPeople Show}
|
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.
|
#PARI.2FGP
|
PARI/GP
|
vecsort([["name", "value"],["name2", "value2"]], 1, 2)
|
http://rosettacode.org/wiki/Sort_an_integer_array
|
Sort an integer array
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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.
|
#Nemerle
|
Nemerle
|
using System.Console;
module IntSort
{
Main() : void
{
def nums = [1, 5, 3, 7, 2, 8, 3, 9];
def sorted = nums.Sort((x, y) => x.CompareTo(y));
WriteLine(nums);
WriteLine(sorted);
}
}
|
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.
|
#NetRexx
|
NetRexx
|
/* NetRexx */
options replace format comments java crossref savelog symbols binary
ia = int[]
ia = [ 2, 4, 3, 1, 2, -1, 0, -2 ]
display(ia)
Arrays.sort(ia)
display(ia)
-- Display results
method display(in = int[]) public static
sorted = Rexx('')
loop ix = 0 for in.length
sorted = sorted || Rexx(in[ix]).right(4)
end ix
say sorted.strip('t')
return
|
http://rosettacode.org/wiki/Sort_disjoint_sublist
|
Sort disjoint sublist
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted.
Make your example work with the following list of values and set of indices:
Values: [7, 6, 5, 4, 3, 2, 1, 0]
Indices: {6, 1, 7}
Where the correct result would be:
[7, 0, 5, 4, 3, 2, 1, 6].
In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead.
The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given.
Cf.
Order disjoint list items
|
#Scheme
|
Scheme
|
(use gauche.sequence)
(define num-list '(7 6 5 4 3 2 1 0))
(define indices '(6 1 7))
(define table
(alist->hash-table
(map cons
(sort indices)
(sort indices < (lambda (x) (~ num-list x))))))
(map last
(sort
(map-with-index
(lambda (i x) (list (hash-table-get table i i) x))
num-list)
<
car))
|
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.
|
#TUSCRIPT
|
TUSCRIPT
|
$$ MODE TUSCRIPT
setofstrings="this is a set of strings to sort This Is A Set Of Strings To Sort"
unsorted=SPLIT (setofstrings,": :")
PRINT "1. setofstrings unsorted"
index=""
LOOP l=unsorted
PRINT l
length=LENGTH (l),index=APPEND(index,length)
ENDLOOP
index =DIGIT_INDEX (index)
sorted=INDEX_SORT (unsorted,index)
PRINT "2. setofstrings sorted"
*{sorted}
|
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.
|
#Ursala
|
Ursala
|
#import std
#show+
data = <'this','is','a','list','of','strings','to','be','sorted'>
example = psort<not leql,lleq+ ~* ~&K31K30piK26 letters> data
|
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.
|
#Lisaac
|
Lisaac
|
Section Header
+ name := BUBBLE_SORT;
- external := `#include <time.h>`;
Section Public
- main <- (
+ a : ARRAY(INTEGER);
a := ARRAY(INTEGER).create 0 to 100;
`srand(time(NULL))`;
0.to 100 do { i : INTEGER;
a.put `rand()`:INTEGER to i;
};
bubble a;
a.foreach { item : INTEGER;
item.print;
'\n'.print;
};
);
- bubble a : ARRAY(INTEGER) <- (
+ lower, size, t : INTEGER;
+ sorted : BOOLEAN;
lower := a.lower;
size := a.upper - lower + 1;
{
sorted := TRUE;
size := size - 1;
0.to (size - 1) do { i : INTEGER;
(a.item(lower + i + 1) < a.item(lower + i)).if {
t := a.item(lower + i + 1);
a.put (a.item(lower + i)) to (lower + i + 1);
a.put t to (lower + i);
sorted := FALSE;
};
};
}.do_while {!sorted};
);
|
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.
|
#SNOBOL4
|
SNOBOL4
|
*** GNOME SORT *****************************************************************
* GNOME(V) -- gnome sort of the numerical vector V.
*** HELPER FUNCTIONS ***********************************************************
* IDXMAX(V) -- highest index of vector V.
* IDXMIN(V) -- lowest index of vector V.
* NUMBER(V) -- succeeds if V is some form of numerical data, fails otherwise.
* NUMBERS(V) -- succeeds iff all elements of vector V are numerical
* SWAP(A,B) -- swaps the values of two variables (named with .var).
* VECTOR(V) -- succeeds iff V is a vector.
********************************************************************************
define('GNOME(V)I,J,K,L,H,T')
*
define('IDXMAX(V)')
define('IDXMIN(V)')
define('NUMBER(V)')
define('NUMBERS(V)I,M')
define('SWAP(SWAP_PARAMETER_VAR_A,SWAP_PARAMETER_VAR_B)')
define('VECTOR(V)')
:(GNOME.END)
****************************************
* GNOME FUNCTION *
****************************************
GNOME numbers(v) :F(FRETURN)
gnome = copy(v)
l = idxmin(v) ; h = idxmax(v) ; i = l + 1
GNOME.LOOP j = i - 1
le(i, l) :S(GNOME.FORWARD)
gt(i,h) :S(RETURN)
le(gnome<j>, gnome<i>) :S(GNOME.FORWARD)
swap(.gnome<j>, .gnome<i>)
i = i - 1 :(GNOME.LOOP)
GNOME.FORWARD i = i + 1 :(GNOME.LOOP)
****************************************
* HELPER FUNCTIONS *
****************************************
IDXMAX vector(v) :F(FRETURN)
prototype(v) ':' span('-' &digits) . idxmax :S(RETURN)F(IDXMAX.NORM)
IDXMAX.NORM idxmax = prototype(v) :(RETURN)
****************************************
IDXMIN vector(v) :F(FRETURN)
prototype(v) span('-' &digits) . idxmin ':' :S(RETURN)F(IDXMIN.NORM)
IDXMIN.NORM idxmin = 1 :(RETURN)
****************************************
NUMBER ident(datatype(v), 'INTEGER') :S(RETURN)
ident(datatype(v), 'REAL') :S(RETURN)F(FRETURN)
****************************************
NUMBERS vector(v) :F(FRETURN)
i = idxmin(v) ; m = idxmax(v)
NUMBERS.LOOP le(i,m) :F(RETURN)
number(v<i>) :F(FRETURN)
i = i + 1 :(NUMBERS.LOOP)
****************************************
SWAP SWAP = $SWAP_PARAMETER_VAR_A
$SWAP_PARAMETER_VAR_A = $SWAP_PARAMETER_VAR_B
$SWAP_PARAMETER_VAR_B = SWAP
SWAP = :(RETURN)
****************************************
VECTOR ident(v) :S(FRETURN)
prototype(v) ',' :S(FRETURN)F(RETURN)
****************************************
GNOME.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
|
#Scala
|
Scala
|
object CocktailSort extends App {
def sort(arr: Array[Int]) = {
var swapped = false
do {
def swap(i: Int) {
val temp = arr(i)
arr(i) = arr(i + 1)
arr(i + 1) = temp
swapped = true
}
swapped = false
for (i <- 0 to (arr.length - 2)) if (arr(i) > arr(i + 1)) swap(i)
if (swapped) {
swapped = false
for (j <- arr.length - 2 to 0 by -1) if (arr(j) > arr(j + 1)) swap(j)
//if no elements have been swapped, then the list is sorted
}
} while (swapped)
arr
}
println(sort(Array(170, 45, 75, -90, -802, 24, 2, 66)).mkString(", "))
}
|
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.
|
#R
|
R
|
s <- make.socket(port = 256)
write.socket(s, "hello socket world")
close.socket(s)
|
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.
|
#Racket
|
Racket
|
#lang racket
(let-values ([(in out) (tcp-connect "localhost" 256)])
(display "hello socket world\n" out)
(close-output-port out))
|
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.
|
#Wren
|
Wren
|
/* snake.wren */
import "random" for Random
import "./dynamic" for Enum, Lower
foreign class Window {
construct initscr() {}
foreign nodelay(bf)
}
class Ncurses {
foreign static cbreak()
foreign static noecho()
foreign static refresh()
foreign static getch()
foreign static mvaddch(y, x, ch)
foreign static endwin()
}
class C {
foreign static usleep(usec)
}
var Dir = Enum.create("Dir", ["N", "E", "S", "W"])
var State = Enum.create("State", ["space", "food", "border"])
var w = 80
var h = 40
var board = List.filled(w * h, 0)
var rand = Random.new()
var head
var dir
var quit
// ASCII values
var hash = 35
var at = 64
var dot = 46
var spc = 32
/* negative values denote the snake (a negated time-to-live in given cell) */
// reduce a time-to-live, effectively erasing the tail
var age = Fn.new {
for (i in 0...w * h) {
if (board[i] < 0) board[i] = board[i] + 1
}
}
// put a piece of food at random empty position
var plant = Fn.new {
var r
while (true) {
r = rand.int(w * h)
if (board[r] = State.space) break
}
board[r] = State.food
}
// initialize the board, plant a very first food item
var start = Fn.new {
for (i in 0...w) board[i] = board[i + (h - 1) * w] = State.border
for (i in 0...h) board[i * w] = board[i * w + w - 1] = State.border
head = (w * (h - 1 - h % 2) / 2).floor // screen center for any h
board[head] = -5
dir = Dir.N
quit = false
plant.call()
}
var step = Fn.new {
var len = board[head]
if (dir == Dir.N) {
head = head - w
} else if (dir == Dir.S) {
head = head + w
} else if (dir == Dir.W) {
head = head - 1
} else if (dir == Dir.E) {
head = head + 1
}
if (board[head] == State.space) {
board[head] = len - 1 // keep in mind len is negative
age.call()
} else if (board[head] == State.food) {
board[head] = len - 1
plant.call()
} else {
quit = true
}
}
var show = Fn.new {
var symbol = [spc, at, dot]
for (i in 0...w*h) {
Ncurses.mvaddch((i/w).floor, i % w, board[i] < 0 ? hash : symbol[board[i]])
}
Ncurses.refresh()
}
var initScreen = Fn.new {
var win = Window.initscr()
Ncurses.cbreak()
Ncurses.noecho()
win.nodelay(true)
}
initScreen.call()
start.call()
while (true) {
show.call()
var ch = Ncurses.getch()
if (ch == Lower.i) {
dir = Dir.N
} else if (ch == Lower.j) {
dir = Dir.W
} else if (ch == Lower.k) {
dir = Dir.S
} else if (ch == Lower.l) {
dir = Dir.E
} else if (ch == Lower.q) {
quit = true
}
step.call()
C.usleep(300 * 1000) // 300 ms is a reasonable delay
if (quit) break
}
C.usleep(999 * 1000)
Ncurses.endwin()
|
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].
|
#Kotlin
|
Kotlin
|
// version 1.0.6
fun getPrimeFactors(n: Int): MutableList<Int> {
val factors = mutableListOf<Int>()
if (n < 2) return factors
var factor = 2
var nn = n
while (true) {
if (nn % factor == 0) {
factors.add(factor)
nn /= factor
if (nn == 1) return factors
}
else if (factor >= 3) factor += 2
else factor = 3
}
}
fun sumDigits(n: Int): Int = when {
n < 10 -> n
else -> {
var sum = 0
var nn = n
while (nn > 0) {
sum += (nn % 10)
nn /= 10
}
sum
}
}
fun isSmith(n: Int): Boolean {
if (n < 2) return false
val factors = getPrimeFactors(n)
if (factors.size == 1) return false
val primeSum = factors.sumBy { sumDigits(it) }
return sumDigits(n) == primeSum
}
fun main(args: Array<String>) {
println("The Smith numbers below 10000 are:\n")
var count = 0
for (i in 2 until 10000) {
if (isSmith(i)) {
print("%5d".format(i))
count++
}
}
println("\n\n$count numbers found")
}
|
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;
|
#Raku
|
Raku
|
my @adjacent = [-1, -1], [-1, 0], [-1, 1],
[ 0, -1], [ 0, 1],
[ 1, -1], [ 1, 0], [ 1, 1];
solveboard q:to/END/;
__ 33 35 __ __ .. .. ..
__ __ 24 22 __ .. .. ..
__ __ __ 21 __ __ .. ..
__ 26 __ 13 40 11 .. ..
27 __ __ __ 9 __ 1 ..
.. .. __ __ 18 __ __ ..
.. .. .. .. __ 7 __ __
.. .. .. .. .. .. 5 __
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.
|
#Pascal
|
Pascal
|
@people = (['joe', 120], ['foo', 31], ['bar', 51]);
@people = sort { $a->[0] cmp $b->[0] } @people;
|
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.
|
#Nial
|
Nial
|
sort >= 9 6 8 7 1 10
= 10 9 8 7 6 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.
|
#Nim
|
Nim
|
import algorithm
var a: array[0..8, int] = [2, 3, 5, 8, 4, 1, 6, 9, 7]
a.sort(Ascending)
for x in a:
echo x
|
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
|
#Sidef
|
Sidef
|
func disjointSort(values, indices) {
values[indices.sort] = [values[indices]].sort...
}
var values = [7, 6, 5, 4, 3, 2, 1, 0];
var indices = [6, 1, 7];
disjointSort(values, indices);
say values;
|
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.
|
#Visual_Basic_.NET
|
Visual Basic .NET
|
Imports System
Module Sorting_Using_a_Custom_Comparator
Function CustomComparator(ByVal x As String, ByVal y As String) As Integer
Dim result As Integer
result = y.Length - x.Length
If result = 0 Then
result = String.Compare(x, y, True)
End If
Return result
End Function
Sub Main()
Dim strings As String() = {"test", "Zoom", "strings", "a"}
Array.Sort(strings, New Comparison(Of String)(AddressOf CustomComparator))
End Sub
End Module
|
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.
|
#Lua
|
Lua
|
function bubbleSort(A)
local itemCount=#A
local hasChanged
repeat
hasChanged = false
itemCount=itemCount - 1
for i = 1, itemCount do
if A[i] > A[i + 1] then
A[i], A[i + 1] = A[i + 1], A[i]
hasChanged = true
end
end
until hasChanged == false
end
|
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
|
Sorting algorithms/Gnome sort
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort.
The pseudocode for the algorithm is:
function gnomeSort(a[0..size-1])
i := 1
j := 2
while i < size do
if a[i-1] <= a[i] then
// for descending sort, use >= for comparison
i := j
j := j + 1
else
swap a[i-1] and a[i]
i := i - 1
if i = 0 then
i := j
j := j + 1
endif
endif
done
Task
Implement the Gnome sort in your language to sort an array (or list) of numbers.
|
#Swift
|
Swift
|
func gnomeSort<T: Comparable>(_ a: inout [T]) {
var i = 1
var j = 2
while i < a.count {
if a[i - 1] <= a[i] {
i = j
j += 1
} else {
a.swapAt(i - 1, i)
i -= 1
if i == 0 {
i = j
j += 1
}
}
}
}
var array = [10, 8, 4, 3, 1, 9, 0, 2, 7, 5, 6]
print("before: \(array)")
gnomeSort(&array)
print(" after: \(array)")
|
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
|
#Scilab
|
Scilab
|
function varargout=cocktailSort(list_in)
swapped = %T;
while swapped
swapped = %F;
for i = [1:length(list_in)-1]
if list_in(i) > list_in(i+1) then
list_in([i i+1])=list_in([i+1 i]);
swapped = %T;
end
end
if ~swapped
break
end
swapped = %F;
for i = [length(list_in)-1:-1:1]
if list_in(i) > list_in(i+1)
list_in([i i+1]) = list_in([i+1 i])
swapped = %T;
end
end
end
varargout=list(list_in)
endfunction
disp(cocktailSort([6 3 7 8 5 1 2 4 9]));
|
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.
|
#Raku
|
Raku
|
my $host = '127.0.0.1';
my $port = 256;
my $client = IO::Socket::INET.new(:$host, :$port);
$client.print( 'hello socket world' );
$client.close;
|
http://rosettacode.org/wiki/Sockets
|
Sockets
|
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
|
#Rhope
|
Rhope
|
Socket Send(0,0)
|:
[New@Net Client["localhost",256]]Put String["hello socket world"]
:|
|
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.
|
#XPL0
|
XPL0
|
def Width=40, Height=25-1, \playing area including border
StartLength = 10, \starting length of snake including head
Morsels = 10; \number of food items constantly offered
int Heading; \direction snake is heading
def Up, Down, Left, Right;
int Length, \current length of snake including head
Score; \number of food items eaten
char SnakeX(10000), \location of each segment including head
SnakeY(10000), \ample room to grow
FoodX(Morsels), FoodY(Morsels); \location of each food item
def Black, Blue, Green, Cyan, Red, Magenta, Brown, White, \attribute colors
Gray, LBlue, LGreen, LCyan, LRed, LMagenta, Yellow, BWhite; \EGA palette
proc PlaceFood(N); \Place Nth food item in playing area
int N;
[FoodX(N):= Ran(Width-3) + 1; \pick random location inside borders
FoodY(N):= Ran(Height-3) + 1;
Cursor(FoodX(N), FoodY(N)); \show food
Attrib(Red<<4+LRed);
ChOut(6, ^@);
]; \PlaceFood
int X, Y, I, C;
[SetVid($01); \set 40x25 text mode
ShowCursor(false); \turn off flashing cursor
Attrib(Blue<<4+LBlue); \show borders
Cursor(0, 0);
for X:= 0 to Width-1 do ChOut(6, ^+);
Cursor(0, Height-1);
for X:= 0 to Width-1 do ChOut(6, ^+);
for Y:= 0 to Height-1 do
[Cursor(0, Y); ChOut(6, ^+);
Cursor(Width-1, Y); ChOut(6, ^+);
];
Attrib(Black<<4+White); \show initial score
Cursor(0, 24);
Text(6, "Score: 0");
Score:= 0;
SnakeX(0):= Width/2; \start snake head at center
SnakeY(0):= Height/2;
Heading:= Left;
Length:= StartLength;
for I:= 1 to Length-1 do \segments follow head to the right
[SnakeX(I):= SnakeX(I-1) + 1;
SnakeY(I):= SnakeY(I-1);
];
for I:= 0 to Morsels-1 do PlaceFood(I); \sow some tasty food
\Continuously move snake
loop \--------------------------------------------------------------------------
[Attrib(Black<<4+White); \remove tail-end segment
Cursor(SnakeX(Length-1), SnakeY(Length-1));
ChOut(6, ^ );
Attrib(Green<<4+Yellow); \add segment at head location
Cursor(SnakeX(0), SnakeY(0));
ChOut(6, ^#);
\Shift coordinates toward tail (+1 in case a segment gets added)
for I:= Length downto 1 do \segment behind head gets head's coords
[SnakeX(I):= SnakeX(I-1);
SnakeY(I):= SnakeY(I-1);
];
if ChkKey then \key hit--get new movement direction
[repeat C:= ChIn(1) until C # 0; \remove arrow keys' prefix byte
case C of
$1B: exit; \Escape, and scan codes for arrow keys
$48: if Heading # Down then Heading:= Up;
$50: if Heading # Up then Heading:= Down;
$4B: if Heading # Right then Heading:= Left;
$4D: if Heading # Left then Heading:= Right
other []; \ignore any other keystrokes
];
case Heading of \move head to its new location
Up: SnakeY(0):= SnakeY(0)-1;
Down: SnakeY(0):= SnakeY(0)+1;
Left: SnakeX(0):= SnakeX(0)-1;
Right:SnakeX(0):= SnakeX(0)+1
other [];
Cursor(SnakeX(0), SnakeY(0)); \show head at its new location
ChOut(6, ^8);
for I:= 0 to Morsels-1 do
if SnakeX(0)=FoodX(I) & SnakeY(0)=FoodY(I) then
[Score:= Score+1; \ate a morsel
Attrib(Black<<4+White);
Cursor(7, 24);
IntOut(6, Score*10);
PlaceFood(I); \replenish morsel
Length:= Length+1; \grow snake one segment
I:= Morsels; \over eating can be bad--quit for loop
Sound(1, 1, 1500); \BURP!
Sound(1, 1, 1000);
];
if I = Morsels then Sound(0, 2, 1); \no sound adds delay of 2/18th second
if SnakeX(0)=0 or SnakeX(0)=Width-1 or
SnakeY(0)=0 or SnakeY(0)=Height-1 then
quit; \snake hit border--game over
for I:= 1 to Length-1 do
if SnakeX(0)=SnakeX(I) & SnakeY(0)=SnakeY(I) then
quit; \snake bit itself--game over
]; \loop -----------------------------------------------------------------------
for I:= 1 to 8 do Sound(1, 1, 4000*I); \death dirge
Sound(0, 36, 1); \pause 2 seconds to see result
OpenI(1); \flush any pending keystrokes
]
|
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].
|
#Lua
|
Lua
|
-- Returns a boolean indicating whether n is prime
function isPrime (n)
if n < 2 then return false end
if n < 4 then return true end
if n % 2 == 0 then return false end
for d = 3, math.sqrt(n), 2 do
if n % d == 0 then return false end
end
return true
end
-- Returns a table of the prime factors of n
function primeFactors (n)
local pfacs, divisor = {}, 1
if n < 1 then return pfacs end
while not isPrime(n) do
while not isPrime(divisor) do divisor = divisor + 1 end
while n % divisor == 0 do
n = n / divisor
table.insert(pfacs, divisor)
end
divisor = divisor + 1
if n == 1 then return pfacs end
end
table.insert(pfacs, n)
return pfacs
end
-- Returns the sum of the digits of n
function sumDigits (n)
local sum, nStr = 0, tostring(n)
for digit = 1, nStr:len() do
sum = sum + tonumber(nStr:sub(digit, digit))
end
return sum
end
-- Returns a boolean indicating whether n is a Smith number
function isSmith (n)
if isPrime(n) then return false end
local sumFacs = 0
for _, v in ipairs(primeFactors(n)) do
sumFacs = sumFacs + sumDigits(v)
end
return sumFacs == sumDigits(n)
end
-- Main procedure
for n = 1, 10000 do
if isSmith(n) then io.write(n .. "\t") end
end
|
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;
|
#REXX
|
REXX
|
/*REXX program solves a Numbrix (R) puzzle, it also displays the puzzle and solution. */
maxR=0; maxC=0; maxX=0; minR=9e9; minC=9e9; minX=9e9; cells=0; @.=
parse arg xxx; PZ='Hidato puzzle' /*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 do; x=x/1 /*normalize X*/
if x<0 then PZ= 'Numbrix puzzle'
x=abs(x) /*use │x│ */
end
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 1 0 -1 -1 1 1 -1' /*possible row for the next move. */
Nc = '1 0 -1 0 1 -1 1 -1' /* " column " " " " */
pMoves=words(Nr) -4*(left(PZ,1)=='N') /*is this to be a Numbrix puzzle ? */
do i=1 for pMoves; Nr.i=word(Nr,i); Nc.i=word(Nc,i); end /*for fast moves. */
if \next(2,!r,!c) then call err 'No solution possible for this' PZ "puzzle."
say 'A solution for the' PZ "exists."; say; call show
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
err: say; say '***error*** (from' PZ"): " 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.
|
#Perl
|
Perl
|
@people = (['joe', 120], ['foo', 31], ['bar', 51]);
@people = sort { $a->[0] cmp $b->[0] } @people;
|
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.
|
#Phix
|
Phix
|
sequence s = {{"grass","green"},{"snow","white"},{"sky","blue"},{"cherry","red"},{0,1.2},{3.4,-1}}
?sort(s)
function compare_col2(sequence a, b) return compare(a[2],b[2]) end function
?custom_sort(compare_col2,s)
?sort_columns(s,{2}) -- 0.8.0+, same result as above w/o needing an explicit comparison routine
|
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.
|
#Niue
|
Niue
|
2 6 1 0 3 8 sort .s
0 1 2 3 6 8
|
http://rosettacode.org/wiki/Sort_an_integer_array
|
Sort an integer array
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Task
Sort an array (or list) of integers in ascending numerical order.
Use a sorting facility provided by the language/library if possible.
|
#Objeck
|
Objeck
|
bundle Default {
class Sort {
function : Main(args : System.String[]) ~ Nil {
nums := Structure.IntVector->New([2,4,3,1,2]);
nums->Sort();
}
}
}
|
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
|
#Standard_ML
|
Standard ML
|
functor SortDisjointFn (A : MONO_ARRAY) : sig
val sort : (A.elem * A.elem -> order) -> (A.array * int array) -> unit
end = struct
structure DisjointView : MONO_ARRAY = struct
type elem = A.elem
type array = A.array * int array
fun length (a, s) = Array.length s
fun sub ((a, s), i) = A.sub (a, Array.sub (s, i))
fun update ((a, s), i, x) = A.update (a, Array.sub (s, i), x)
(* dummy implementations for not-needed functions *)
type vector = unit
val maxLen = Array.maxLen
fun array _ = raise Domain
fun fromList _ = raise Domain
fun tabulate _ = raise Domain
fun vector _ = raise Domain
fun copy _ = raise Domain
fun copyVec _ = raise Domain
fun appi _ = raise Domain
fun app _ = raise Domain
fun modifyi _ = raise Domain
fun modify _ = raise Domain
fun foldli _ = raise Domain
fun foldl _ = raise Domain
fun foldri _ = raise Domain
fun foldr _ = raise Domain
fun findi _ = raise Domain
fun find _ = raise Domain
fun exists _ = raise Domain
fun all _ = raise Domain
fun collate _ = raise Domain
end
structure DisjointViewSort = ArrayQSortFn (DisjointView)
fun sort cmp (arr, indices) = (
ArrayQSort.sort Int.compare indices;
DisjointViewSort.sort cmp (arr, indices)
)
end
|
http://rosettacode.org/wiki/Sort_disjoint_sublist
|
Sort disjoint sublist
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted.
Make your example work with the following list of values and set of indices:
Values: [7, 6, 5, 4, 3, 2, 1, 0]
Indices: {6, 1, 7}
Where the correct result would be:
[7, 0, 5, 4, 3, 2, 1, 6].
In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead.
The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given.
Cf.
Order disjoint list items
|
#Swift
|
Swift
|
struct DisjointSublistView<T> : MutableCollectionType {
let array : UnsafeMutablePointer<T>
let indexes : [Int]
subscript (position: Int) -> T {
get {
return array[indexes[position]]
}
set {
array[indexes[position]] = newValue
}
}
var startIndex : Int { return 0 }
var endIndex : Int { return indexes.count }
func generate() -> IndexingGenerator<DisjointSublistView<T>> { return IndexingGenerator(self) }
}
func sortDisjointSublist<T : Comparable>(inout array: [T], indexes: [Int]) {
var d = DisjointSublistView(array: &array, indexes: sorted(indexes))
sort(&d)
}
var a = [7, 6, 5, 4, 3, 2, 1, 0]
let ind = [6, 1, 7]
sortDisjointSublist(&a, ind)
println(a)
|
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.
|
#Wren
|
Wren
|
import "/sort" for Cmp, Sort
var cmp = Fn.new { |s, t|
if (s.count < t.count) return 1
if (s.count > t.count) return -1
return Cmp.insensitive.call(s, t)
}
var strings = ["Here", "are", "some", "sample", "strings", "to", "be", "sorted"]
System.print("Unsorted: %(strings)")
Sort.insertion(strings, cmp)
System.print("Sorted : %(strings)")
|
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.
|
#zkl
|
zkl
|
s:=T("Cat","apple","Adam","zero","Xmas","quit","Level","add","Actor","base","butter");
r:=s.sort(fcn(a,b){
an,bn := a.len(),b.len();
if(an==bn)(a.toLower() < b.toLower()) else (an > bn)
});
r.pump(Console.println);
|
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort
|
Sorting algorithms/Bubble sort
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
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.
|
#Lucid
|
Lucid
|
bsort(a) = if iseod(first a) then a else
follow(bsort(allbutlast(b)),last(b)) fi
where
b = bubble(a);
bubble(a) = smaller(max, next a)
where
max = first a fby larger(max, next a);
larger(x,y) = if iseod(y) then y elseif x
end;
follow(x,y) = if xdone then y upon xdone else x fi
where
xdone = iseod x fby xdone or iseod x;
end;
last(x) = (x asa iseod next x) fby eod;
allbutlast(x) = if not iseod(next x) then x else eod fi;
end
|
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort
|
Sorting algorithms/Gnome sort
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Gnome sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort.
The pseudocode for the algorithm is:
function gnomeSort(a[0..size-1])
i := 1
j := 2
while i < size do
if a[i-1] <= a[i] then
// for descending sort, use >= for comparison
i := j
j := j + 1
else
swap a[i-1] and a[i]
i := i - 1
if i = 0 then
i := j
j := j + 1
endif
endif
done
Task
Implement the Gnome sort in your language to sort an array (or list) of numbers.
|
#Tcl
|
Tcl
|
package require Tcl 8.5
package require struct::list
proc gnomesort {a} {
set i 1
set j 2
set size [llength $a]
while {$i < $size} {
if {[lindex $a [expr {$i - 1}]] <= [lindex $a $i]} {
set i $j
incr j
} else {
struct::list swap a [expr {$i - 1}] $i
incr i -1
if {$i == 0} {
set i $j
incr j
}
}
}
return $a
}
puts [gnomesort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9
|
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
|
#Seed7
|
Seed7
|
const proc: cocktailSort (inout array elemType: arr) is func
local
var boolean: swapped is FALSE;
var integer: i is 0;
var elemType: help is elemType.value;
begin
repeat
swapped := FALSE;
for i range 1 to length(arr) - 1 do
if arr[i] > arr[i + 1] then
help := arr[i];
arr[i] := arr[i + 1];
arr[i + 1] := help;
swapped := TRUE;
end if;
end for;
if swapped then
swapped := FALSE;
for i range length(arr) - 1 downto 1 do
if arr[i] > arr[i + 1] then
help := arr[i];
arr[i] := arr[i + 1];
arr[i + 1] := help;
swapped := TRUE;
end if;
end for;
end if;
until not swapped;
end func;
|
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.
|
#Ring
|
Ring
|
Load "guilib.ring"
new qApp {
oClient = new Client { client() }
exec()
}
Class Client
win1 oTcpSocket
func client
win1 = new qwidget()
new qpushbutton(win1) {
setgeometry(50,50,100,30)
settext("connect")
setclickevent("oClient.Connect()")
}
win1 {
setwindowtitle("client")
setgeometry(10,100,400,400)
show()
}
func connect
oTcpSocket = new qTcpSocket(win1) {
setconnectedevent("oClient.pConnected()")
connecttohost("127.0.0.1",256,3,0)
waitforconnected(5000)
}
func pConnected
cStr = "hello socket world"
write(cStr,len(cStr))
flush()
waitforbyteswritten(300000)
close()
|
http://rosettacode.org/wiki/Sockets
|
Sockets
|
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
|
#Ruby
|
Ruby
|
require 'socket'
sock = TCPSocket.open("localhost", 256)
sock.write("hello socket world")
sock.close
|
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].
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module Checkit {
Set Fast !
Form 80, 40
Refresh
Function Smith(max=10000) {
Function SumDigit(a$) {
def long sum
For i=1 to len(a$) {sum+=val(mid$(a$,i, 1)) }
=sum
}
x=max
\\ Euler's Sieve
Dim r(x+1)=1
k=2
k2=k**2
While k2<x {
For m=k2 to x step k {r(m)=0}
Repeat {
k++ : k2=k**2
} Until r(k)=1 or k2>x
}
r(0)=0
smith=0
smith2=0
lastI=0
inventory smithnumbers
Top=max div 100
c=4
For i=4 to max {
if c> top then print over $(0,6), ceil(i/max*100);"%" : Refresh : c=1
c++
if r(i)=0 then {
smith=sumdigit(str$(i)) : lastI=i
smith2=0
do {
ii=int(sqrt(i))+1
do { ii-- : while r(ii)<>1 {ii--} } until i mod ii=0
if ii<2 then smith2+=sumdigit(str$(i)):exit
smith3=sumdigit(str$(ii))
do {
smith2+=smith3
i=i div ii : if ii<2 or i<2 then exit
} until i mod ii<>0 or smith2>smith
} until i<2 or smith2>smith
If smith=smith2 then Append smithnumbers, lastI
}
}
=smithnumbers
}
const MaxNumbers=10000
numbers= Smith(MaxNumbers)
Print
Print $(,5), numbers
Print
Print format$(" {0} smith numbers found <= {1}", Len(numbers), MaxNumbers)
}
Checkit
|
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].
|
#MAD
|
MAD
|
NORMAL MODE IS INTEGER
PRINT COMMENT$ SMITH NUMBERS$
R GENERATE PRIMES UP TO 10,000 USING SIEVE METHOD
BOOLEAN SIEVE
DIMENSION SIEVE(10000)
DIMENSION PRIMES(1500)
THROUGH SET, FOR I=2, 1, I.G.10000
SET SIEVE(I) = 1B
THROUGH NXPRIM, FOR P=2, 1, P.G.100
WHENEVER SIEVE(P)
THROUGH MARK, FOR I=P*P, P, I.G.10000
MARK SIEVE(I) = 0B
NXPRIM END OF CONDITIONAL
NPRIMS = 0
THROUGH CNTPRM, FOR P=2, 1, P.G.10000
WHENEVER SIEVE(P)
PRIMES(NPRIMS) = P
NPRIMS = NPRIMS + 1
CNTPRM END OF CONDITIONAL
R CHECK SMITH NUMBERS
THROUGH SMITH, FOR I=4, 1, I.GE.10000
WHENEVER .NOT. SIEVE(I)
K = I
PFSUM = 0
THROUGH FACSUM, FOR P=0, 1, P.GE.NPRIMS .OR. K.E.0
L = PRIMES(P)
FACDIV WHENEVER K/L*L.E.K .AND. K.NE.0
PFSUM = PFSUM + DGTSUM.(L)
K = K/L
TRANSFER TO FACDIV
FACSUM END OF CONDITIONAL
WHENEVER PFSUM.E.DGTSUM.(I), PRINT FORMAT NUMFMT,I
SMITH END OF CONDITIONAL
VECTOR VALUES NUMFMT = $I5*$
R GET SUM OF DIGITS OF N
INTERNAL FUNCTION(N)
ENTRY TO DGTSUM.
DSUM = 0
DNUM = N
LOOP WHENEVER DNUM.E.0, FUNCTION RETURN DSUM
DSUM = DSUM + DNUM-DNUM/10*10
DNUM = DNUM/10
TRANSFER TO LOOP
END OF FUNCTION
END OF PROGRAM
|
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;
|
#Ruby
|
Ruby
|
# Solve a Hidato Puzzle
#
class Hidato
Cell = Struct.new(:value, :used, :adj)
ADJUST = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]]
def initialize(board, pout=true)
@board = []
board.each_line do |line|
@board << line.split.map{|n| Cell[Integer(n), false] rescue nil} + [nil]
end
@board << [] # frame (Sentinel value : nil)
@board.each_with_index do |row, x|
row.each_with_index do |cell, y|
if cell
@sx, @sy = x, y if cell.value==1 # start position
cell.adj = ADJUST.map{|dx,dy| [x+dx,y+dy]}.select{|xx,yy| @board[xx][yy]}
end
end
end
@xmax = @board.size - 1
@ymax = @board.map(&:size).max - 1
@end = @board.flatten.compact.size
puts to_s('Problem:') if pout
end
def solve
@zbl = Array.new(@end+1, false)
@board.flatten.compact.each{|cell| @zbl[cell.value] = true}
puts (try(@board[@sx][@sy], 1) ? to_s('Solution:') : "No solution")
end
def try(cell, seq_num)
return true if seq_num > @end
return false if cell.used
value = cell.value
return false if value > 0 and value != seq_num
return false if value == 0 and @zbl[seq_num]
cell.used = true
cell.adj.each do |x, y|
if try(@board[x][y], seq_num+1)
cell.value = seq_num
return true
end
end
cell.used = false
end
def to_s(msg=nil)
str = (0...@xmax).map do |x|
(0...@ymax).map{|y| "%3s" % ((c=@board[x][y]) ? c.value : c)}.join
end
(msg ? [msg] : []) + str + [""]
end
end
|
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures
|
Sort an array of composite structures
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Sort an array of composite structures by a key.
For example, if you define a composite structure that presents a name-value pair (in pseudo-code):
Define structure pair such that:
name as a string
value as a string
and an array of such pairs:
x: array of pairs
then define a sort routine that sorts the array x by the key name.
This task can always be accomplished with Sorting Using a Custom Comparator.
If your language is not listed here, please see the other article.
|
#Phixmonti
|
Phixmonti
|
include ..\Utilitys.pmt
def minverse
reverse
enddef
getid minverse var f
( ( "grass" "green" ) ( "snow" "white" ) ( "sky" "blue" ) ( "cherry" "red" ) ( 0 1.2 ) ( 3.4 -1 ) )
dup
sort print nl
/# sorted by second component #/
f map sort f map print
|
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.
|
#PicoLisp
|
PicoLisp
|
: (sort '(("def" 456) ("abc" 789) ("ghi" 123)))
-> (("abc" 789) ("def" 456) ("ghi" 123))
|
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.
|
#Objective-C
|
Objective-C
|
NSArray *nums = @[@2, @4, @3, @1, @2];
NSArray *sorted = [nums sortedArrayUsingSelector:@selector(compare:)];
|
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.
|
#OCaml
|
OCaml
|
let nums = [|2; 4; 3; 1; 2|]
Array.sort compare nums
|
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
|
#Tcl
|
Tcl
|
package require Tcl 8.5
proc disjointSort {values indices args} {
# Ensure that we have a unique list of integers, in order
# We assume there are no end-relative indices
set indices [lsort -integer -unique $indices]
# Map from those indices to the values to sort
set selected {}
foreach i $indices {lappend selected [lindex $values $i]}
# Sort the values (using any extra options) and write back to the list
foreach i $indices v [lsort {*}$args $selected] {
lset values $i $v
}
# The updated list is the result
return $values
}
|
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.
|
#M2000_Interpreter
|
M2000 Interpreter
|
Module Bubble {
function bubblesort {
dim a()
\\ [] is a stack object, interpreter pass current stack pointer, and set a new stack for current stack
\\ array( stackobject ) get a stack object and return an array
a()=array([])
itemcount=len(a())
repeat {
haschange=false
if itemcount>1 then {
for index=0 to itemcount-2 {
if a(index)>a(index+1) then swap a(index), a(index+1) : haschange=true
}
}
itemcount--
} until not haschange
=a()
}
\\ function can take parameters
Print bubblesort(5,3,2,7,6,1)
A=(2, 10, 17, 13, 20, 14, 3, 17, 16, 16)
\\ !A copy values from array A to function stack
B=bubblesort(!A)
Print Len(A)=10
Print B
\\ Print array in descending order
k=each(b, -1, 1)
While k {
Print Array(k),
}
\\ sort two arrays in one
Print BubbleSort(!A, !B)
\\ We can use a stack object, and values pop from object
Z=Stack:=2, 10, 17, 13, 20, 14, 3, 17, 16, 16
Print Len(Z)=10
Def GetStack(x)=Stack(x)
Z1=GetStack(BubbleSort(!Z))
Print Type$(Z1)="mStiva"
Print Z1
Print Len(Z1)
Print Len(Z)=0 ' now Z is empty
}
Bubble
|
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.
|
#TI-83_BASIC
|
TI-83 BASIC
|
:1→P
:L1→L2
:While P<dim(L2)
:If PP=1
:Then
:P+1→P
:Else
:If L2(P)≥L2(P-1)
:Then
:P+1→P
:Else
:L2(P)→Q
:L2(P-1)→L2(P)
:Q→L2(P-1)
:P-1→P
:End
:End
:End
:If L2(dim(L2))<L2(dim(L2)-1)
:Then
:L2(dim(L2))→Q
:L2(dim(L2)-1)→L2(dim(L2))
:Q→L2(dim(L2)-1)
:End
:DelVar P
:DelVar Q
:Return
|
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
|
#Sidef
|
Sidef
|
func cocktailsort(a) {
var swapped = false
func cmpsw(i) {
if (a[i] > a[i+1]) {
a[i, i+1] = a[i+1, i]
swapped = true
}
}
var max = a.end
do {
{|i| cmpsw(i) } << ^max
swapped.not! && break
{|i| cmpsw(max-i) } << 1..max
} while (swapped)
return a
}
|
http://rosettacode.org/wiki/Sockets
|
Sockets
|
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
|
#Rust
|
Rust
|
use std::io::prelude::*;
use std::net::TcpStream;
fn main() {
// Open a tcp socket connecting to 127.0.0.1:256, no error handling (unwrap)
let mut my_stream = TcpStream::connect("127.0.0.1:256").unwrap();
// Write 'hello socket world' to the stream, ignoring the result of write
let _ = my_stream.write(b"hello socket world");
} // <- my_stream's drop function gets called, which closes the 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.
|
#Scala
|
Scala
|
import java.net.Socket
object sendSocketData {
def sendData(host: String, msg: String) {
val sock = new Socket(host, 256)
sock.getOutputStream().write(msg.getBytes())
sock.getOutputStream().flush()
sock.close()
}
sendData("localhost", "hello socket world")
}
|
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].
|
#Maple
|
Maple
|
isSmith := proc(n::posint)
local factors, sumofDigits, sumofFactorDigits, x;
if isprime(n) then
return false;
else
sumofDigits := add(x, x = convert(n, base, 10));
sumofFactorDigits := add(map(x -> op(convert(x, base, 10)), [op(NumberTheory:-PrimeFactors(n))]));
return evalb(sumofDigits = sumofFactorDigits);
end if;
end proc:
findSmith := proc(n::posint)
return select(isSmith, [seq(1 .. n - 1)]);
end proc:
findSmith(10000);
|
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].
|
#Mathematica.2FWolfram_Language
|
Mathematica/Wolfram Language
|
smithQ[n_] := Not[PrimeQ[n]] &&
Total[IntegerDigits[n]] == Total[IntegerDigits /@ Flatten[ConstantArray @@@ FactorInteger[n]],2];
Select[Range[2, 10000], smithQ]
|
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;
|
#Rust
|
Rust
|
use std::cmp::{max, min};
use std::fmt;
use std::ops;
#[derive(Debug, Clone, PartialEq)]
struct Board {
cells: Vec<Vec<Option<u32>>>,
}
impl Board {
fn new(initial_board: Vec<Vec<u32>>) -> Self {
let b = initial_board
.iter()
.map(|r| {
r.iter()
.map(|c| if *c == u32::MAX { None } else { Some(*c) })
.collect()
})
.collect();
Board { cells: b }
}
fn height(&self) -> usize {
self.cells.len()
}
fn width(&self) -> usize {
self.cells[0].len()
}
}
impl ops::Index<(usize, usize)> for Board {
type Output = Option<u32>;
fn index(&self, (y, x): (usize, usize)) -> &Self::Output {
&self.cells[y][x]
}
}
impl ops::IndexMut<(usize, usize)> for Board {
/// Returns a mutable reference to an cell for a given 'x' 'y' coordinates
fn index_mut(&mut self, (y, x): (usize, usize)) -> &mut Option<u32> {
&mut self.cells[y][x]
}
}
impl fmt::Display for Board {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let output: Vec<String> = self
.cells
.iter()
.map(|r| {
let mut row = String::default();
r.iter().for_each(|c| match c {
None => row.push_str(format!("{:>2} ", " ").as_ref()),
Some(c) if c == &0 => row.push_str(format!("{:>2} ", ".").as_ref()),
Some(c) => row.push_str(format!("{:>2} ", c).as_ref()),
});
row
})
.collect();
write!(f, "{}", output.join("\n"))
}
}
/// Structure for holding puzzle related information.
#[derive(Clone, Debug)]
struct Puzzle {
/// The state of the board.
board: Board,
/// All the numbers which were given at puzzle setup:
/// the numbers which cannot be changed during solving the puzzle.
fixed: Vec<u32>,
/// Position of the first number (1).
start: (usize, usize),
}
impl Puzzle {
/// Creates a new puzzle
/// * `initial_board` contains the layout and the startin position.
///
/// - Simple numbers in the `initial_board` are considered as "fixed",
/// aka the solving does not change them
///
/// - As the board can be non-rectangular, all cells which are invalid or cannot be used
/// are marked with u32::MAX in the `initial_board`
fn new(initial_board: Vec<Vec<u32>>) -> Self {
let mut s: (usize, usize) = (0, 0);
let mut f = initial_board
.iter()
.enumerate()
.flat_map(|(y, r)| r.iter().enumerate().map(move |(x, c)| (y, x, *c)))
.filter(|(_, _, c)| (1..u32::MAX).contains(c))
.fold(Vec::new(), |mut fixed, (y, x, c)| {
fixed.push(c);
if c == 1 {
// store the position of the start
s = (y, x)
};
fixed
});
f.sort_unstable();
Puzzle {
board: Board::new(initial_board),
fixed: f,
start: s,
}
}
pub fn print_board(&self) {
println!("{}", self.board);
}
fn solver(&mut self, current: (usize, usize), n: &u32, mut next: usize) -> bool {
// reached the last number, solving successful
if n > self.fixed.last().unwrap() {
return true;
}
// check for exit conditions
match self.board[current] {
// cell outside of the board
None => return false,
//cell is already has a number in it
Some(c) if c != 0 && c != *n => return false,
//cell is empty, but the to be placed number is already matching the next fixed number
Some(c) if c == 0 && self.fixed[next] == *n => return false,
// continue
_ => (),
}
let mut backup: u32 = 0;
if self.board[current] == Some(*n) {
backup = *n;
next += 1;
}
self.board[current] = Some(*n);
for y in (max(current.0, 1) - 1)..=min(current.0 + 1, self.board.height() - 1) {
for x in (max(current.1, 1) - 1)..=min(current.1 + 1, self.board.width() - 1) {
if self.solver((y, x), &(n + 1), next) {
return true;
}
}
}
// unsuccessful branch, restore original value
self.board[current] = Some(backup);
false
}
pub fn solve(&mut self) {
let start = self.start;
self.solver(start, &1, 0);
}
}
fn main() {
let input = vec![
vec![0, 33, 35, 0, 0, u32::MAX, u32::MAX, u32::MAX],
vec![0, 0, 24, 22, 0, u32::MAX, u32::MAX, u32::MAX],
vec![0, 0, 0, 21, 0, 0, u32::MAX, u32::MAX],
vec![0, 26, 0, 13, 40, 11, u32::MAX, u32::MAX],
vec![27, 0, 0, 0, 9, 0, 1, u32::MAX],
vec![u32::MAX, u32::MAX, 0, 0, 18, 0, 0, u32::MAX],
vec![u32::MAX, u32::MAX, u32::MAX, u32::MAX, 0, 7, 0, 0],
vec![
u32::MAX,
u32::MAX,
u32::MAX,
u32::MAX,
u32::MAX,
u32::MAX,
5,
0,
],
];
let mut p = Puzzle::new(input);
p.print_board();
p.solve();
println!("\nSolution:");
p.print_board();
}
|
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.
|
#PowerShell
|
PowerShell
|
$list = @{
"def" = "one"
"abc" = "two"
"jkl" = "three"
"abcdef" = "four"
"ghi" = "five"
"ghijkl" = "six"
}
$list.GetEnumerator() | sort {-($PSItem.Name).length}, Name
|
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.
|
#Octave
|
Octave
|
sortedv = sort(v);
|
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
|
#TUSCRIPT
|
TUSCRIPT
|
$$ MODE TUSCRIPT
values="7'6'5'4'3'2'1'0"
indices="7'2'8"
v_unsorted=SELECT (values,#indices)
v_sort=DIGIT_SORT (v_unsorted)
i_sort=DIGIT_SORT (indices)
LOOP i=i_sort,v=v_sort
values=REPLACE (values,#i,v)
ENDLOOP
PRINT values
|
http://rosettacode.org/wiki/Sort_disjoint_sublist
|
Sort disjoint sublist
|
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a list of values and a set of integer indices into that value list, the task is to sort the values at the given indices, while preserving the values at indices outside the set of those to be sorted.
Make your example work with the following list of values and set of indices:
Values: [7, 6, 5, 4, 3, 2, 1, 0]
Indices: {6, 1, 7}
Where the correct result would be:
[7, 0, 5, 4, 3, 2, 1, 6].
In case of one-based indexing, rather than the zero-based indexing above, you would use the indices {7, 2, 8} instead.
The indices are described as a set rather than a list but any collection-type of those indices without duplication may be used as long as the example is insensitive to the order of indices given.
Cf.
Order disjoint list items
|
#Ursala
|
Ursala
|
#import std
#import nat
disjoint_sort = ^|(~&,num); ("i","v"). (-:(-:)"v"@p nleq-<~~lSrSX ~&rlPlw~|/"i" "v")*lS "v"
#cast %nL
t = disjoint_sort({6,1,7},<7,6,5,4,3,2,1,0>)
|
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.
|
#M4
|
M4
|
divert(-1)
define(`randSeed',141592653)
define(`setRand',
`define(`randSeed',ifelse(eval($1<10000),1,`eval(20000-$1)',`$1'))')
define(`rand_t',`eval(randSeed^(randSeed>>13))')
define(`random',
`define(`randSeed',eval((rand_t^(rand_t<<18))&0x7fffffff))randSeed')
define(`set',`define(`$1[$2]',`$3')')
define(`get',`defn(`$1[$2]')')
define(`new',`set($1,size,0)')
dnl for the heap calculations, it's easier if origin is 0, so set value first
define(`append',
`set($1,size,incr(get($1,size)))`'set($1,get($1,size),$2)')
dnl swap(<name>,<j>,<name>[<j>],<k>) using arg stack for the temporary
define(`swap',`set($1,$2,get($1,$4))`'set($1,$4,$3)')
define(`deck',
`new($1)for(`x',1,$2,
`append(`$1',eval(random%100))')')
define(`show',
`for(`x',1,get($1,size),`get($1,x) ')')
define(`for',
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
`pushdef(`$1',$2)$4`'popdef(`$1')$0(`$1',incr($2),$3,`$4')')')')
define(`bubbleonce',
`for(`x',1,$2,
`ifelse(eval(get($1,x)>get($1,incr(x))),1,
`swap($1,x,get($1,x),incr(x))`'1')')0')
define(`bubbleupto',
`ifelse(bubbleonce($1,$2),0,
`',
`bubbleupto($1,decr($2))')')
define(`bubblesort',
`bubbleupto($1,decr(get($1,size)))')
divert
deck(`a',10)
show(`a')
bubblesort(`a')
show(`a')
|
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.
|
#True_BASIC
|
True BASIC
|
RANDOMIZE !RAMDOMZE TIMER en QBASIC
DIM array(-5 TO 12)
CALL iniciarray(array())
PRINT "unsort: ";
CALL escritura(array())
CALL gnomeSort(array())
PRINT
PRINT " sort: ";
CALL escritura(array())
END
SUB escritura (array())
FOR i = LBOUND(array) TO UBOUND(array)
PRINT array(i);
NEXT i
PRINT
END SUB
SUB gnomeSort (array())
LET i = LBOUND(array) + 1
LET j = i + 1
DO WHILE i <= UBOUND(array)
IF array(i - 1) <= array(i) THEN
LET i = j
LET j = j + 1
ELSE
LET T = array(i - 1)
LET array(i - 1) = array(i)
LET array(i) = T
LET i = i - 1
IF i = LBOUND(array) THEN
LET i = j
LET j = j + 1
END IF
END IF
LOOP
END SUB
SUB iniciarray (array())
FOR i = LBOUND(array) TO UBOUND(array)
LET array(i) = (RND * 98) + 1
NEXT i
END SUB
|
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
|
#Slate
|
Slate
|
s@(Sequence traits) cocktailSort
[ |swapped|
swapped: False.
s size <= 1 ifTrue: [^ s].
[{0 to: s size - 2. s size - 2 downTo: 0}
do: [|:range| range do: [|:index| (s at: index) > (s at: index + 1) ifTrue: [s swap: index with: index + 1. swapped: True]].
swapped ifFalse: [^ s].
swapped: False].
] loop
].
|
http://rosettacode.org/wiki/Sockets
|
Sockets
|
For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
|
#Scheme
|
Scheme
|
(let ((s (socket PF_INET SOCK_STREAM 0)))
(connect s AF_INET (inet-pton AF_INET "127.0.0.1") 256)
(display "hello socket world" s))
|
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.
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
include "socket.s7i";
const proc: main is func
local
var file: sock is STD_NULL;
begin
sock := openInetSocket(256);
writeln(sock, "hello socket world");
close(sock);
end func;
|
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].
|
#Modula-2
|
Modula-2
|
MODULE SmithNumbers;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
PROCEDURE SumDigits(n : INTEGER) : INTEGER;
VAR sum : INTEGER;
BEGIN
sum := 0;
WHILE n > 0 DO
sum := sum + (n MOD 10);
n := n DIV 10;
END;
RETURN sum;
END SumDigits;
VAR
n,i,j,fc,sum,rc : INTEGER;
buf : ARRAY[0..63] OF CHAR;
BEGIN
rc := 0;
FOR i:=1 TO 10000 DO
n := i;
fc := 0;
sum := SumDigits(n);
j := 2;
WHILE n MOD j = 0 DO
INC(fc);
sum := sum - SumDigits(j);
n := n DIV j;
END;
j := 3;
WHILE j*j<=n DO
WHILE n MOD j = 0 DO
INC(fc);
sum := sum - SumDigits(j);
n := n DIV j;
END;
INC(j,2);
END;
IF n#1 THEN
INC(fc);
sum := sum - SumDigits(n);
END;
IF (fc>1) AND (sum=0) THEN
FormatString("%4i ", buf, i);
WriteString(buf);
INC(rc);
IF rc=10 THEN
rc := 0;
WriteLn;
END;
END;
END;
ReadChar;
END SmithNumbers.
|
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;
|
#Seed7
|
Seed7
|
$ include "seed7_05.s7i";
var set of integer: given is {};
var array array integer: board is 0 times 0 times 0;
var integer: startRow is 0;
var integer: startColumn is 0;
const proc: setup (in array string: input) is func
local
var integer: r is 0;
var integer: c is 0;
var array string: row is 0 times "";
var string: cell is "";
var integer: value is 0;
begin
board := (length(input) + 2) times 0 times 0;
for key r range input do
row := split(input[r], " ");
board[r + 1] := (length(row) + 2) times - 1;
for key c range row do
cell := row[c];
if cell = "_" then
board[r + 1][c + 1] := 0;
elsif cell[1] in {'0' .. '9'} then
value := integer parse cell;
board[r + 1][c + 1] := value;
incl(given, value);
if value = 1 then
startRow := r + 1;
startColumn := c + 1;
end if;
end if;
end for;
end for;
board[1] := (length(row) + 2) times - 1;
board[length(input) + 2] := (length(row) + 2) times - 1;
end func;
const func boolean: solve (in integer: r, in integer: c, in integer: n) is func
result
var boolean: solved is FALSE;
local
var integer: back is 0;
var integer: i is 0;
var integer: j is 0;
begin
if n > max(given) then
solved := TRUE;
elsif board[r][c] = 0 and n not in given or board[r][c] = n then
back := board[r][c];
board[r][c] := n;
for i range -1 to 1 until solved do
for j range -1 to 1 until solved do
solved := solve(r + i, c + j, n + 1);
end for;
end for;
if not solved then
board[r][c] := back;
end if;
end if;
end func;
const proc: printBoard is func
local
var integer: r is 0;
var integer: c is 0;
begin
for key r range board do
for c range board[r] do
if c = -1 then
write(" . ");
elsif c > 0 then
write(c lpad 2 <& " ");
else
write("__ ");
end if;
end for;
writeln;
end for;
end func;
const proc: main is func
local
const array string: input is [] ("_ 33 35 _ _ . . .",
"_ _ 24 22 _ . . .",
"_ _ _ 21 _ _ . .",
"_ 26 _ 13 40 11 . .",
"27 _ _ _ 9 _ 1 .",
". . _ _ 18 _ _ .",
". . . . _ 7 _ _",
". . . . . . 5 _");
begin
setup(input);
printBoard;
writeln;
if solve(startRow, startColumn, 1) then
writeln("Found:");
printBoard;
end if;
end func;
|
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.
|
#PureBasic
|
PureBasic
|
Structure MyPair ; Define a structured data type
Name$
Value.i
EndStructure
Dim People.MyPair(2) ; Allocate some elements
People(0)\Name$ = "John" ; Start filling them in
People(0)\Value = 100
People(1)\Name$ = "Emma"
People(1)\Value = 200
People(2)\Name$ = "Johnny"
People(2)\Value = 175
If OpenConsole()
Define i
; Sort ascending by name
SortStructuredArray(People(), #PB_Sort_Ascending, OffsetOf(MyPair\Name$), #PB_Sort_String)
PrintN(#CRLF$+"Sorted ascending by name.")
For i=0 To 2
PrintN(People(i)\Name$+" - Value: "+Str(People(i)\Value))
Next
; Sort descending by value
SortStructuredArray(People(), #PB_Sort_Descending, OffsetOf(MyPair\Value), #PB_Sort_Integer)
PrintN(#CRLF$+"Sorted descending by value.")
For i=0 To 2
PrintN(People(i)\Name$+" - Value: "+Str(People(i)\Value))
Next
; Wait for user...
PrintN(#CRLF$+"Press ENTER to exit"):Input()
EndIf
|
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.
|
#Oforth
|
Oforth
|
[ 8, 2, 5, 9, 1, 3, 6, 7, 4 ] 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.
|
#ooRexx
|
ooRexx
|
a = .array~of(4, 1, 6, -2, 99, -12)
say "The sorted numbers are"
say a~sortWith(.numericComparator~new)~makeString
|
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
|
#Wren
|
Wren
|
import "/sort" for Sort
// sorts values in place, leaves indices unsorted
var sortDisjoint = Fn.new { |values, indices|
var sublist = []
for (ix in indices) sublist.add(values[ix])
Sort.quick(sublist)
var i = 0
var indices2 = Sort.merge(indices)
for (ix in indices2) {
values[ix] = sublist[i]
i = i + 1
}
}
var values = [7, 6, 5, 4, 3, 2, 1, 0]
var indices = [6, 1, 7]
System.print("Initial: %(values)")
sortDisjoint.call(values, indices)
System.print("Sorted : %(values)")
|
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.
|
#Maple
|
Maple
|
arr := Array([17,3,72,0,36,2,3,8,40,0]):
len := numelems(arr):
while(true) do
change := false:
len--;
for i from 1 to len do
if (arr[i] > arr[i+1]) then
temp := arr[i]:
arr[i] := arr[i+1]:
arr[i+1] := temp:
change := true:
end if:
end do:
if (not change) then break end if:
end do:
arr;
|
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.
|
#uBasic.2F4tH
|
uBasic/4tH
|
PRINT "Gnome sort:"
n = FUNC (_InitArray)
PROC _ShowArray (n)
PROC _Gnomesort (n)
PROC _ShowArray (n)
PRINT
END
_Gnomesort PARAM (1) ' Gnome sort
LOCAL (2)
b@=1
c@=2
DO WHILE b@ < a@
IF @(b@-1) > @(b@) THEN
PROC _Swap (b@, b@-1)
b@ = b@ - 1
IF b@ THEN
CONTINUE
ENDIF
ENDIF
b@ = c@
c@ = c@ + 1
LOOP
RETURN
_Swap PARAM(2) ' Swap two array elements
PUSH @(a@)
@(a@) = @(b@)
@(b@) = POP()
RETURN
_InitArray ' Init example array
PUSH 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
FOR i = 0 TO 9
@(i) = POP()
NEXT
RETURN (i)
_ShowArray PARAM (1) ' Show array subroutine
FOR i = 0 TO a@-1
PRINT @(i),
NEXT
PRINT
RETURN
|
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
|
#Smalltalk
|
Smalltalk
|
OrderedCollection extend [
swap: indexA and: indexB [
|t|
t := self at: indexA.
self at: indexA put: (self at: indexB).
self at: indexB put: t
]
cocktailSort [
|swapped|
[
swapped := false.
1 to: (self size - 1) do: [ :i |
(self at: i) > (self at: (i+1)) ifTrue: [
self swap: i and: (i+1).
swapped := true
]
].
swapped ifFalse: [ ^ self ].
swapped := false.
(self size - 1) to: 1 by: -1 do: [ :i |
(self at: i) > (self at: (i+1)) ifTrue: [
self swap: i and: (i+1).
swapped := true
]
].
swapped
] whileTrue: [ ].
^ self
]
].
|
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.
|
#SenseTalk
|
SenseTalk
|
set SocketID to "localhost:256"
open socket SocketID
write "Hello socket world!" to socket SocketID
close socket SocketID
|
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.
|
#Sidef
|
Sidef
|
var host = Socket.gethostbyname('localhost');
var in = Socket.sockaddr_in(256, host);
var proto = Socket.getprotobyname('tcp');
var sock = Socket.open(Socket.AF_INET, Socket.SOCK_STREAM, proto);
sock.connect(in);
sock.send('hello socket world', 0, in);
sock.close;
|
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].
|
#Nim
|
Nim
|
import strformat
func primeFactors(n: int): seq[int] =
result = newSeq[int]()
var n = n
var i = 2
while n mod i == 0:
result.add(i)
n = n div i
i = 3
while i * i <= n:
while n mod i == 0:
result.add(i)
n = n div i
inc i, 2
if n != 1:
result.add(n)
func sumDigits(n: int): int =
var n = n
var sum = 0
while n > 0:
inc sum, n mod 10
n = n div 10
sum
var cnt = 0
for n in 1..10_000:
var factors = primeFactors(n)
if factors.len > 1:
var sum = sumDigits(n)
for f in factors:
dec sum, sumDigits(f)
if sum == 0:
stdout.write(&"{n:4} ")
inc cnt
if cnt == 10:
cnt = 0
stdout.write("\n")
echo()
|
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].
|
#Objeck
|
Objeck
|
use Collection;
class Test {
function : Main(args : String[]) ~ Nil {
for(n := 1; n < 10000; n+=1;) {
factors := PrimeFactors(n);
if(factors->Size() > 1) {
sum := SumDigits(n);
each(i : factors) {
sum -= SumDigits(factors->Get(i));
};
if(sum = 0) {
n->PrintLine();
};
};
};
}
function : PrimeFactors(n : Int) ~ IntVector {
result := IntVector->New();
for(i := 2; n % i = 0; n /= i;) {
result->AddBack(i);
};
for(i := 3; i * i <= n; i += 2;) {
while(n % i = 0) {
result->AddBack(i);
n /= i;
};
};
if(n <> 1) {
result->AddBack(n);
};
return result;
}
function : SumDigits(n : Int) ~ Int {
sum := 0;
while(n > 0) {
sum += (n % 10);
n /= 10;
};
return sum;
}
}
|
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle
|
Solve a Hidato puzzle
|
The task is to write a program which solves Hidato (aka Hidoku) puzzles.
The rules are:
You are given a grid with some numbers placed in it. The other squares in the grid will be blank.
The grid is not necessarily rectangular.
The grid may have holes in it.
The grid is always connected.
The number “1” is always present, as is another number that is equal to the number of squares in the grid. Other numbers are present so as to force the solution to be unique.
It may be assumed that the difference between numbers present on the grid is not greater than lucky 13.
The aim is to place a natural number in each blank square so that in the sequence of numbered squares from “1” upwards, each square is in the wp:Moore neighborhood of the squares immediately before and after it in the sequence (except for the first and last squares, of course, which only have one-sided constraints).
Thus, if the grid was overlaid on a chessboard, a king would be able to make legal moves along the path from first to last square in numerical order.
A square may only contain one number.
In a proper Hidato puzzle, the solution is unique.
For example the following problem
has the following solution, with path marked on it:
Related tasks
A* search algorithm
N-queens problem
Solve a Holy Knight's tour
Solve a Knight's tour
Solve a Hopido puzzle
Solve a Numbrix puzzle
Solve the no connection puzzle;
|
#Tailspin
|
Tailspin
|
def input:
'__ 33 35 __ __ . . .
__ __ 24 22 __ . . .
__ __ __ 21 __ __ . .
__ 26 __ 13 40 11 . .
27 __ __ __ 9 __ 1 .
. . __ __ 18 __ __ .
. . . . __ 7 __ __
. . . . . . 5 __';
templates hidato
composer setup
data givenInput <[<={}|{row: <row>, col: <col>}>*]> local
@: {row: 1, col: 1, givenInput:[]};
{ board: [ <line>+ ], given: [email protected] -> \[i](<~={}> { n: $i, $...} !\) }
rule line: [ <cell>+ ] (<'\n '>?) (..|@: {row: [email protected]::raw + 1, col: 1};)
rule cell: <open|blocked|given> (<' '>?) (@.col: [email protected]::raw + 1;)
rule open: <'__'> -> 0
rule blocked: <' \.'> -> -1
rule given: (<' '>?) (def given: <INT>;)
($given -> ..|@.givenInput: [email protected]::length+1..$ -> {};)
($given -> @.givenInput($): { row: [email protected], col: [email protected] };)
$given
end setup
templates solve
when <~{row: <[email protected]::length>, col: <[email protected](1)::length>}> do !VOID
when <{ n: <[email protected](last).n>, row: <[email protected](last).row>, col: <[email protected](last).col> }> do [email protected] !
when <?([email protected]($.row; $.col) <~=0|=$.n>)> do !VOID
when <?([email protected]($.row; $.col) <=0>)?([email protected]($.next) <=$.n>)> do !VOID
otherwise
def guess: $;
def back: [email protected]($.row; $.col);
def next: $ -> \(when <{n: <=$back>}> do $.next::raw + 1! otherwise $.next!\);
@hidato.board($.row; $.col): $.n::raw;
0..8 -> { next: $next, n: $guess.n::raw + 1, row: $guess.row::raw + $ ~/ 3 - 1, col: $guess.col::raw + $ mod 3 - 1 } -> #
@hidato.board($.row; $.col): $back;
end solve
@: $ -> setup;
{ next: 1, [email protected](1)... } -> solve !
end hidato
$input -> hidato -> '$... -> '$... -> ' $ -> \(when <=-1> do ' .' ! when <10..> do '$;' ! otherwise ' $;' !\);';
';
' ->!OUT::write
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.