task_url stringlengths 30 116 | task_name stringlengths 2 86 | task_description stringlengths 0 14.4k | language_url stringlengths 2 53 | language_name stringlengths 1 52 | code stringlengths 0 61.9k |
|---|---|---|---|---|---|
http://rosettacode.org/wiki/Solve_a_Hidato_puzzle | Solve a Hidato puzzle | The task is to write a program which solves Hidato (aka Hidoku) puzzles.
The rules are:
You are given a grid with some numbers placed in it. The other squares in the grid will be blank.
The grid is not necessarily rectangular.
The grid may have holes in it.
The grid is always connected.
The number “1” is always ... | #C.23 | C# | using System.Collections;
using System.Collections.Generic;
using static System.Console;
using static System.Math;
using static System.Linq.Enumerable;
public class Solver
{
private static readonly (int dx, int dy)[]
//other puzzle types elided
hidatoMoves = {(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1... |
http://rosettacode.org/wiki/Sokoban | Sokoban | Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred.
Sokoban levels are usually stored as a character array where
space is an empty... | #Julia | Julia | struct BoardState
board::String
csol::String
position::Int
end
function move(s::BoardState, dpos)
buffer = Vector{UInt8}(deepcopy(s.board))
if s.board[s.position] == '@'
buffer[s.position] = ' '
else
buffer[s.position] = '.'
end
newpos = s.position + dpos
if s.board... |
http://rosettacode.org/wiki/Sokoban | Sokoban | Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred.
Sokoban levels are usually stored as a character array where
space is an empty... | #Kotlin | Kotlin | // version 1.2.0
import java.util.LinkedList
class Sokoban(board: List<String>) {
val destBoard: String
val currBoard: String
val nCols = board[0].length
var playerX = 0
var playerY = 0
init {
val destBuf = StringBuilder()
val currBuf = StringBuilder()
for (r in 0 u... |
http://rosettacode.org/wiki/Solve_a_Holy_Knight%27s_tour | Solve a Holy Knight's tour |
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies.
This kind of knight's tour puzzle is similar to Hidato.
The present task is to produce a solution ... | #Lua | Lua |
local p1, p1W = ".xxx.....x.xx....xxxxxxxxxx..x.xx.x..xxxsxxxxxx...xx.x.....xxx..", 8
local p2, p2W = ".....s.x..........x.x.........xxxxx.........xxx.......x..x.x..x..xxxxx...xxxxx..xx.....xx..xxxxx...xxxxx..x..x.x..x.......xxx.........xxxxx.........x.x..........x.x.....", 13
local puzzle, movesCnt, wid = {}, 0, 0
l... |
http://rosettacode.org/wiki/Solve_a_Hopido_puzzle | Solve a Hopido puzzle | Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Pos... | #Wren | Wren | import "/sort" for Sort
import "/fmt" for Fmt
var board = [
".00.00.",
"0000000",
"0000000",
".00000.",
"..000..",
"...0..."
]
var moves = [
[-3, 0], [0, 3], [ 3, 0], [ 0, -3],
[ 2, 2], [2, -2], [-2, 2], [-2, -2]
]
var grid = []
var totalToFill = 0
var countNeighbors = Fn.new { ... |
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
... | #F.23 | F# | let persons = [| ("Joe", 120); ("foo", 31); ("bar", 51) |]
Array.sortInPlaceBy fst persons
printfn "%A" persons |
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Factor | Factor | TUPLE: example-pair name value ;
: sort-by-name ( seq -- seq' ) [ [ name>> ] compare ] sort ; |
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle | Solve the no connection puzzle | You are given a box with eight holes labelled A-to-H, connected by fifteen straight lines in the pattern as shown below:
A B
/│\ /│\
/ │ X │ \
/ │/ \│ \
C───D───E───F
\ │\ /│ /
\ │ X │ /
\│/ \│/
G H
You ar... | #Kotlin | Kotlin | // version 1.2.0
import kotlin.math.abs
// Holes A=0, B=1, …, H=7
// With connections:
const val conn = """
A B
/|\ /|\
/ | X | \
/ |/ \| \
C - D - E - F
\ |\ /| /
\ | X | /
\|/ \|/
G H
"""
val connections = listOf(
0 to 2, 0 to 3, 0 to 4, // A to C, D,... |
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
... | #FreeBASIC | FreeBASIC | ' version 11-03-2016
' compile with: fbc -s console
#Include Once "crt/stdlib.bi" ' needed for qsort subroutine
' Declare Sub qsort (ByVal As Any Ptr, <== point to start of array
' ByVal As size_t, <== size of array
' ByVal As size_t, <== size of array element
' ByVal As... |
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers | Sort a list of object identifiers |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #REXX | REXX | /*REXX program performs a sort of OID (Object IDentifiers ◄── used in Network data).*/
call gen /*generate an array (@.) from the OIDs.*/
call show 'before sort ───► ' /*display the @ array before sorting.*/
say copies('░', 79... |
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
... | #Ksh | Ksh |
#!/bin/ksh
# Sort disjoint sublist
# # Variables:
#
typeset -a arr_Val=( 7 6 5 4 3 2 1 0 )
typeset -a arr_Ind=( 6 1 7 )
integer i
# # Functions:
#
# # Function _insertionSort(array) - Insertion sort of array of integers
#
function _insertionSort {
typeset _arr ; nameref _arr="$1"
typeset _i _j _val ; in... |
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
... | #Lua | Lua | values = { 7, 6, 5, 4, 3, 2, 1, 0 }
indices = { 6, 1, 7 }
i = 1 -- discard duplicates
while i < #indices do
j = i + 1
while j < #indices do
if indices[i] == indices[j] then
table.remove( indices[j] )
end
j = j + 1
end
i = i + 1
end
for i = 1, #indices do
indices[i] = indices[i] +... |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Seed7 | Seed7 | $ include "seed7_05.s7i";
const proc: genSort3 (in type: elemType) is func
begin
global
const proc: doSort3 (in var elemType: x, in var elemType: y, in var elemType: z) is func
local
var array elemType: sorted is 0 times elemType.value;
begin
writeln("BEFORE: x=[" <& x <& "]; y... |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #SenseTalk | SenseTalk | Set x to "lions, tigers and"
Set y to "bears, oh my!"
Set z to "(from the Wizard of Oz)"
log x
log y
log z
set RosettaListAlpha to (x,y,z)
log RosettaListAlpha
sort RosettaListAlpha alphabetically
log RosettaListAlpha
LogSuccess "Alphabetical Sort Successful"
set (x,y,z) to RosettaListAlpha
log x
log y
log z
... |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Sidef | Sidef | func sort_refs(*arr) {
arr.map{ *_ }.sort ~Z arr -> each { *_[1] = _[0] }
}
var x = 77444
var y = -12
var z = 0
sort_refs(\x, \y, \z)
say x
say y
say z |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Ol | Ol |
(import (scheme char))
(define (comp a b)
(let ((la (string-length a))
(lb (string-length b)))
(or
(> la lb)
(and (= la lb) (string-ci<? a b)))))
(print
(sort comp '(
"lorem" "ipsum" "dolor" "sit" "amet" "consectetur"
"adipiscing" "elit" "maecenas" "varius" "sapi... |
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort | Sorting algorithms/Bogosort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Ursala | Ursala | #import std
#import nat
shuffle = @iNX ~&l->r ^jrX/~&l ~&lK8PrC
bogosort = (not ordered nleq)-> shuffle
#cast %nL
example = bogosort <8,50,0,12,47,51> |
http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort | Sorting algorithms/Bubble sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Forth | Forth | defer bubble-test
' > is bubble-test
: bubble { addr cnt -- }
cnt 1 do
addr cnt i - cells bounds do
i 2@ bubble-test if i 2@ swap i 2! then
cell +loop
loop ; |
http://rosettacode.org/wiki/Sorting_algorithms/Gnome_sort | Sorting algorithms/Gnome sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Phix | Phix | with javascript_semantics
function gnomeSort(sequence s)
integer i = 1, j = 2
while i<length(s) do
object si = s[i],
sn = s[i+1]
if si<=sn then
i = j
j += 1
else
s[i] = sn
s[i+1] = si
i -= 1
if i = 0 then... |
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
... | #ooRexx | ooRexx | /* Rexx */
placesList = .array~of( -
"UK London", "US New York" , "US Boston", "US Washington" -
, "UK Washington", "US Birmingham" , "UK Birmingham", "UK Boston" -
)
sortedList = cocktailSort(placesList~allItems())
lists = .array~of(placesList, sortedList)
loop ln = 1 to lists~items()... |
http://rosettacode.org/wiki/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #Elixir | Elixir |
defmodule Sockets do
require Logger
def send_message(port, message) do
{:ok, socket} = :gen_tcp.connect('localhost', port, [])
:gen_tcp.send(socket, message)
end
end
Sockets.send_message(256, "hello socket world")
|
http://rosettacode.org/wiki/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #Emacs_Lisp | Emacs Lisp | (let ((proc (make-network-process :name "my sock"
:host 'local ;; or hostname string
:service 256)))
(process-send-string proc "hello socket world")
(delete-process proc)) |
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin... | #Phix | Phix | constant iterations = 1_000_000,
fmt = """
Wakings over %,d repetitions = %,d
Percentage probability of heads on waking = %f%%
"""
integer heads = 0, wakings = 0
for i=1 to iterations do
integer flip = rand(2) -- 1==heads, 2==tails
wakings += 1 + (flip==2)
heads += (flip==1)
end for
printf(1,fmt,{iterations... |
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin... | #Python | Python | from random import choice
def sleeping_beauty_experiment(repetitions):
"""
Run the Sleeping Beauty Problem experiment `repetitions` times, checking to see
how often we had heads on waking Sleeping Beauty.
"""
gotheadsonwaking = 0
wakenings = 0
for _ in range(repetitions):
coin_resu... |
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence | Smarandache prime-digital sequence | The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime.
For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime.
Task
Show the first 25 SPDS primes.
Show the hundredth SPDS prime.
See also
... | #Go | Go | package main
import (
"fmt"
"math/big"
)
var b = new(big.Int)
func isSPDSPrime(n uint64) bool {
nn := n
for nn > 0 {
r := nn % 10
if r != 2 && r != 3 && r != 5 && r != 7 {
return false
}
nn /= 10
}
b.SetUint64(n)
if b.ProbablyPrime(0) { // 10... |
http://rosettacode.org/wiki/Snake | Snake |
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Snake is a game where the player maneuvers a line which grows i... | #AutoHotkey | AutoHotkey | gosub Init
Gui, +AlwaysOnTop
Gui, font, s12, consolas
Gui, add, Edit, vEditGrid x10 y10 ReadOnly, % grid2Text(oGrid)
Gui, add, Text, vScore x10 y+10 w200 ReadOnly, % "Your Score = " Score
Gui, show,, Snake
GuiControl, Focus, Score
return
;-----------------------------------------
Init:
Width := 100, Height := 30 ; s... |
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.... | #Ada | Ada |
with Ada.Text_IO;
procedure smith is
type Vector is array (natural range <>) of Positive;
empty_vector : constant Vector(1..0):= (others=>1);
function digits_sum (n : Positive) return Positive is
(if n < 10 then n else n mod 10 + digits_sum (n / 10));
function prime_factors (n : Positive; d : Positiv... |
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 ... | #C.2B.2B | C++ |
#include <iostream>
#include <sstream>
#include <iterator>
#include <vector>
//------------------------------------------------------------------------------
using namespace std;
//------------------------------------------------------------------------------
struct node
{
int val;
unsigned char neighbors... |
http://rosettacode.org/wiki/Sokoban | Sokoban | Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred.
Sokoban levels are usually stored as a character array where
space is an empty... | #Nim | Nim | import deques, sets, strutils
type
Sokoban = object
destBoard: string
currBoard: string
nCols: Natural
playerX: Natural
playerY: Natural
Board = tuple[cur, sol: string; x, y: int]
func initSokoban(board: openArray[string]): Sokoban =
result.nCols = board[0].len
for row in 0..board.... |
http://rosettacode.org/wiki/Sokoban | Sokoban | Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred.
Sokoban levels are usually stored as a character array where
space is an empty... | #OCaml | OCaml | type dir = U | D | L | R
type move_t = Move of dir | Push of dir
let letter = function
| Push(U) -> 'U' | Push(D) -> 'D' | Push(L) -> 'L' | Push(R) -> 'R'
| Move(U) -> 'u' | Move(D) -> 'd' | Move(L) -> 'l' | Move(R) -> 'r'
let cols = ref 0
let delta = function U -> -(!cols) | D -> !cols | L -> -1 | R -> 1
l... |
http://rosettacode.org/wiki/Solve_a_Holy_Knight%27s_tour | Solve a Holy Knight's tour |
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies.
This kind of knight's tour puzzle is similar to Hidato.
The present task is to produce a solution ... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | puzzle = " 0 0 0
0 0 0
0 0 0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
1 0 0 0 0 0 0
0 0 0
0 0 0";
puzzle = StringSplit[puzzle, "\n"];
puzzle = StringTake[#, {1, -1, 2}] & /@ puzzle;
pos0 = Join @@ Table[{i, #} & /@ StringPosition[puzzle[[i]], "0"][[All, 1]], {i, Length@puzzle}];
pos1 = Join @@ Table... |
http://rosettacode.org/wiki/Solve_a_Hopido_puzzle | Solve a Hopido puzzle | Hopido puzzles are similar to Hidato. The most important difference is that the only moves allowed are: hop over one tile diagonally; and over two tiles horizontally and vertically. It should be possible to start anywhere in the path, the end point isn't indicated and there are no intermediate clues. Hopido Design Pos... | #zkl | zkl | hi:= // 0==empty cell, X==not a cell
#<<<
" X 0 0 X 0 0 X
0 0 0 0 0 0 0
0 0 0 0 0 0 0
X 0 0 0 0 0 X
X X 0 0 0 X X
X X X 0 X X X";
#<<<
adjacent:=T( T(-3,0),
T(-2,-2), T(-2,2),
T(0,-3), T(0,3),
T(2,-2), T(2,2),
T(3,0) );
puzzle:=Puzzle(hi,adjacent);
puzz... |
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
... | #Fantom | Fantom |
class Pair // create a composite structure
{
Str name
Str value
new make (Str name, Str value)
{
this.name = name
this.value = value
}
override Str toStr ()
{
"(Pair: $name, $value)"
}
}
class Main
{
public static Void main ()
{
// samples
pairs := [Pair("Fantom", "OO"), P... |
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
... | #Fortran | Fortran | PROGRAM EXAMPLE
IMPLICIT NONE
TYPE Pair
CHARACTER(6) :: name
CHARACTER(1) :: value
END TYPE Pair
TYPE(Pair) :: rcc(10), temp
INTEGER :: i, j
rcc(1) = Pair("Black", "0")
rcc(2) = Pair("Brown", "1")
rcc(3) = Pair("Red", "2")
rcc(4) = Pair("Orange", "3")
rcc(5) = Pair("Yellow", "4")
... |
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle | Solve the no connection puzzle | You are given a box with eight holes labelled A-to-H, connected by fifteen straight lines in the pattern as shown below:
A B
/│\ /│\
/ │ X │ \
/ │/ \│ \
C───D───E───F
\ │\ /│ /
\ │ X │ /
\│/ \│/
G H
You ar... | #M2000_Interpreter | M2000 Interpreter |
Module no_connection_puzzle {
\\ Holes
Inventory Connections="A":="CDE","B":="DEF","C":="ADG", "D":="ABCEGH"
Append Connections, "E":="ABDFGH","F":="HEB", "G":="CDE","H":="DEF"
Inventory ToDelete, Solutions
\\ eliminate double connnections
con=each(Connections)
While con {
... |
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle | Solve the no connection puzzle | You are given a box with eight holes labelled A-to-H, connected by fifteen straight lines in the pattern as shown below:
A B
/│\ /│\
/ │ X │ \
/ │/ \│ \
C───D───E───F
\ │\ /│ /
\ │ X │ /
\│/ \│/
G H
You ar... | #m4 | m4 | divert(-1)
define(`abs',`eval(((( $1 ) < 0) * (-( $1 ))) + ((0 <= ( $1 )) * ( $1 )))')
define(`display_solution',
` substr($1,0,1) substr($1,1,1)
/|\ /|\
/ | X | \
/ |/ \| \
substr($1,2,1)`---'substr($1,3,1)`---'substr($1,4,1)`---'substr($1,5,1)
\ |\ /| /
\ | X | /
\|/ \|/
substr($1,6,1) ... |
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
... | #Frink | Frink | a = [5, 2, 4, 1, 6, 7, 9, 3, 8, 0]
sort[a] |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #FunL | FunL | nums = [5, 2, 78, 2, 578, -42]
println( sort(nums) ) // sort in ascending order
println( nums.sortWith((>)) ) // sort in descending order |
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers | Sort a list of object identifiers |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Ring | Ring |
/*
+--------------------------------------------------------------
+ Program Name : SortOIDNumeric.ring
+ Date : 2016-07-14
+ Author : Bert Mariani
+ Purpose : Sort OID List in Numeric Order
+--------------------------------------------------------------
*/
old... |
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers | Sort a list of object identifiers |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Ruby | Ruby | %w[
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11150.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11150.3.4.0
]
.sort_by{|oid| oid.split(".").map(&:to_i)}
.each{|oid| puts oid} |
http://rosettacode.org/wiki/Sort_disjoint_sublist | Sort disjoint sublist |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Maple | Maple | sortDisjoint := proc(values, indices::set)
local vals,inds,i:
vals := sort([seq(values[i], i in indices)]):
inds := sort(convert(indices, Array)):
for i to numelems(vals) do
values(inds[i]) := vals[i]:
od:
end proc:
tst := Array([7,6,5,4,3,2,1,0]):
sortDisjoint(tst,{7,2,8}); |
http://rosettacode.org/wiki/Sort_disjoint_sublist | Sort disjoint sublist |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Values = { 7, 6, 5, 4, 3, 2, 1, 0} ; Indices = { 7, 2, 8 };
Values[[Sort[Indices]]] = Sort[Values[[Indices]]];
Values |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Swift | Swift | func varSort<T: Comparable>(_ x: inout T, _ y: inout T, _ z: inout T) {
let res = [x, y, z].sorted()
x = res[0]
y = res[1]
z = res[2]
}
var x = "lions, tigers, and"
var y = "bears, oh my!"
var z = "(from the \"Wizard of OZ\")"
print("Before:")
print("x = \(x)")
print("y = \(y)")
print("z = \(z)")
print()
... |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Tcl | Tcl |
set x {lions, tigers, and}
set y {bears, oh my!}
set z {(from the "Wizard of OZ")}
lassign [lsort [list $x $y $z]] x y z
puts "x: $x"
puts "y: $y"
puts "z: $z"
set x 77444
set y -12
set z 0
lassign [lsort [list $x $y $z]] x y z
puts "x: $x"
puts "y: $y"
puts "z: $z"
|
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #ooRexx | ooRexx | A=.array~of('The seven deadly sins','Pride','avarice','Wrath','envy','gluttony','sloth','Lust')
say 'Sorted in order of descending length, and in ascending lexicographic order'
say A~sortWith(.DescLengthAscLexical~new)~makeString
::class DescLengthAscLexical mixinclass Comparator
::method compare
use strict arg left,... |
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
... | #OxygenBasic | OxygenBasic |
uses generics 'containing sort macros
uses console
string sdata={"CC","Aa","aAa","bb","bbB","b","B","c","A"}
'
int count = countof sdata
'
macro filter(f,a)
=================
'sdata[a]
f=1 'allow all
end macro
'
macro compare(f,a,b)
====================
int la=len sdata[a]
int lb=len sdata[b]
if la<lb
f... |
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort | Sorting algorithms/Bogosort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #VBA | VBA | Private Function Knuth(a As Variant) As Variant
Dim t As Variant, i As Integer
If Not IsMissing(a) Then
For i = UBound(a) To LBound(a) + 1 Step -1
j = Int((UBound(a) - LBound(a) + 1) * Rnd + LBound(a))
t = a(i)
a(i) = a(j)
a(j) = t
Next i
End I... |
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
... | #Fortran | Fortran | SUBROUTINE Bubble_Sort(a)
REAL, INTENT(in out), DIMENSION(:) :: a
REAL :: temp
INTEGER :: i, j
LOGICAL :: swapped
DO j = SIZE(a)-1, 1, -1
swapped = .FALSE.
DO i = 1, j
IF (a(i) > a(i+1)) THEN
temp = a(i)
a(i) = a(i+1)
a(i+1) = temp
swapped = .TRUE.
END IF
... |
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
... | #PHP | PHP | function gnomeSort($arr){
$i = 1;
$j = 2;
while($i < count($arr)){
if ($arr[$i-1] <= $arr[$i]){
$i = $j;
$j++;
}else{
list($arr[$i],$arr[$i-1]) = array($arr[$i-1],$arr[$i]);
$i--;
if($i == 0){
$i = $j;
$j++;
}
}
}
return $arr;
}
$arr = array(3,1,6,2,9,4,7,8,5);
echo implode(',',gnom... |
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
... | #Oz | Oz | declare
proc {CocktailSort Arr}
proc {Swap I J}
Arr.J := (Arr.I := Arr.J) %% assignment returns the old value
end
IsSorted = {NewCell false}
Up = {List.number {Array.low Arr} {Array.high Arr}-1 1}
Down = {Reverse Up}
in
for until:@IsSorted break:Break do
for Range in [Up Down]... |
http://rosettacode.org/wiki/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #Erlang | Erlang | -module(socket).
-export([start/0]).
start() ->
{ok, Sock} = gen_tcp:connect("localhost", 256,
[binary, {packet, 0}]),
ok = gen_tcp:send(Sock, "hello socket world"),
ok = gen_tcp:close(Sock).
|
http://rosettacode.org/wiki/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #Factor | Factor | "localhost" 256 <inet> utf8 [ "hello socket world" print ] with-client |
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin... | #Quackery | Quackery | [ $ "bigrat.qky" loadfile ] now!
[ say "Number of trials: "
dup echo cr
0 ( heads count )
0 ( sleeps count )
rot times
[ 1+
2 random if
[ 1+ dip 1+ ] ]
say "Data: heads count: "
over echo cr
say " sleeps count: "
dup echo cr
say "Credence of heads:... |
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin... | #R | R | beautyProblem <- function(n)
{
wakeCount <- headCount <- 0
for(i in seq_len(n))
{
wakeCount <- wakeCount + 1
if(sample(c("H", "T"), 1) == "H") headCount <- headCount + 1 else wakeCount <- wakeCount + 1
}
headCount/wakeCount
}
print(beautyProblem(10000000)) |
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin... | #Raku | Raku | sub sleeping-beauty ($trials) {
my $gotheadsonwaking = 0;
my $wakenings = 0;
^$trials .map: {
given <Heads Tails>.roll {
++$wakenings;
when 'Heads' { ++$gotheadsonwaking }
when 'Tails' { ++$wakenings }
}
}
say "Wakenings over $trials experiments: "... |
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence | Smarandache prime-digital sequence | The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime.
For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime.
Task
Show the first 25 SPDS primes.
Show the hundredth SPDS prime.
See also
... | #Haskell | Haskell | {-# LANGUAGE NumericUnderscores #-}
import Control.Monad (guard)
import Math.NumberTheory.Primes.Testing (isPrime)
import Data.List.Split (chunksOf)
import Data.List (intercalate)
import Text.Printf (printf)
smarandache :: [Integer]
smarandache = [2,3,5,7] <> s [2,3,5,7] >>= \x -> guard (isPrime x) >> [x]
where s xs... |
http://rosettacode.org/wiki/Snake | Snake |
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Snake is a game where the player maneuvers a line which grows i... | #BASIC | BASIC |
REM Snake
#define EXTCHAR Chr(255)
Dim Shared As Integer puntos, contar, longitud, posX, posY, oldhi = 0
Dim Shared As Integer x(500), y(500)
For contar = 1 To 500
x(contar) = 0 : y(contar) = 0
Next contar
Dim Shared As Byte fruitX, fruitY, convida
Dim Shared As Single delay
Dim Shared As String direccion, us... |
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.... | #ALGOL_68 | ALGOL 68 | # sieve of Eratosthene: sets s[i] to TRUE if i is prime, FALSE otherwise #
PROC sieve = ( REF[]BOOL s )VOID:
BEGIN
# start with everything flagged as prime #
FOR i TO UPB s DO s[ i ] := TRUE OD;
# sieve out the non-primes ... |
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 ... | #Curry | Curry | import CLPFD
import Constraint (andC, anyC)
import Findall (unpack)
import Integer (abs)
hidato :: [[Int]] -> Success
hidato path =
test path inner
& domain inner 1 40
& allDifferent inner
& andFD [x `near` y | x <- cells, y <- cells]
& labeling [] (concat path)
where
andFD = solve . foldr1 (#/\#)... |
http://rosettacode.org/wiki/Sokoban | Sokoban | Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred.
Sokoban levels are usually stored as a character array where
space is an empty... | #Perl | Perl | #!perl
use strict;
use warnings qw(FATAL all);
my @initial = split /\n/, <<'';
#############
# # #
# $$$$$$$ @#
#....... #
#############
#######
# #
# #
#. # #
#. $$ #
#.$$ #
#.# @#
#######
=for
space is an empty square
# is a wall
@ is the player
$ is a box
. is a goal
+ is the player on a g... |
http://rosettacode.org/wiki/Solve_a_Holy_Knight%27s_tour | Solve a Holy Knight's tour |
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies.
This kind of knight's tour puzzle is similar to Hidato.
The present task is to produce a solution ... | #Nim | Nim | import sequtils, strformat
const Moves = [[-1, -2], [1, -2], [-2, -1], [2, -1], [-2, 1], [2, 1], [-1, 2], [1, 2]]
proc solve(pz: var seq[seq[int]]; sx, sy, idx, count: Natural): bool =
if idx > count: return true
var x, y: int
for move in Moves:
x = sx + move[0]
y = sy + move[1]
if x in 0..pz.... |
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
... | #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Type Pair
As String name, value
Declare Constructor(name_ As String, value_ As String)
Declare Operator Cast() As String
End Type
Constructor Pair(name_ As String, value_ As String)
name = name_
value = value_
End Constructor
Operator Pair.Cast() As String
Return "[" + name + ", " +... |
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle | Solve the no connection puzzle | You are given a box with eight holes labelled A-to-H, connected by fifteen straight lines in the pattern as shown below:
A B
/│\ /│\
/ │ X │ \
/ │/ \│ \
C───D───E───F
\ │\ /│ /
\ │ X │ /
\│/ \│/
G H
You ar... | #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | sol = Fold[
Select[#,
Function[perm, Abs[perm[[#2[[1]]]] - perm[[#2[[2]]]]] > 1]] &,
Permutations[
Range[8]], {{1, 3}, {1, 4}, {1, 5}, {2, 4}, {2, 5}, {2, 6}, {3,
4}, {3, 7}, {4, 5}, {4, 7}, {4, 8}, {5, 6}, {5, 7}, {5, 8}, {6,
8}}][[1]];
Print[StringForm[
" `` ``\n /|\\ /|\\... |
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle | Solve the no connection puzzle | You are given a box with eight holes labelled A-to-H, connected by fifteen straight lines in the pattern as shown below:
A B
/│\ /│\
/ │ X │ \
/ │/ \│ \
C───D───E───F
\ │\ /│ /
\ │ X │ /
\│/ \│/
G H
You ar... | #Nim | Nim | import strformat
const Connections = [(1, 3), (1, 4), (1, 5), # A to C, D, E
(2, 4), (2, 5), (2, 6), # B to D, E, F
(7, 3), (7, 4), (7, 5), # G to C, D, E
(8, 4), (8, 5), (8, 6), # H to D, E, F
(3, 4), (4, 5), (5, 6)] # C-D, D-E,... |
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
... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | Public Sub Main()
Dim iArray As Integer[] = [8, 2, 5, 9, 1, 3, 6, 7, 4]
Dim iTemp As Integer
Dim sOutput As String
For Each iTemp In iArray.Sort()
sOutput &= iTemp & ", "
Next
Print Left(sOutput, -2)
End |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Gambas | Gambas | Public Sub Main()
Dim iArray As Integer[] = [8, 2, 5, 9, 1, 3, 6, 7, 4]
Dim iTemp As Integer
Dim sOutput As String
For Each iTemp In iArray.Sort()
sOutput &= iTemp & ", "
Next
Print Left(sOutput, -2)
End |
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers | Sort a list of object identifiers |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Rust | Rust | fn split(s: &str) -> impl Iterator<Item = u64> + '_ {
s.split('.').map(|x| x.parse().unwrap())
}
fn main() {
let mut oids = vec![
"1.3.6.1.4.1.11.2.17.19.3.4.0.10",
"1.3.6.1.4.1.11.2.17.5.2.0.79",
"1.3.6.1.4.1.11.2.17.19.3.4.0.4",
"1.3.6.1.4.1.11150.3.4.0.1",
"1.3.6.1.4... |
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers | Sort a list of object identifiers |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Sather | Sather | class MAIN is
oid_lt (a, b: STR): BOOL is
as ::= a.cursor.split('.');
bs ::= b.cursor.split('.');
loop
na ::= #INT(as.elt!);
nb ::= #INT(bs.elt!);
if na /= nb then return na < nb; end;
end;
return as.size < bs.size;
end;
main is
sorter: ARR_SORT_... |
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
... | #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method sortDisjoint(oldList, indices) public static
newList = oldList.space()
if indices.words() > 1 then do -- only do work if we n... |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Swap(Of T)(ByRef a As T, ByRef b As T)
Dim c = a
a = b
b = c
End Sub
Sub Sort(Of T As IComparable(Of T))(ByRef a As T, ByRef b As T, ByRef c As T)
If a.CompareTo(b) > 0 Then
Swap(a, b)
End If
If a.CompareTo(c) > 0 Then
... |
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
... | #Oz | Oz | declare
fun {LexicographicLessThan Xs Ys}
for
X in {Map Xs Char.toLower}
Y in {Map Ys Char.toLower}
return:Return
default:{Length Xs}<{Length Ys}
do
if X < Y then {Return true} end
end
end
fun {LessThan Xs Ys}
{Length Xs} > {Length Ys}
orelse
... |
http://rosettacode.org/wiki/Sorting_algorithms/Bogosort | Sorting algorithms/Bogosort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #VBScript | VBScript | sub swap( byref a, byref b )
dim tmp
tmp = a
a = b
b = tmp
end sub
'knuth shuffle (I think)
function shuffle( a )
dim i
dim r
randomize timer
for i = lbound( a ) to ubound( a )
r = int( rnd * ( ubound( a ) + 1 ) )
if r <> i then
swap a(i), a(r)
end if
next
shuffle = a
end function
function inOr... |
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
... | #FreeBASIC | FreeBASIC | ' version 21-10-2016
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
Sub bubblesort(bs() As Long)
' sort from lower bound to the highter bound
' array's can have subscript range from -2147483648 to +2147483647
Dim As Long lb = LBound(bs)
Dim As Long ub ... |
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
... | #PicoLisp | PicoLisp | (de gnomeSort (Lst)
(let J (cdr Lst)
(for (I Lst (cdr I))
(if (>= (cadr I) (car I))
(setq I J J (cdr J))
(xchg I (cdr I))
(if (== I Lst)
(setq I J J (cdr J))
(setq I (prior I Lst)) ) ) ) )
Lst ) |
http://rosettacode.org/wiki/Sorting_algorithms/Cocktail_sort | Sorting algorithms/Cocktail sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #PARI.2FGP | PARI/GP | cocktailSort(v)={
while(1,
my(done=1);
for(i=2,#v,
if(v[i-1]>v[i],
my(t=v[i-1]);
v[i-1]=v[i];
v[i]=t;
done=0
)
);
if(done, return(v));
done=1;
forstep(i=#v,2,-1,
if(v[i-1]>v[i],
my(t=v[i-1]);
v[i-1]=v[i];
v[i]=t;
... |
http://rosettacode.org/wiki/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #Fantom | Fantom |
using inet
class Socket
{
public static Void main ()
{
sock := TcpSocket()
sock.connect(IpAddr("localhost"), 256)
sock.out.printLine("hello socket world")
sock.out.flush
sock.close
}
}
|
http://rosettacode.org/wiki/Sockets | Sockets | For this exercise a program is open a socket to localhost on port 256 and send the message "hello socket world" before closing the socket.
Catching any exceptions or errors is not required.
| #Forth | Forth | include unix/socket.fs
s" localhost" 256 open-socket
dup s" hello socket world" rot write-socket
close-socket |
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin... | #Red | Red | Red ["Sleeping Beauty problem"]
experiments: 1'000'000
heads: awakenings: 0
loop experiments [
awakenings: awakenings + 1
either 1 = random 2 [heads: heads + 1] [awakenings: awakenings + 1]
]
print ["Awakenings over" experiments "experiments:" awakenings]
print ["Probability of heads on waking:" heads / awake... |
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin... | #REXX | REXX | /*REXX pgm uses a Monte Carlo estimate for the results for the Sleeping Beauty problem. */
parse arg n seed . /*obtain optional arguments from the CL*/
if n=='' | n=="," then n= 1000000 /*Not specified? Then use the default.*/
if datatype(seed, 'W') then call random ,,seed... |
http://rosettacode.org/wiki/Sleeping_Beauty_problem | Sleeping Beauty problem | Background on the task
In decision theory, The Sleeping Beauty Problem
is a problem invented by Arnold Zoboff and first publicized on Usenet. The experimental
subject, named Sleeping Beauty, agrees to an experiment as follows:
Sleeping Beauty volunteers to be put into a deep sleep on a Sunday. There is then a fair coin... | #Ruby | Ruby | def sleeping_beauty_experiment(n)
coin = [:heads, :tails]
gotheadsonwaking = 0
wakenings = 0
n.times do
wakenings += 1
coin.sample == :heads ? gotheadsonwaking += 1 : wakenings += 1
end
puts "Wakenings over #{n} experiments: #{wakenings}"
gotheadsonwaking / wakenings.to_f
end
puts "Results of ex... |
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence | Smarandache prime-digital sequence | The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime.
For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime.
Task
Show the first 25 SPDS primes.
Show the hundredth SPDS prime.
See also
... | #J | J | Filter=: (#~`)(`:6)
NB. given a prime y, smarandache y is 1 iff it's a smarandache prime
smarandache=: [: -. (0 e. (p:i.4) e.~ 10 #.inv ])&>
SP=: smarandache Filter p: i. 1000000
SP {~ i. 25 NB. first 25 Smarandache primes
2 3 5 7 23 37 53 73 223 227 233 257 277 337 353 373 523 557 577 727 733 757 7... |
http://rosettacode.org/wiki/Smarandache_prime-digital_sequence | Smarandache prime-digital sequence | The Smarandache prime-digital sequence (SPDS for brevity) is the sequence of primes whose digits are themselves prime.
For example 257 is an element of this sequence because it is prime itself and its digits: 2, 5 and 7 are also prime.
Task
Show the first 25 SPDS primes.
Show the hundredth SPDS prime.
See also
... | #Java | Java |
public class SmarandachePrimeDigitalSequence {
public static void main(String[] args) {
long s = getNextSmarandache(7);
System.out.printf("First 25 Smarandache prime-digital sequence numbers:%n2 3 5 7 ");
for ( int count = 1 ; count <= 21 ; s = getNextSmarandache(s) ) {
if ( ... |
http://rosettacode.org/wiki/Snake | Snake |
This page uses content from Wikipedia. The original article was at Snake_(video_game). The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Snake is a game where the player maneuvers a line which grows i... | #C | C | // Snake
// The problem with implementing this task in C is, the language standard
// does not cover some details essential for interactive games:
// a nonblocking keyboard input, a positional console output,
// a and millisecond-precision timer: these things are all system-dependent.
// Therefore the program is sp... |
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.... | #Arturo | Arturo | digitSum: function [v][
n: new v
result: new 0
while [n > 0][
'result + n % 10
'n / 10
]
return result
]
smith?: function [z][
return
(prime? z) ? -> false
-> (digitSum z) = sum map factors.prime z 'num [digitSum num]
]
found: 0
loop 1..10000 'x [
... |
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 ... | #D | D | import std.stdio, std.array, std.conv, std.algorithm, std.string;
int[][] board;
int[] given, start;
void setup(string s) {
auto lines = s.splitLines;
auto cols = lines[0].split.length;
auto rows = lines.length;
given.length = 0;
board = new int[][](rows + 2, cols + 2);
foreach (row; board... |
http://rosettacode.org/wiki/Sokoban | Sokoban | Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred.
Sokoban levels are usually stored as a character array where
space is an empty... | #Phix | Phix | -- demo\rosetta\Sokoban.exw
integer w, h -- (set from parsing the input grid)
sequence moves -- "", as +/-w and +/-1 (udlr)
string live -- "", Y if box can go there
function reachable(sequence pushes, string level)
integer p = find_any("@+",level)
string ok = repeat('N',length(level))
ok[p] ... |
http://rosettacode.org/wiki/Sokoban | Sokoban | Demonstrate how to find a solution to a given Sokoban level. For the purpose of this task (formally, a PSPACE-complete problem) any method may be used. However a move-optimal or push-optimal (or any other -optimal) solutions is preferred.
Sokoban levels are usually stored as a character array where
space is an empty... | #PicoLisp | PicoLisp | (load "@lib/simul.l")
# Display board
(de display ()
(disp *Board NIL
'((This)
(pack
(if2 (== This *Pos) (memq This *Goals)
"+" # Player on goal
"@" # Player elsewhere
(if (: val) "*" ".") # On gloal
... |
http://rosettacode.org/wiki/Solve_a_Holy_Knight%27s_tour | Solve a Holy Knight's tour |
Chess coaches have been known to inflict a kind of torture on beginners by taking a chess board, placing pennies on some squares and requiring that a Knight's tour be constructed that avoids the squares with pennies.
This kind of knight's tour puzzle is similar to Hidato.
The present task is to produce a solution ... | #Perl | Perl | package KT_Locations;
# A sequence of locations on a 2-D board whose order might or might not
# matter. Suitable for representing a partial tour, a complete tour, or the
# required locations to visit.
use strict;
use overload '""' => "as_string";
use English;
# 'locations' must be a reference to an array of 2-element a... |
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
... | #Frink | Frink | class Pair
{
var name
var value
new[name is string, value is string] :=
{
this.name = name
this.value = value
}
}
a = [new Pair["one", "1"], new Pair["two", "2"], new Pair["three", "3"]]
sort[a, {|a,b| lexicalCompare[a.name, b.name]}]
|
http://rosettacode.org/wiki/Sort_an_array_of_composite_structures | Sort an array of composite structures |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #F.C5.8Drmul.C3.A6 | Fōrmulæ | package main
import (
"fmt"
"sort"
)
type pair struct {
name, value string
}
type csArray []pair
// three methods satisfy sort.Interface
func (a csArray) Less(i, j int) bool { return a[i].name < a[j].name }
func (a csArray) Len() int { return len(a) }
func (a csArray) Swap(i, j int) { a... |
http://rosettacode.org/wiki/Solve_the_no_connection_puzzle | Solve the no connection puzzle | You are given a box with eight holes labelled A-to-H, connected by fifteen straight lines in the pattern as shown below:
A B
/│\ /│\
/ │ X │ \
/ │/ \│ \
C───D───E───F
\ │\ /│ /
\ │ X │ /
\│/ \│/
G H
You ar... | #Perl | Perl | #!/usr/bin/perl
use strict;
use warnings;
my $gap = qr/.{3}/s;
find( <<terminator );
-AB-
CDEF
-GH-
terminator
sub find
{
my $p = shift;
$p =~ /(\d)$gap.{0,2}(\d)(??{abs $1 - $2 <= 1 ? '' : '(*F)'})/ ||
$p =~ /^.*\n.*(\d)(\d)(??{abs $1 - $2 <= 1 ? '' : '(*F)'})/ and return;
if( $p =~ /[A-H]/ )
{... |
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
... | #GAP | GAP | a := [ 8, 2, 5, 9, 1, 3, 6, 7, 4 ];
# Make a copy (with "b := a;", b and a would point to the same list)
b := ShallowCopy(a);
# Sort in place
Sort(a);
a;
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
# Sort without changing the argument
SortedList(b);
# [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
b;
# [ 8, 2, 5, 9, 1, 3, 6, 7, 4 ] |
http://rosettacode.org/wiki/Sort_an_integer_array | Sort an integer array |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Go | Go | package main
import "fmt"
import "sort"
func main() {
nums := []int {2, 4, 3, 1, 2}
sort.Ints(nums)
fmt.Println(nums)
} |
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers | Sort a list of object identifiers |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Sidef | Sidef | func sort_OIDs(ids) {
ids.sort_by { |id|
id.split('.').map { Num(_) }
}
}
var OIDs = %w(
1.3.6.1.4.1.11.2.17.19.3.4.0.10
1.3.6.1.4.1.11.2.17.5.2.0.79
1.3.6.1.4.1.11.2.17.19.3.4.0.4
1.3.6.1.4.1.11150.3.4.0.1
1.3.6.1.4.1.11.2.17.19.3.4.0.1
1.3.6.1.4.1.11150.3.4.0
)
sort_OIDs(OI... |
http://rosettacode.org/wiki/Sort_a_list_of_object_identifiers | Sort a list of object identifiers |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Swift | Swift | import Foundation
public struct OID {
public var val: String
public init(_ val: String) {
self.val = val
}
}
extension OID: CustomStringConvertible {
public var description: String {
return val
}
}
extension OID: Comparable {
public static func < (lhs: OID, rhs: OID) -> Bool {
let split1... |
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
... | #Nial | Nial |
values := [7, 6, 5, 4, 3, 2, 1, 0]
indices := sortup [6, 1, 7]
values#indices := sortup values#indices
7 0 5 4 3 2 1 6
|
http://rosettacode.org/wiki/Sort_disjoint_sublist | Sort disjoint sublist |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Nim | Nim | import algorithm
proc sortDisjoinSublist[T](data: var seq[T], indices: seq[int]) =
var indices = indices
sort indices, cmp[T]
var values: seq[T] = @[]
for i in indices: values.add data[i]
sort values, cmp[T]
for j, i in indices: data[i] = values[j]
var d = @[7, 6, 5, 4, 3, 2, 1, 0]
sortDisjoinSublis... |
http://rosettacode.org/wiki/Sort_three_variables | Sort three variables |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Wren | Wren | import "/sort" for Sort
import "/fmt" for Fmt
var sort3 = Fn.new { |x, y, z|
var a = [x, y, z]
Sort.insertion(a)
x = a[0]
y = a[1]
z = a[2]
Fmt.print(" x = $s\n y = $s\n z = $s", x, y, z)
}
System.print("After sorting strings:")
var x = "lions, tigers, and"
var y = "bears, oh my!"
var z =... |
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
... | #PARI.2FGP | PARI/GP | cmp(a,b)=if(#a<#b,1,if(#a>#b,-1,lex(a,b)));
vecsort(v,cmp) |
http://rosettacode.org/wiki/Sort_using_a_custom_comparator | Sort using a custom comparator |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
... | #Pascal | Pascal | use feature 'say';
@strings = qw/Here are some sample strings to be sorted/;
# with a subroutine:
sub mycmp { length $b <=> length $a || lc $a cmp lc $b }
say join ' ', sort mycmp @strings;
# inline:
say join ' ', sort {length $b <=> length $a || lc $a cmp lc $b} @strings
# for large inputs, can be faster with ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.