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/Pancake_sort | Sorting algorithms/Pancake 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
Task
Sort an array of integers (of any convenient size) into ascending order using Pancake sorting.
In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so:
Before: 6 7 8 9 2 5 3 4 1
After: 9 8 7 6 2 5 3 4 1
Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it must be the same end for the entire solution. (The end flipped can't be arbitrarily changed.)
Show both the initial, unsorted list and the final sorted list.
(Intermediate steps during sorting are optional.)
Optimizations are optional (but recommended).
Related tasks
Number reversal game
Topswops
Also see
Wikipedia article: pancake sorting.
| #11l | 11l | V tutor = 1B
F pancakesort(&data)
I data.len <= 1
R
I :tutor
print()
L(size) (data.len .< 1).step(-1)
V maxindex = max(0 .< size, key' x -> @data[x])
I maxindex + 1 != size
I maxindex != 0
I :tutor
print(‘With: #. doflip #.’.format(data.map(x -> String(x)).join(‘ ’), maxindex + 1))
data.reverse_range(0 .< maxindex + 1)
I :tutor
print(‘With: #. doflip #.’.format(data.map(x -> String(x)).join(‘ ’), size))
data.reverse_range(0 .< size)
I :tutor
print()
V data = ‘6 7 2 1 8 9 5 3 4’.split(‘ ’)
print(‘Original List: ’data.join(‘ ’))
pancakesort(&data)
print(‘Pancake Sorted List: ’data.join(‘ ’)) |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lingo | Lingo | str = "Hello " & QUOTE & "world!" & QUOTE
put str
-- "Hello "world!"" |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Lua | Lua | Markup :
() Sequence
{} List
" String
\ Escape for following character
(* *) Comment block
base^^number`s
` Context
[[]] Indexed reference
Within expression:
\ At end of line: Continue on next line, skipping white space |
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort | Sorting algorithms/Stooge 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 Stooge sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Show the Stooge Sort for an array of integers.
The Stooge Sort algorithm is as follows:
algorithm stoogesort(array L, i = 0, j = length(L)-1)
if L[j] < L[i] then
L[i] ↔ L[j]
if j - i > 1 then
t := (j - i + 1)/3
stoogesort(L, i , j-t)
stoogesort(L, i+t, j )
stoogesort(L, i , j-t)
return L
| #Eiffel | Eiffel |
class
STOOGE_SORT
feature
stoogesort (ar: ARRAY[INTEGER]; i,j: INTEGER)
-- Sorted array in ascending order.
require
ar_not_empty: ar.count >= 0
i_in_range: i>=1
j_in_range: j <= ar.count
boundary_set: i<=j
local
t: REAL_64
third: INTEGER
swap: INTEGER
do
if ar[j]< ar[i] then
swap:= ar[i]
ar[i]:=ar[j]
ar[j]:= swap
end
if j-i >1 then
t:= (j-i+1)/3
third:= t.floor
stoogesort(ar, i, j-third)
stoogesort(ar, i+third, j)
stoogesort(ar, i, j-third)
end
end
end
|
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort | Sorting algorithms/Sleep 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
In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time.
Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required.
Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
| #F.23 | F# |
let sleepSort (values: seq<int>) =
values
|> Seq.map (fun x -> async {
do! Async.Sleep x
Console.WriteLine x
})
|> Async.Parallel
|> Async.Ignore
|> Async.RunSynchronously
|
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort | Sorting algorithms/Sleep 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
In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time.
Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required.
Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
| #Factor | Factor |
USING: threads calendar concurrency.combinators ;
: sleep-sort ( seq -- ) [ dup seconds sleep . ] parallel-each ;
|
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort | Sorting algorithms/Selection 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
Task
Sort an array (or list) of elements using the Selection sort algorithm.
It works as follows:
First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted.
Its asymptotic complexity is O(n2) making it inefficient on large arrays.
Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM.
No other sorting algorithm has less data movement.
References
Rosetta Code: O (complexity).
Wikipedia: Selection sort.
Wikipedia: [Big O notation].
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program selectionSort.s */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSortOk: .asciz "Table sorted.\n"
szMessSortNok: .asciz "Table not sorted !!!!!.\n"
sMessResult: .ascii "Value : "
sMessValeur: .fill 11, 1, ' ' @ size => 11
szCarriageReturn: .asciz "\n"
.align 4
iGraine: .int 123456
.equ NBELEMENTS, 10
#TableNumber: .int 1,3,6,2,5,9,10,8,4,7
TableNumber: .int 10,9,8,7,6,5,4,3,2,1
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
1:
ldr r0,iAdrTableNumber @ address number table
mov r1,#0
mov r2,#NBELEMENTS @ number of élements
bl selectionSort
ldr r0,iAdrTableNumber @ address number table
bl displayTable
ldr r0,iAdrTableNumber @ address number table
mov r1,#NBELEMENTS @ number of élements
bl isSorted @ control sort
cmp r0,#1 @ sorted ?
beq 2f
ldr r0,iAdrszMessSortNok @ no !! error sort
bl affichageMess
b 100f
2: @ yes
ldr r0,iAdrszMessSortOk
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrTableNumber: .int TableNumber
iAdrszMessSortOk: .int szMessSortOk
iAdrszMessSortNok: .int szMessSortNok
/******************************************************************/
/* control sorted table */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the number of elements > 0 */
/* r0 return 0 if not sorted 1 if sorted */
isSorted:
push {r2-r4,lr} @ save registers
mov r2,#0
ldr r4,[r0,r2,lsl #2]
1:
add r2,#1
cmp r2,r1
movge r0,#1
bge 100f
ldr r3,[r0,r2, lsl #2]
cmp r3,r4
movlt r0,#0
blt 100f
mov r4,r3
b 1b
100:
pop {r2-r4,lr}
bx lr @ return
/******************************************************************/
/* selection sort */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the first element */
/* r2 contains the number of element */
selectionSort:
push {r1-r7,lr} @ save registers
mov r3,r1 @ start index i
sub r7,r2,#1 @ compute n - 1
1: @ start loop
mov r4,r3
add r5,r3,#1 @ init index 2
2:
ldr r1,[r0,r4,lsl #2] @ load value A[mini]
ldr r6,[r0,r5,lsl #2] @ load value A[j]
cmp r6,r1 @ compare value
movlt r4,r5 @ j -> mini
add r5,#1 @ increment index j
cmp r5,r2 @ end ?
blt 2b @ no -> loop
cmp r4,r3 @ mini <> j ?
beq 3f @ no
ldr r1,[r0,r4,lsl #2] @ yes swap A[i] A[mini]
ldr r6,[r0,r3,lsl #2]
str r1,[r0,r3,lsl #2]
str r6,[r0,r4,lsl #2]
3:
add r3,#1 @ increment i
cmp r3,r7 @ end ?
blt 1b @ no -> loop
100:
pop {r1-r7,lr}
bx lr @ return
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* r0 contains the address of table */
displayTable:
push {r0-r3,lr} @ save registers
mov r2,r0 @ table address
mov r3,#0
1: @ loop display table
ldr r0,[r2,r3,lsl #2]
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function
ldr r0,iAdrsMessResult
bl affichageMess @ display message
add r3,#1
cmp r3,#NBELEMENTS - 1
ble 1b
ldr r0,iAdrszCarriageReturn
bl affichageMess
100:
pop {r0-r3,lr}
bx lr
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal unsigned */
/******************************************************************/
/* r0 contains value and r1 address area */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ else previous position
bne 1b @ and loop
@ and move digit from left of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4]
add r2,#1
add r4,#1
cmp r2,#LGZONECAL
ble 2b
@ and move spaces in end on area
mov r0,r4 @ result length
mov r1,#' ' @ space
3:
strb r1,[r3,r4] @ store space in area
add r4,#1 @ next position
cmp r4,#LGZONECAL
ble 3b @ loop if r4 <= area size
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
//mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3
//movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
|
http://rosettacode.org/wiki/Soundex | Soundex | Soundex is an algorithm for creating indices for words based on their pronunciation.
Task
The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling (from the soundex Wikipedia article).
Caution
There is a major issue in many of the implementations concerning the separation of two consonants that have the same soundex code! According to the official Rules [[1]]. So check for instance if Ashcraft is coded to A-261.
If a vowel (A, E, I, O, U) separates two consonants that have the same soundex code, the consonant to the right of the vowel is coded. Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored (see "Side-by-Side" rule above), 2 for the K). Since the vowel "A" separates the Z and K, the K is coded.
If "H" or "W" separate two consonants that have the same soundex code, the consonant to the right of the vowel is not coded. Example: Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 for the F). It is not coded A-226.
| #BQN | BQN | ToUpper ← -⟜(32×1="a{"⊸⍋)
Split ← ((⊢-˜+`׬)∘=⊔⊢)
replace ← ⟨
"AEIOUYHW"
"BFPV"
"CGJKQSXZ"
"DT"
"L"
"MN"
"R"
⟩
Soundex ← ⊑∾{'0'+»⟜0‿0‿0⊑¨0⊸≠⊸/(0≠⊑)⊸↓⊑¨(¯1+·+`1»≠⟜«)⊸⊔∾/¨<˘⍉>replace∊˜¨<ToUpper 𝕩}
names ← ' ' Split "Lloyd Woolcock Donnell Baragwanath Williams Ashcroft Euler Ellery Gauss Ghosh Hilbert Heilbronn Knuth Kant Ladd Lukasiewicz Lissajous"
vals ← ' ' Split "L300 W422 D540 B625 W452 A226 E460 E460 G200 G200 H416 H416 K530 K530 L300 L222 L222"
•Show >(⊢ ⋈ Soundex)¨names
•Show vals≡Soundex¨names |
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort | Sorting algorithms/Shell 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
Task
Sort an array of elements using the Shell sort algorithm, a diminishing increment sort.
The Shell sort (also known as Shellsort or Shell's method) is named after its inventor, Donald Shell, who published the algorithm in 1959.
Shell sort is a sequence of interleaved insertion sorts based on an increment sequence.
The increment size is reduced after each pass until the increment size is 1.
With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case".
Any sequence will sort the data as long as it ends in 1, but some work better than others.
Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice.
[1]
Other good sequences are found at the On-Line Encyclopedia of Integer Sequences.
| #C.2B.2B | C++ |
#include <time.h>
#include <iostream>
//--------------------------------------------------------------------------------------------------
using namespace std;
//--------------------------------------------------------------------------------------------------
const int MAX = 126;
class shell
{
public:
shell()
{ _gap[0] = 1750; _gap[1] = 701; _gap[2] = 301; _gap[3] = 132; _gap[4] = 57; _gap[5] = 23; _gap[6] = 10; _gap[7] = 4; _gap[8] = 1; }
void sort( int* a, int count )
{
_cnt = count;
for( int x = 0; x < 9; x++ )
if( count > _gap[x] )
{ _idx = x; break; }
sortIt( a );
}
private:
void sortIt( int* arr )
{
bool sorted = false;
while( true )
{
sorted = true;
int st = 0;
for( int x = _gap[_idx]; x < _cnt; x += _gap[_idx] )
{
if( arr[st] > arr[x] )
{ swap( arr[st], arr[x] ); sorted = false; }
st = x;
}
if( ++_idx >= 8 ) _idx = 8;
if( sorted && _idx == 8 ) break;
}
}
void swap( int& a, int& b ) { int t = a; a = b; b = t; }
int _gap[9], _idx, _cnt;
};
//--------------------------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
srand( static_cast<unsigned int>( time( NULL ) ) ); int arr[MAX];
for( int x = 0; x < MAX; x++ )
arr[x] = rand() % MAX - rand() % MAX;
cout << " Before: \n=========\n";
for( int x = 0; x < 7; x++ )
{
for( int a = 0; a < 18; a++ )
{ cout << arr[x * 18 + a] << " "; }
cout << endl;
}
cout << endl; shell s; s.sort( arr, MAX );
cout << " After: \n========\n";
for( int x = 0; x < 7; x++ )
{
for( int a = 0; a < 18; a++ )
{ cout << arr[x * 18 + a] << " "; }
cout << endl;
}
cout << endl << endl; return system( "pause" );
}
//--------------------------------------------------------------------------------------------------
|
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a sparkline-type bar graph of the values on a single line of output.
The eight characters: '▁▂▃▄▅▆▇█'
(Unicode values U+2581 through U+2588).
Use your program to show sparklines for the following input,
here on this page:
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5
(note the mix of separators in this second case)!
Notes
A space is not part of the generated sparkline.
The sparkline may be accompanied by simple statistics of the data such as its range.
A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:
"0, 1, 19, 20" -> ▁▁██
(Aiming to use just two spark levels)
"0, 999, 4000, 4999, 7000, 7999" -> ▁▁▅▅██
(Aiming to use just three spark levels)
It may be helpful to include these cases in output tests.
You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols nobinary
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method sparkline(spark) private static
spark = spark.changestr(',', ' ')
bars = '\u2581 \u2582 \u2583 \u2584 \u2585 \u2586 \u2587 \u2588'
barK = bars.words()
nmin = spark.word(1)
nmax = nmin
-- get min & max values
loop iw = 1 to spark.words()
nval = spark.word(iw)
nmin = nval.min(nmin)
nmax = nval.max(nmax)
end iw
range = nmax - nmin + 1
slope = ''
loop iw = 1 to spark.words()
point = Math.ceil((spark.word(iw) - nmin + 1) / range * barK)
slope = slope || bars.word(point)
end iw
return slope nmin nmax range
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
-- sample data setup
parse arg vals
sparks = 0
sparks[0] = 0
if vals = '' then do
si = sparks[0] + 1; sparks[0] = si; sparks[si] = 1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
si = sparks[0] + 1; sparks[0] = si; sparks[si] = '1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5'
end
else do
loop until vals = ''
-- split input on a ! character
parse vals lst '!' vals
si = sparks[0] + 1; sparks[0] = si; sparks[si] = lst
end
end
-- run the samples
loop si = 1 to sparks[0]
vals = sparks[si]
parse sparkline(vals) slope .
say 'Input: ' vals
say 'Sparkline: ' slope
say
end si
return
|
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand 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 Strand sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Strand sort.
This is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list.
| #PicoLisp | PicoLisp | (de strandSort (Lst)
(let Res NIL # Result list
(while Lst
(let Sub (circ (car Lst)) # Build sublist as fifo
(setq
Lst (filter
'((X)
(or
(> (car Sub) X)
(nil (fifo 'Sub X)) ) )
(cdr Lst) )
Res (make
(while (or Res Sub) # Merge
(link
(if2 Res Sub
(if (>= (car Res) (cadr Sub))
(fifo 'Sub)
(pop 'Res) )
(pop 'Res)
(fifo 'Sub) ) ) ) ) ) ) )
Res ) ) |
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand 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 Strand sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Strand sort.
This is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list.
| #PL.2FI | PL/I | strand: procedure options (main); /* 27 Oct. 2012 */
declare A(100) fixed, used(100) bit (1), sorted fixed controlled;
declare (temp, work) fixed controlled;
declare (i, j, k, n) fixed binary;
n = hbound(A, 1);
used = '1'b;
A = random()*99;
put edit (A) (f(3));
do while (allocation(sorted) < n);
call fetch (A, work);
call move (temp, work);
call merge(sorted, temp);
/* Merges elements in SORTED with elements in TEMP. */
end;
/* Transfer the sorted elements to A. */
do i = 1 to allocation(sorted);
A(i) = sorted; free sorted;
end;
/* Print the sorted values. */
put skip list ('The sorted values are:');
put skip edit (A) (f(3));
/* Merges elements of SORTED with elements of TEMP and places */
/* the result in SORTED. */
/* Elements in SORTED and TEMP are in forward order. */
merge: procedure (sorted, temp);
declare (sorted, temp) fixed controlled;
declare work fixed controlled;
declare (j_ok, k_ok) bit (1);
do until ((k_ok | j_ok) = '0'b);
k_ok = allocation(sorted) > 0;
j_ok = allocation(temp) > 0;
if k_ok & j_ok then
do;
if sorted <= temp then
do; allocate work; work = sorted; free sorted; end;
else
do; allocate work; work = temp; free temp; end;
end;
else
if allocation(temp) = 0 then
/* temp is empty; copy remainder of sorted into work */
do while (allocation(sorted) > 0);
allocate work; work = sorted; free sorted;
end;
else
/* sorted is empty; copy remainder of temp onto work */
do while (allocation(temp) > 0);
allocate work; work = temp; free temp;
end;
end;
call move (sorted, work); /* Move the values to SORTED. */
end merge;
/* Collect a thread of ascending values from aray A, and stack them in temp. */
/* Note: the values in temp are in reverse order. */
fetch: procedure (A, temp);
declare A(*) fixed, temp controlled fixed;
declare i fixed binary;
do i = 1 to hbound(A,1);
if used(i) then
do; allocate temp; temp = A(i); used(i) = '0'b; go to found; end;
end;
found:
do i = i+1 to hbound(A,1);
if (temp <= A(i)) & used(i) then
do; allocate temp; temp = A(i); used(i) = '0'b; end;
end;
end fetch;
/* Copy the stack at TEMP to the stack at SORTED. */
/* In TEMP, elements are in reverse order; */
/* in SORTED, elements are in forward order. */
move: procedure (sorted, temp);
declare (sorted, temp) fixed controlled;
do while (allocation(sorted) > 0); free sorted; end;
do while (allocation (temp) > 0);
allocate sorted; sorted = temp; free temp;
end;
end move;
end strand; |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.
Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.
Task Specifics
Given ten males:
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
And ten females:
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
And a complete list of ranked preferences, where the most liked is to the left:
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope
abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan
Use the Gale Shapley algorithm to find a stable set of engagements
Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.
References
The Stable Marriage Problem. (Eloquent description and background information).
Gale-Shapley Algorithm Demonstration.
Another Gale-Shapley Algorithm Demonstration.
Stable Marriage Problem - Numberphile (Video).
Stable Marriage Problem (the math bit) (Video).
The Stable Marriage Problem and School Choice. (Excellent exposition)
| #Phix | Phix | constant men = {"abe","bob","col","dan","ed","fred","gav","hal","ian","jon"}
enum abe , bob , col , dan , ed , fred , gav , hal , ian , jon
constant hen = {"abi","bea","cath","dee","eve","fay","gay","hope","ivy","jan"}
enum abi , bea , cath , dee , eve , fay , gay , hope , ivy , jan
-- Given a complete list of ranked preferences, where the most liked is to the left:
sequence mpref = repeat(0,length(men))
mpref[abe] = {abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay}
mpref[bob] = {cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay}
mpref[col] = {hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan}
mpref[dan] = {ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi}
mpref[ed] = {jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay}
mpref[fred] = {bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay}
mpref[gav] = {gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay}
mpref[hal] = {abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee}
mpref[ian] = {hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve}
mpref[jon] = {abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope}
sequence hpref = repeat(0,length(hen))
hpref[abi] = {bob, fred, jon, gav, ian, abe, dan, ed, col, hal}
hpref[bea] = {bob, abe, col, fred, gav, dan, ian, ed, jon, hal}
hpref[cath] = {fred, bob, ed, gav, hal, col, ian, abe, dan, jon}
hpref[dee] = {fred, jon, col, abe, ian, hal, gav, dan, bob, ed}
hpref[eve] = {jon, hal, fred, dan, abe, gav, col, ed, ian, bob}
hpref[fay] = {bob, abe, ed, ian, jon, dan, fred, gav, col, hal}
hpref[gay] = {jon, gav, hal, fred, bob, abe, col, ed, dan, ian}
hpref[hope] = {gav, jon, bob, abe, ian, dan, hal, ed, col, fred}
hpref[ivy] = {ian, col, hal, gav, fred, bob, abe, ed, jon, dan}
hpref[jan] = {ed, hal, gav, abe, bob, jon, col, ian, fred, dan}
sequence engagements := repeat(0,length(hen))
sequence freemen = tagset(length(men))
printf(1,"Engagements:\n")
-- use the Gale Shapley algorithm to find a stable set of engagements:
while length(freemen) do
integer man = freemen[1]
freemen = freemen[2..$]
integer fem, dumpee
-- each male loops through all females in order of his preference until one accepts him
for j=1 to length(mpref[man]) do
fem = mpref[man][j]
dumpee = engagements[fem]
if dumpee=0
or find(man,hpref[fem])<find(dumpee,hpref[fem]) then
exit
end if
end for
if dumpee!=0 then -- if she was previously engaged
freemen &= dumpee -- he goes to the bottom of the list
printf(1,"%s dumped %s and accepted %s\n",{hen[fem],men[dumpee],men[man]})
else
printf(1,"%s accepted %s\n",{hen[fem],men[man]})
end if
engagements[fem] := man -- the new engagement is registered
end while
printf(1,"\nCouples:\n")
for fem=1 to length(hen) do
printf(1,"%s is engaged to %s\n",{hen[fem],men[engagements[fem]]})
end for
procedure stable()
bool unstable = false
for fem=1 to length(hen) do
integer man = engagements[fem]
for j=1 to length(hen) do
if find(fem,mpref[man])>find(j,mpref[man])
and find(engagements[j],hpref[j])>find(man,hpref[j]) then
if unstable=false then
printf(1,"\nThese couples are not stable.\n")
unstable = true
end if
printf(1,"%s is engaged to %s but would prefer %s and %s is engaged to %s but would prefer %s\n",
{men[man],hen[fem],hen[j],hen[j],men[engagements[j]],men[man]})
end if
end for
end for
if not unstable then
printf(1,"\nThese couples are stable.\n")
end if
end procedure
stable()
printf(1,"\nWhat if cath and ivy swap?\n")
engagements[cath]:=abe; engagements[ivy]:=bob
stable()
|
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Haskell | Haskell | type Stack a = [a]
create :: Stack a
create = []
push :: a -> Stack a -> Stack a
push = (:)
pop :: Stack a -> (a, Stack a)
pop [] = error "Stack empty"
pop (x:xs) = (x,xs)
empty :: Stack a -> Bool
empty = null
peek :: Stack a -> a
peek [] = error "Stack empty"
peek (x:_) = x |
http://rosettacode.org/wiki/Spiral_matrix | Spiral matrix | Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
Related tasks
Zig-zag matrix
Identity_matrix
Ulam_spiral_(for_primes)
| #Go | Go | package main
import (
"fmt"
"strconv"
)
var n = 5
func main() {
if n < 1 {
return
}
top, left, bottom, right := 0, 0, n-1, n-1
sz := n * n
a := make([]int, sz)
i := 0
for left < right {
// work right, along top
for c := left; c <= right; c++ {
a[top*n+c] = i
i++
}
top++
// work down right side
for r := top; r <= bottom; r++ {
a[r*n+right] = i
i++
}
right--
if top == bottom {
break
}
// work left, along bottom
for c := right; c >= left; c-- {
a[bottom*n+c] = i
i++
}
bottom--
// work up left side
for r := bottom; r >= top; r-- {
a[r*n+left] = i
i++
}
left++
}
// center (last) element
a[top*n+left] = i
// print
w := len(strconv.Itoa(n*n - 1))
for i, e := range a {
fmt.Printf("%*d ", w, e)
if i%n == n-1 {
fmt.Println("")
}
}
} |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #REXX | REXX | /*REXX program demonstrates REXX special variables: RC, RESULT, SIGL */
/*line two. */
/*line three.*/ say copies('═',79)
rc=1/3 /*line four. */
signal youWho /*line five. */
myLoo='this got skipped' /*line six. */
youwho: /*line seven.*/
sep=copies('─', 9) /*line eight.*/
say sep 'SIGL=' sigl /*line nine. */
say sep 'REXX source statement' SIGL '=' sourceline(sigl)
say copies('═',79)
g=44
call halve g
say sep 'rc=' rc
say sep 'result=' result
say copies('═',79)
h=66
hh=halve(h)
say sep 'rc=' rc
say sep 'result=' result
say sep 'hh=' hh
say copies('═',79)
'DIR /ad /b' /*display the directories (Bare).*/
say sep 'rc=' rc
say sep 'result=' result
say copies('═',79)
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────HALVE subroutine────────────────────*/
halve: return arg(1) / 2 /*a simple halving function. */ |
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort | Sorting algorithms/Radix 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
Task
Sort an integer array with the radix sort algorithm.
The primary purpose is to complete the characterization of sort algorithms task.
| #ATS | ATS | (*
Stable integer-keyed radix sorts for unsigned and signed integers
of the various typekinds.
The radix is 256.
*)
(*------------------------------------------------------------------*)
#include "share/atspre_staload.hats"
staload UN = "prelude/SATS/unsafe.sats"
(*------------------------------------------------------------------*)
extern fn {a : vt@ype}
{tk : tkind}
g0uint_radix_sort
{n : int}
(arr : &array (a, n) >> _,
n : size_t n)
:<!wrt> void
extern fn {a : vt@ype}
{tk : tkind}
g0uint_radix_sort$key
{n : int}
{i : nat | i < n}
(arr : &RD(array (a, n)),
i : size_t i)
:<> g0uint tk
(*------------------------------------------------------------------*)
extern fn {a : vt@ype}
{tki, tku : tkind}
g0int_radix_sort
{n : int}
(arr : &array (a, n) >> _,
n : size_t n)
:<!wrt> void
extern fn {a : vt@ype}
{tki : tkind}
g0int_radix_sort$key
{n : int}
{i : nat | i < n}
(arr : &RD(array (a, n)),
i : size_t i)
:<> g0int tki
(*------------------------------------------------------------------*)
(* WARNING: Much of the following code does NOT take into account
the linearity of array entries. But this unsafeness is
hidden from the user. *)
fn {}
bin_sizes_to_indices
(bin_indices : &array (size_t, 256) >> _)
:<!wrt> void =
let
fun
loop {i : int | i <= 256}
{accum : int}
.<256 - i>.
(bin_indices : &array (size_t, 256) >> _,
i : size_t i,
accum : size_t accum)
:<!wrt> void =
if i <> i2sz 256 then
let
prval () = lemma_g1uint_param i
val elem = bin_indices[i]
in
if elem = i2sz 0 then
loop (bin_indices, succ i, accum)
else
begin
bin_indices[i] := accum;
loop (bin_indices, succ i, accum + g1ofg0 elem)
end
end
in
loop (bin_indices, i2sz 0, i2sz 0)
end
fn {a : vt@ype}
{tk : tkind}
count_entries
{n : int}
{shift : nat}
(arr : &RD(array (a, n)),
n : size_t n,
bin_indices : &array (size_t?, 256)
>> array (size_t, 256),
all_expended : &bool? >> bool,
shift : int shift)
:<!wrt> void =
let
fun
loop {i : int | i <= n}
.<n - i>.
(arr : &RD(array (a, n)),
bin_indices : &array (size_t, 256) >> _,
all_expended : &bool >> bool,
i : size_t i)
:<!wrt> void =
if i <> n then
let
prval () = lemma_g1uint_param i
val key : g0uint tk = g0uint_radix_sort$key<a><tk> (arr, i)
val key_shifted = key >> shift
val digit = ($UN.cast{uint} key_shifted) land 255U
val [digit : int] digit = g1ofg0 digit
extern praxi set_range :
() -<prf> [0 <= digit; digit <= 255] void
prval () = set_range ()
val count = bin_indices[digit]
val () = bin_indices[digit] := succ count
in
all_expended := all_expended * iseqz key_shifted;
loop (arr, bin_indices, all_expended, succ i)
end
prval () = lemma_array_param arr
in
array_initize_elt<size_t> (bin_indices, i2sz 256, i2sz 0);
all_expended := true;
loop (arr, bin_indices, all_expended, i2sz 0)
end
fn {a : vt@ype}
{tk : tkind}
sort_by_digit
{n : int}
{shift : nat}
(arr1 : &RD(array (a, n)),
arr2 : &array (a, n) >> _,
n : size_t n,
all_expended : &bool? >> bool,
shift : int shift)
:<!wrt> void =
let
var bin_indices : array (size_t, 256)
in
count_entries<a><tk> (arr1, n, bin_indices, all_expended, shift);
if all_expended then
()
else
let
fun
rearrange {i : int | i <= n}
.<n - i>.
(arr1 : &RD(array (a, n)),
arr2 : &array (a, n) >> _,
bin_indices : &array (size_t, 256) >> _,
i : size_t i)
:<!wrt> void =
if i <> n then
let
prval () = lemma_g1uint_param i
val key = g0uint_radix_sort$key<a><tk> (arr1, i)
val key_shifted = key >> shift
val digit = ($UN.cast{uint} key_shifted) land 255U
val [digit : int] digit = g1ofg0 digit
extern praxi set_range :
() -<prf> [0 <= digit; digit <= 255] void
prval () = set_range ()
val [j : int] j = g1ofg0 bin_indices[digit]
(* One might wish to get rid of this assertion somehow,
to eliminate the branch, should it prove a
problem. *)
val () = $effmask_exn assertloc (j < n)
val p_dst = ptr_add<a> (addr@ arr2, j)
and p_src = ptr_add<a> (addr@ arr1, i)
val _ = $extfcall (ptr, "memcpy", p_dst, p_src,
sizeof<a>)
val () = bin_indices[digit] := succ (g0ofg1 j)
in
rearrange (arr1, arr2, bin_indices, succ i)
end
prval () = lemma_array_param arr1
in
bin_sizes_to_indices<> bin_indices;
rearrange (arr1, arr2, bin_indices, i2sz 0)
end
end
fn {a : vt@ype}
{tk : tkind}
g0uint_sort {n : pos}
(arr1 : &array (a, n) >> _,
arr2 : &array (a, n) >> _,
n : size_t n)
:<!wrt> void =
let
fun
loop {idigit_max, idigit : nat | idigit <= idigit_max}
.<idigit_max - idigit>.
(arr1 : &array (a, n) >> _,
arr2 : &array (a, n) >> _,
from1to2 : bool,
idigit_max : int idigit_max,
idigit : int idigit)
:<!wrt> void =
if idigit = idigit_max then
begin
if ~from1to2 then
let
val _ =
$extfcall (ptr, "memcpy", addr@ arr1, addr@ arr2,
sizeof<a> * n)
in
end
end
else if from1to2 then
let
var all_expended : bool
in
sort_by_digit<a><tk> (arr1, arr2, n, all_expended,
8 * idigit);
if all_expended then
()
else
loop (arr1, arr2, false, idigit_max, succ idigit)
end
else
let
var all_expended : bool
in
sort_by_digit<a><tk> (arr2, arr1, n, all_expended,
8 * idigit);
if all_expended then
let
val _ =
$extfcall (ptr, "memcpy", addr@ arr1, addr@ arr2,
sizeof<a> * n)
in
end
else
loop (arr1, arr2, true, idigit_max, succ idigit)
end
in
loop (arr1, arr2, true, sz2i sizeof<g1uint tk>, 0)
end
#define SIZE_THRESHOLD 256
extern praxi
unsafe_cast_array
{a : vt@ype}
{b : vt@ype}
{n : int}
(arr : &array (b, n) >> array (a, n))
:<prf> void
implement {a} {tk}
g0uint_radix_sort {n} (arr, n) =
if n <> 0 then
let
prval () = lemma_array_param arr
fn
sort {n : pos}
(arr1 : &array (a, n) >> _,
arr2 : &array (a, n) >> _,
n : size_t n)
:<!wrt> void =
g0uint_sort<a><tk> (arr1, arr2, n)
in
if n <= SIZE_THRESHOLD then
let
var arr2 : array (a, SIZE_THRESHOLD)
prval @(pf_left, pf_right) =
array_v_split {a?} {..} {SIZE_THRESHOLD} {n} (view@ arr2)
prval () = view@ arr2 := pf_left
prval () = unsafe_cast_array{a} arr2
val () = sort (arr, arr2, n)
prval () = unsafe_cast_array{a?} arr2
prval () = view@ arr2 :=
array_v_unsplit (view@ arr2, pf_right)
in
end
else
let
val @(pf_arr2, pfgc_arr2 | p_arr2) = array_ptr_alloc<a> n
macdef arr2 = !p_arr2
prval () = unsafe_cast_array{a} arr2
val () = sort (arr, arr2, n)
prval () = unsafe_cast_array{a?} arr2
val () = array_ptr_free (pf_arr2, pfgc_arr2 | p_arr2)
in
end
end
(*------------------------------------------------------------------*)
fn {a : vt@ype}
{tki, tku : tkind}
g0int_sort {n : int}
(arr : &array (a, n) >> _,
n : size_t n)
:<!wrt> void =
let
macdef get_key = g0int_radix_sort$key<a><tki>
prval () = lemma_array_param arr
in
if n = 0 then
()
else
let
val () = $effmask_exn
assertloc (sizeof<g0int tki> = sizeof<g0uint tku>)
fn
find_least_key (arr : &RD(array (a, n)))
:<> g0int tki =
let
fun
loop {i : int | i <= n}
.<n - i>.
(arr : &RD(array (a, n)),
least_key : g0int tki,
i : size_t i)
:<> g0int tki =
if i <> n then
let
prval () = lemma_g1uint_param i
val key = get_key (arr, i)
in
loop (arr, min (least_key, key), succ i)
end
else
least_key
in
if n = 0 then
get_key (arr, i2sz 0)
else
let
val first_key = get_key (arr, i2sz 0)
in
loop (arr, first_key, i2sz 1)
end
end
val least_key = find_least_key arr
(* The offset is the two's complement of the least key. Thus the
least key is mapped to zero and the order of keys is
preserved. *)
val offset = succ (lnot ($UN.cast{g1uint tku} least_key))
implement
g0uint_radix_sort$key<a><tku> (arr, i) =
let
val keyi = get_key (arr, i)
in
g0i2u keyi + offset
end
in
g0uint_radix_sort<a><tku> (arr, n)
end
end
implement {a} {tki, tku}
g0int_radix_sort (arr, n) =
g0int_sort<a><tki, tku> (arr, n)
(*------------------------------------------------------------------*)
implement
main0 () =
let
implement
g0int_radix_sort$key<int><intknd> (arr, i) =
arr[i]
var arr : array (int, 10)
val () =
array_initize_list<int>
(arr, 10, $list (1, 2, 1, ~2, 330, 5000, 16, ~20000, 1, 2))
val () = g0int_radix_sort<int><intknd, uintknd> (arr, i2sz 10)
val () = println! (list_vt2t (array2list (arr, i2sz 10)))
in
end
(*------------------------------------------------------------------*) |
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort | Sorting algorithms/Patience 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
Sort an array of numbers (of any convenient size) into ascending order using Patience sorting.
Related task
Longest increasing subsequence
| #11l | 11l | F patience_sort(&arr)
I arr.len < 2 {R}
[[T(arr[0])]] piles
L(el) arr
L(&pile) piles
I pile.last > el
pile.append(el)
L.break
L.was_no_break
piles.append([el])
L(i) 0 .< arr.len
V min = piles[0].last
V minPileIndex = 0
L(j) 1 .< piles.len
I piles[j].last < min
min = piles[j].last
minPileIndex = j
arr[i] = min
V& minPile = piles[minPileIndex]
minPile.pop()
I minPile.empty
piles.pop(minPileIndex)
V iArr = [4, 65, 2, -31, 0, 99, 83, 782, 1]
patience_sort(&iArr)
print(iArr)
V cArr = [‘n’, ‘o’, ‘n’, ‘z’, ‘e’, ‘r’, ‘o’, ‘s’, ‘u’, ‘m’]
patience_sort(&cArr)
print(cArr)
V sArr = [‘dog’, ‘cow’, ‘cat’, ‘ape’, ‘ant’, ‘man’, ‘pig’, ‘ass’, ‘gnu’]
patience_sort(&sArr)
print(sArr) |
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort | Sorting algorithms/Permutation 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
Task
Implement a permutation sort, which proceeds by generating the possible permutations
of the input array/list until discovering the sorted one.
Pseudocode:
while not InOrder(list) do
nextPermutation(list)
done
| #Clojure | Clojure |
(use '[clojure.contrib.combinatorics :only (permutations)])
(defn permutation-sort [s]
(first (filter (partial apply <=) (permutations s))))
(permutation-sort [2 3 5 3 5])
|
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort | Sorting algorithms/Permutation 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
Task
Implement a permutation sort, which proceeds by generating the possible permutations
of the input array/list until discovering the sorted one.
Pseudocode:
while not InOrder(list) do
nextPermutation(list)
done
| #CoffeeScript | CoffeeScript | # This code takes a ridiculously inefficient algorithm and rather futilely
# optimizes one part of it. Permutations are computed lazily.
sorted_copy = (a) ->
# This returns a sorted copy of an array by lazily generating
# permutations of indexes and stopping when the indexes yield
# a sorted array.
indexes = [0...a.length]
ans = find_matching_permutation indexes, (permuted_indexes) ->
new_array = (a[i] for i in permuted_indexes)
console.log permuted_indexes, new_array
in_order(new_array)
(a[i] for i in ans)
in_order = (a) ->
# return true iff array a is in increasing order.
return true if a.length <= 1
for i in [0...a.length-1]
return false if a[i] > a[i+1]
true
get_factorials = (n) ->
# return an array of the first n+1 factorials, starting with 0!
ans = [1]
f = 1
for i in [1..n]
f *= i
ans.push f
ans
permutation = (a, i, factorials) ->
# Return the i-th permutation of an array by
# using remainders of factorials to determine
# elements.
while a.length > 0
f = factorials[a.length-1]
n = Math.floor(i / f)
i = i % f
elem = a[n]
a = a[0...n].concat(a[n+1...])
elem
# The above loop gets treated like
# an array expression, so it returns
# all the elements.
find_matching_permutation = (a, f_match) ->
factorials = get_factorials(a.length)
for i in [0...factorials[a.length]]
permuted_array = permutation(a, i, factorials)
if f_match permuted_array
return permuted_array
null
do ->
a = ['c', 'b', 'a', 'd']
console.log 'input:', a
ans = sorted_copy a
console.log 'DONE!'
console.log 'sorted copy:', ans
|
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort | Sorting algorithms/Pancake 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
Task
Sort an array of integers (of any convenient size) into ascending order using Pancake sorting.
In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so:
Before: 6 7 8 9 2 5 3 4 1
After: 9 8 7 6 2 5 3 4 1
Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it must be the same end for the entire solution. (The end flipped can't be arbitrarily changed.)
Show both the initial, unsorted list and the final sorted list.
(Intermediate steps during sorting are optional.)
Optimizations are optional (but recommended).
Related tasks
Number reversal game
Topswops
Also see
Wikipedia article: pancake sorting.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program mergeSort64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeConstantesARM64.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSortOk: .asciz "Table sorted.\n"
szMessSortNok: .asciz "Table not sorted !!!!!.\n"
sMessResult: .asciz "Value : @ \n"
sMessCounter: .asciz "sorted in @ flips \n"
szCarriageReturn: .asciz "\n"
.align 4
TableNumber: .quad 1,3,11,6,2,-5,9,10,8,4,7
#TableNumber: .quad 10,9,8,7,6,-5,4,3,2,1
.equ NBELEMENTS, (. - TableNumber) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrTableNumber // address number table
mov x1,0 // first element
mov x2,NBELEMENTS // number of élements
bl pancakeSort
ldr x0,qAdrTableNumber // address number table
bl displayTable
mov x0,x10 // display counter
ldr x1,qAdrsZoneConv
bl conversion10S // décimal conversion
ldr x0,qAdrsMessCounter
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
ldr x0,qAdrTableNumber // address number table
mov x1,NBELEMENTS // number of élements
bl isSorted // control sort
cmp x0,1 // sorted ?
beq 1f
ldr x0,qAdrszMessSortNok // no !! error sort
bl affichageMess
b 100f
1: // yes
ldr x0,qAdrszMessSortOk
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrTableNumber: .quad TableNumber
qAdrszMessSortOk: .quad szMessSortOk
qAdrszMessSortNok: .quad szMessSortNok
qAdrsMessCounter: .quad sMessCounter
/******************************************************************/
/* control sorted table */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the number of elements > 0 */
/* x0 return 0 if not sorted 1 if sorted */
isSorted:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
mov x2,0
ldr x4,[x0,x2,lsl 3]
1:
add x2,x2,1
cmp x2,x1
bge 99f
ldr x3,[x0,x2, lsl 3]
cmp x3,x4
blt 98f
mov x4,x3
b 1b
98:
mov x0,0 // not sorted
b 100f
99:
mov x0,1 // sorted
100:
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* flip */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains first start index
/* x2 contains the number of elements */
/* x3 contains the position of flip */
flip:
//push {r1-r6,lr} // save registers
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
str x6, [sp,-16]! // save registers
add x10,x10,#1 // flips counter
cmp x3,x2
sub x4,x2,1
csel x3,x4,x3,ge // last index if position >= size
1:
cmp x1,x3
bge 100f
ldr x5,[x0,x1,lsl 3] // load value first index
ldr x6,[x0,x3,lsl 3] // load value position index
str x6,[x0,x1,lsl 3] // inversion
str x5,[x0,x3,lsl 3] //
sub x3,x3,1
add x1,x1,1
b 1b
100:
ldr x6, [sp],16 // restaur 1 register
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* pancake sort */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains first start index
/* x2 contains the number of elements */
pancakeSort:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
stp x8,x9,[sp,-16]! // save registers
sub x7,x2,1 // last index
1:
mov x5,x1 // index
mov x4,0 // max
mov x3,0 // position
mov x8,1 // top sorted
ldr x9,[x0,x5,lsl 3] // load value A[i-1]
2:
ldr x6,[x0,x5,lsl 3] // load value
cmp x6,x4 // compare max
csel x4,x6,x4,ge // max = A[i}
csel x3,x5,x3,ge // position = index
cmp x6,x9 // cmp A[i] A[i-1] sorted ?
csel x8,xzr,x8,lt // no
mov x9,x6 // A[i-1] = A[i]
add x5,x5,1 // increment index
cmp x5,x7 // end ?
ble 2b
cmp x8,1 // sorted ?
beq 100f // yes -> end
cmp x3,x7 // position ok ?
beq 4f // yes
cmp x3,0 // first position ?
beq 3f
bl flip // flip if not greather in first position
3:
mov x3,x7 // and flip the whole stack
bl flip
4:
//bl displayTable // to display an intermediate state
subs x7,x7,1 // decrement number of pancake
bge 1b // and loop
100:
ldp x8,x9,[sp],16 // restaur 2 registers
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* x0 contains the address of table */
displayTable:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x0 // table address
mov x3,0
1: // loop display table
ldr x0,[x2,x3,lsl 3]
ldr x1,qAdrsZoneConv
bl conversion10S // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
add x3,x3,1
cmp x3,NBELEMENTS - 1
ble 1b
ldr x0,qAdrszCarriageReturn
bl affichageMess
mov x0,x2
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort | Sorting algorithms/Pancake 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
Task
Sort an array of integers (of any convenient size) into ascending order using Pancake sorting.
In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so:
Before: 6 7 8 9 2 5 3 4 1
After: 9 8 7 6 2 5 3 4 1
Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it must be the same end for the entire solution. (The end flipped can't be arbitrarily changed.)
Show both the initial, unsorted list and the final sorted list.
(Intermediate steps during sorting are optional.)
Optimizations are optional (but recommended).
Related tasks
Number reversal game
Topswops
Also see
Wikipedia article: pancake sorting.
| #Action.21 | Action! | PROC PrintArray(INT ARRAY a INT size)
INT i
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
PROC Flip(INT ARRAY a INT last)
INT i,n,tmp
n=(last-1)/2
FOR i=0 TO n
DO
tmp=a(i)
a(i)=a(last-i)
a(last-i)=tmp
OD
RETURN
PROC PancakeSort(INT ARRAY a INT size)
INT i,j,maxpos
i=size-1
WHILE i>=0
DO
maxpos=i
FOR j=0 TO i-1
DO
IF a(j)>a(maxpos) THEN
maxpos=j
FI
OD
IF maxpos#i THEN
IF maxpos#0 THEN
Flip(a,maxpos)
FI
Flip(a,i)
FI
i==-1
OD
RETURN
PROC Test(INT ARRAY a INT size)
PrintE("Array before sort:")
PrintArray(a,size)
PancakeSort(a,size)
PrintE("Array after sort:")
PrintArray(a,size)
PutE()
RETURN
PROC Main()
INT ARRAY
a(10)=[1 4 65535 0 3 7 4 8 20 65530],
b(21)=[10 9 8 7 6 5 4 3 2 1 0
65535 65534 65533 65532 65531
65530 65529 65528 65527 65526],
c(8)=[101 102 103 104 105 106 107 108],
d(12)=[1 65535 1 65535 1 65535 1
65535 1 65535 1 65535]
Test(a,10)
Test(b,21)
Test(c,8)
Test(d,12)
RETURN |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Markup :
() Sequence
{} List
" String
\ Escape for following character
(* *) Comment block
base^^number`s
` Context
[[]] Indexed reference
Within expression:
\ At end of line: Continue on next line, skipping white space |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #MBS | MBS | USER>Set S1="Hello, World!" Write S1
Hello, World!
USER>Set S2=""Hello, World!"" Write S2
SET S2=""Hello, World!"" Write S2
^
<SYNTAX>
USER>Set S3="""Hello, World!"" she typed." Write S3
"Hello, World!" she typed.
USER>Set S4="""""""Wow""""""" Write S4
"""Wow"""
|
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #MUMPS | MUMPS | USER>Set S1="Hello, World!" Write S1
Hello, World!
USER>Set S2=""Hello, World!"" Write S2
SET S2=""Hello, World!"" Write S2
^
<SYNTAX>
USER>Set S3="""Hello, World!"" she typed." Write S3
"Hello, World!" she typed.
USER>Set S4="""""""Wow""""""" Write S4
"""Wow"""
|
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort | Sorting algorithms/Stooge 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 Stooge sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Show the Stooge Sort for an array of integers.
The Stooge Sort algorithm is as follows:
algorithm stoogesort(array L, i = 0, j = length(L)-1)
if L[j] < L[i] then
L[i] ↔ L[j]
if j - i > 1 then
t := (j - i + 1)/3
stoogesort(L, i , j-t)
stoogesort(L, i+t, j )
stoogesort(L, i , j-t)
return L
| #Elena | Elena | import extensions;
import system'routines;
extension op
{
stoogeSort()
= self.stoogeSort(0, self.Length - 1);
stoogeSort(IntNumber i, IntNumber j)
{
if(self[j]<self[i])
{
self.exchange(i,j)
};
if (j - i > 1)
{
int t := (j - i + 1) / 3;
self.stoogeSort(i,j-t);
self.stoogeSort(i+t,j);
self.stoogeSort(i,j-t)
}
}
}
public program()
{
var list := new Range(0, 15).selectBy:(n => randomGenerator.eval(20)).toArray();
console.printLine("before:", list.asEnumerable());
console.printLine("after:", list.stoogeSort().asEnumerable())
} |
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort | Sorting algorithms/Stooge 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 Stooge sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Show the Stooge Sort for an array of integers.
The Stooge Sort algorithm is as follows:
algorithm stoogesort(array L, i = 0, j = length(L)-1)
if L[j] < L[i] then
L[i] ↔ L[j]
if j - i > 1 then
t := (j - i + 1)/3
stoogesort(L, i , j-t)
stoogesort(L, i+t, j )
stoogesort(L, i , j-t)
return L
| #Elixir | Elixir | defmodule Sort do
def stooge_sort(list) do
stooge_sort(List.to_tuple(list), 0, length(list)-1) |> Tuple.to_list
end
defp stooge_sort(tuple, i, j) do
if (vj = elem(tuple, j)) < (vi = elem(tuple, i)) do
tuple = put_elem(tuple,i,vj) |> put_elem(j,vi)
end
if j - i > 1 do
t = div(j - i + 1, 3)
tuple
|> stooge_sort(i, j-t)
|> stooge_sort(i+t, j)
|> stooge_sort(i, j-t)
else
tuple
end
end
end
(for _ <- 1..20, do: :rand.uniform(20)) |> IO.inspect
|> Sort.stooge_sort |> IO.inspect |
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort | Sorting algorithms/Sleep 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
In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time.
Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required.
Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
| #Fortran | Fortran |
program sleepSort
use omp_lib
implicit none
integer::nArgs,myid,i,stat
integer,allocatable::intArg(:)
character(len=5)::arg
!$omp master
nArgs=command_argument_count()
if(nArgs==0)stop ' : No argument is given !'
allocate(intArg(nArgs))
do i=1,nArgs
call get_command_argument(i, arg)
read(arg,'(I5)',iostat=stat)intArg(i)
if(intArg(i)<0 .or. stat/=0) stop&
&' :Only 0 or positive integer allowed !'
end do
call omp_set_num_threads(nArgs)
!$omp end master
!$omp parallel private(myid)
myid =omp_get_thread_num()
call sleepNprint(intArg(myid+1))
!$omp end parallel
contains
subroutine sleepNprint(nSeconds)
integer::nSeconds
call sleep(nSeconds)
print*,nSeconds
end subroutine sleepNprint
end program sleepSort
|
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort | Sorting algorithms/Sleep 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
In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time.
Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required.
Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
| #FreeBASIC | FreeBASIC | ' version 21-10-2016
' compile with: fbc -s console
' compile with: fbc -s console -exx (for bondry check on the array's)
' not very well suited for large numbers and large array's
' positive numbers only
Sub sandman(sleepy() As ULong)
Dim As Long lb = LBound(sleepy)
Dim As Long ub = UBound(sleepy)
Dim As Long i, count = ub
Dim As Double wakeup(lb To ub)
Dim As Double t = Timer
For i = lb To ub
wakeup(i) = sleepy(i) +1 + t
Next
Do
t = Timer
For i = lb To ub
If wakeup(i) <= t Then
Print Using "####";sleepy(i);
wakeup(i) = 1e9 ' mark it as used
count = count -1
End If
Next
Sleep (1 - (Timer - t)) * 300, 1 ' reduce CPU load
Loop Until count < lb
End Sub
' ------=< MAIN >=------
Dim As ULong i, arr(10)
Dim As ULong lb = LBound(arr)
Dim As ULong ub = UBound(arr)
Randomize Timer
For i = lb To ub -1 ' leave last one zero
arr(i) = Int(Rnd * 10) +1
Next
Print "unsorted ";
For i = lb To ub
Print Using "####";arr(i);
Next
Print : Print
Print " sorted ";
sandman(arr())
Print : Print
' empty keyboard buffer
While InKey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort | Sorting algorithms/Selection 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
Task
Sort an array (or list) of elements using the Selection sort algorithm.
It works as follows:
First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted.
Its asymptotic complexity is O(n2) making it inefficient on large arrays.
Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM.
No other sorting algorithm has less data movement.
References
Rosetta Code: O (complexity).
Wikipedia: Selection sort.
Wikipedia: [Big O notation].
| #Arturo | Arturo | selectionSort: function [items][
sorted: new []
tmp: new items
while [not? empty? tmp][
minIndex: index tmp min tmp
'sorted ++ tmp\[minIndex]
remove 'tmp .index minIndex
]
return sorted
]
print selectionSort [3 1 2 8 5 7 9 4 6] |
http://rosettacode.org/wiki/Soundex | Soundex | Soundex is an algorithm for creating indices for words based on their pronunciation.
Task
The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling (from the soundex Wikipedia article).
Caution
There is a major issue in many of the implementations concerning the separation of two consonants that have the same soundex code! According to the official Rules [[1]]. So check for instance if Ashcraft is coded to A-261.
If a vowel (A, E, I, O, U) separates two consonants that have the same soundex code, the consonant to the right of the vowel is coded. Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored (see "Side-by-Side" rule above), 2 for the K). Since the vowel "A" separates the Z and K, the K is coded.
If "H" or "W" separate two consonants that have the same soundex code, the consonant to the right of the vowel is not coded. Example: Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 for the F). It is not coded A-226.
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
/* for ASCII only */
static char code[128] = { 0 };
void add_code(const char *s, int c)
{
while (*s) {
code[(int)*s] = code[0x20 ^ (int)*s] = c;
s++;
}
}
void init()
{
static const char *cls[] =
{ "AEIOU", "", "BFPV", "CGJKQSXZ", "DT", "L", "MN", "R", 0};
int i;
for (i = 0; cls[i]; i++)
add_code(cls[i], i - 1);
}
/* returns a static buffer; user must copy if want to save
result across calls */
const char* soundex(const char *s)
{
static char out[5];
int c, prev, i;
out[0] = out[4] = 0;
if (!s || !*s) return out;
out[0] = *s++;
/* first letter, though not coded, can still affect next letter: Pfister */
prev = code[(int)out[0]];
for (i = 1; *s && i < 4; s++) {
if ((c = code[(int)*s]) == prev) continue;
if (c == -1) prev = 0; /* vowel as separator */
else if (c > 0) {
out[i++] = c + '0';
prev = c;
}
}
while (i < 4) out[i++] = '0';
return out;
}
int main()
{
int i;
const char *sdx, *names[][2] = {
{"Soundex", "S532"},
{"Example", "E251"},
{"Sownteks", "S532"},
{"Ekzampul", "E251"},
{"Euler", "E460"},
{"Gauss", "G200"},
{"Hilbert", "H416"},
{"Knuth", "K530"},
{"Lloyd", "L300"},
{"Lukasiewicz", "L222"},
{"Ellery", "E460"},
{"Ghosh", "G200"},
{"Heilbronn", "H416"},
{"Kant", "K530"},
{"Ladd", "L300"},
{"Lissajous", "L222"},
{"Wheaton", "W350"},
{"Burroughs", "B620"},
{"Burrows", "B620"},
{"O'Hara", "O600"},
{"Washington", "W252"},
{"Lee", "L000"},
{"Gutierrez", "G362"},
{"Pfister", "P236"},
{"Jackson", "J250"},
{"Tymczak", "T522"},
{"VanDeusen", "V532"},
{"Ashcraft", "A261"},
{0, 0}
};
init();
puts(" Test name Code Got\n----------------------");
for (i = 0; names[i][0]; i++) {
sdx = soundex(names[i][0]);
printf("%11s %s %s ", names[i][0], names[i][1], sdx);
printf("%s\n", strcmp(sdx, names[i][1]) ? "not ok" : "ok");
}
return 0;
} |
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort | Sorting algorithms/Shell 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
Task
Sort an array of elements using the Shell sort algorithm, a diminishing increment sort.
The Shell sort (also known as Shellsort or Shell's method) is named after its inventor, Donald Shell, who published the algorithm in 1959.
Shell sort is a sequence of interleaved insertion sorts based on an increment sequence.
The increment size is reduced after each pass until the increment size is 1.
With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case".
Any sequence will sort the data as long as it ends in 1, but some work better than others.
Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice.
[1]
Other good sequences are found at the On-Line Encyclopedia of Integer Sequences.
| #COBOL | COBOL | *******************************************************
IDENTIFICATION DIVISION.
*******************************************************
PROGRAM-ID. SHELLSRT.
************************************************************
*** SHELLSORT ****
************************************************************
ENVIRONMENT DIVISION.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 II PIC S9(008) COMP-5.
01 IJ PIC S9(008) COMP-5.
01 IZ PIC S9(008) COMP-5.
01 IA PIC S9(008) COMP-5.
01 STRT1 PIC S9(008) COMP-5.
01 STRT2 PIC S9(008) COMP-5.
01 LGT PIC S9(008) COMP-5.
01 ORG PIC S9(008) COMP-5.
01 DST PIC S9(008) COMP-5.
*
01 GAP PIC S9(008) COMP-5.
01 NEGAP PIC S9(008) COMP-5.
01 TEMP PIC X(32768).
77 KEY-RESULT PIC X.
*
LINKAGE SECTION.
01 SRT-ARRAY PIC X(1000000).
01 NUM-ITEM PIC 9(008) COMP-5.
01 SRT-DATA.
03 LGT-ITEM PIC 9(004) COMP-5.
03 SRT-KEYS.
05 SRT-KEY OCCURS 10.
07 K-START PIC S9(004) COMP-5.
07 K-LENGTH PIC S9(004) COMP-5.
07 K-ASC PIC X.
*
* P R O C E D U R E D I V I S I O N
*
PROCEDURE DIVISION USING SRT-ARRAY NUM-ITEM SRT-DATA.
COMPUTE GAP = NUM-ITEM / 2.
PERFORM UNTIL GAP < 1
COMPUTE NEGAP = GAP * -1
PERFORM VARYING II FROM GAP BY 1
UNTIL II GREATER NUM-ITEM
MOVE ' ' TO KEY-RESULT
COMPUTE ORG = (II - 1) * LGT-ITEM + 1
MOVE SRT-ARRAY(ORG:LGT-ITEM) TO TEMP(1:LGT-ITEM)
PERFORM VARYING IJ FROM II BY NEGAP
UNTIL IJ NOT GREATER GAP
OR (KEY-RESULT NOT EQUAL '<' AND ' ')
COMPUTE IA = IJ - GAP
IF IA < 1
MOVE 1 TO IA
END-IF
PERFORM COMPARE-KEYS
IF KEY-RESULT = '<'
COMPUTE ORG = (IA - 1) * LGT-ITEM + 1
COMPUTE DST = (IJ - 1) * LGT-ITEM + 1
MOVE SRT-ARRAY(ORG:LGT-ITEM)
TO SRT-ARRAY(DST:LGT-ITEM)
COMPUTE DST = (IA - 1) * LGT-ITEM + 1
MOVE TEMP(1:LGT-ITEM) TO SRT-ARRAY(DST:LGT-ITEM)
END-IF
END-PERFORM
END-PERFORM
IF GAP = 2
MOVE 1 TO GAP
ELSE
COMPUTE GAP = GAP / 2.2
END-IF
END-PERFORM.
GOBACK.
*
COMPARE-KEYS.
MOVE ' ' TO KEY-RESULT
PERFORM VARYING IZ FROM 1 BY 1
UNTIL IZ GREATER 10
OR (KEY-RESULT NOT EQUAL '=' AND ' ')
IF SRT-KEY(IZ) GREATER LOW-VALUES
COMPUTE STRT1 = (IJ - 1) * LGT-ITEM + K-START(IZ)
COMPUTE STRT2 = (IA - 1) * LGT-ITEM + K-START(IZ)
MOVE K-LENGTH(IZ) TO LGT
IF SRT-ARRAY(STRT1:LGT) > SRT-ARRAY(STRT2:LGT) AND
K-ASC(IZ) EQUAL 'A'
OR SRT-ARRAY(STRT1:LGT) < SRT-ARRAY(STRT2:LGT) AND
K-ASC(IZ) EQUAL 'D'
MOVE '>' TO KEY-RESULT
END-IF
IF SRT-ARRAY(STRT1:LGT) < SRT-ARRAY(STRT2:LGT) AND
K-ASC(IZ) EQUAL 'A'
OR SRT-ARRAY(STRT1:LGT) > SRT-ARRAY(STRT2:LGT) AND
K-ASC(IZ) EQUAL 'D'
MOVE '<' TO KEY-RESULT
END-IF
END-IF
END-PERFORM.
IF KEY-RESULT = ' '
MOVE '=' TO KEY-RESULT
END-IF. |
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a sparkline-type bar graph of the values on a single line of output.
The eight characters: '▁▂▃▄▅▆▇█'
(Unicode values U+2581 through U+2588).
Use your program to show sparklines for the following input,
here on this page:
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5
(note the mix of separators in this second case)!
Notes
A space is not part of the generated sparkline.
The sparkline may be accompanied by simple statistics of the data such as its range.
A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:
"0, 1, 19, 20" -> ▁▁██
(Aiming to use just two spark levels)
"0, 999, 4000, 4999, 7000, 7999" -> ▁▁▅▅██
(Aiming to use just three spark levels)
It may be helpful to include these cases in output tests.
You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.
| #Nim | Nim | import rdstdin, sequtils, strutils
const bar = ["\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"]
const barcount = float(bar.high)
while true:
let
line = readLineFromStdin "Numbers please separated by space/commas: "
numbers = line.split({' ', ','}).filterIt(it.len != 0).map(parseFloat)
mn = min(numbers)
mx = max(numbers)
extent = mx - mn
var sparkline = ""
for n in numbers:
let i = int((n - mn) / extent * barcount)
sparkline.add bar[i]
echo "min: ", mn.formatFloat(precision = 0), "; max: ", mx.formatFloat(precision = -1)
echo sparkline |
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a sparkline-type bar graph of the values on a single line of output.
The eight characters: '▁▂▃▄▅▆▇█'
(Unicode values U+2581 through U+2588).
Use your program to show sparklines for the following input,
here on this page:
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5
(note the mix of separators in this second case)!
Notes
A space is not part of the generated sparkline.
The sparkline may be accompanied by simple statistics of the data such as its range.
A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:
"0, 1, 19, 20" -> ▁▁██
(Aiming to use just two spark levels)
"0, 999, 4000, 4999, 7000, 7999" -> ▁▁▅▅██
(Aiming to use just three spark levels)
It may be helpful to include these cases in output tests.
You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.
| #OCaml | OCaml | let before_first_bar = 0x2580
let num_bars = 8
let sparkline numbers =
let max_num = List.fold_left max 0. numbers in
let scale = float_of_int num_bars /. max_num in
let bars = Buffer.create num_bars in
let add_bar number =
let scaled = scale *. number |> Float.round |> int_of_float in
if scaled <= 0 then
(* Using underscore character to differentiate between zero and one *)
Buffer.add_char bars '_'
else
scaled + before_first_bar |> Uchar.of_int |> Buffer.add_utf_8_uchar bars
in
List.iter add_bar numbers;
Buffer.contents bars
let print_sparkline line =
Printf.printf "Numbers: %s\n" line;
line
|> String.trim
|> String.split_on_char ' '
|> List.map (String.split_on_char ',')
|> List.flatten
|> List.filter_map (function
| "" -> None
| number -> Some (float_of_string number))
|> sparkline
|> print_endline
let () =
"0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;
1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 "
|> String.trim
|> String.split_on_char ';'
|> List.iter print_sparkline
|
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand 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 Strand sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Strand sort.
This is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list.
| #PureBasic | PureBasic | Procedure strandSort(List a())
Protected NewList subList()
Protected NewList results()
While ListSize(a()) > 0
ClearList(subList())
AddElement(subList())
FirstElement(a())
subList() = a()
DeleteElement(a())
ForEach a()
If a() >= subList()
AddElement(subList())
subList() = a()
DeleteElement(a())
EndIf
Next
;merge lists
FirstElement(subList())
If Not FirstElement(results())
;copy all of sublist() to results()
MergeLists(subList(), results(), #PB_List_Last)
Else
Repeat
If subList() < results()
InsertElement(results())
results() = subList()
DeleteElement(subList())
If Not NextElement(subList())
Break
EndIf
ElseIf Not NextElement(results())
;add remainder of sublist() to end of results()
MergeLists(subList(), results(), #PB_List_Last)
Break
EndIf
ForEver
EndIf
Wend
CopyList(results(), a())
EndProcedure
Procedure.s listContents(List a())
Protected output.s
PushListPosition(a())
ForEach a()
output + Str(a()) + ","
Next
PopListPosition(a())
ProcedureReturn Left(output, Len(output) - 1)
EndProcedure
Procedure setupList(List a())
ClearList(a())
Protected elementCount, i
elementCount = Random(5) + 10
For i = 1 To elementCount
AddElement(a())
a() = Random(10) - 5
Next
EndProcedure
If OpenConsole()
NewList sample()
Define i
For i = 1 To 3
setupList(sample())
PrintN("List " + Str(i) + ":")
PrintN(" Before: " + listContents(sample()))
strandSort(sample())
PrintN(" After : " + listContents(sample()))
PrintN("")
Next
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.
Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.
Task Specifics
Given ten males:
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
And ten females:
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
And a complete list of ranked preferences, where the most liked is to the left:
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope
abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan
Use the Gale Shapley algorithm to find a stable set of engagements
Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.
References
The Stable Marriage Problem. (Eloquent description and background information).
Gale-Shapley Algorithm Demonstration.
Another Gale-Shapley Algorithm Demonstration.
Stable Marriage Problem - Numberphile (Video).
Stable Marriage Problem (the math bit) (Video).
The Stable Marriage Problem and School Choice. (Excellent exposition)
| #PicoLisp | PicoLisp | (setq
*Boys (list
(de abe abi eve cath ivy jan dee fay bea hope gay)
(de bob cath hope abi dee eve fay bea jan ivy gay)
(de col hope eve abi dee bea fay ivy gay cath jan)
(de dan ivy fay dee gay hope eve jan bea cath abi)
(de ed jan dee bea cath fay eve abi ivy hope gay)
(de fred bea abi dee gay eve ivy cath jan hope fay)
(de gav gay eve ivy bea cath abi dee hope jan fay)
(de hal abi eve hope fay ivy cath jan bea gay dee)
(de ian hope cath dee gay bea abi fay ivy jan eve)
(de jon abi fay jan gay eve bea dee cath ivy hope) )
*Girls (list
(de bi bob fred jon gav ian abe dan ed col hal)
(de bea bob abe col fred gav dan ian ed jon hal)
(de cath fred bob ed gav hal col ian abe dan jon)
(de dee fred jon col abe ian hal gav dan bob ed)
(de eve jon hal fred dan abe gav col ed ian bob)
(de fay bob abe ed ian jon dan fred gav col hal)
(de gay jon gav hal fred bob abe col ed dan ian)
(de hope gav jon bob abe ian dan hal ed col fred)
(de ivy ian col hal gav fred bob abe ed jon dan)
(de jan ed hal gav abe bob jon col ian fred dan) )
*Couples NIL )
(bind *Boys
(while
(find
'((Boy) (and (val Boy) (not (asoq Boy *Couples))))
*Boys )
(let (Boy @ Girl (pop Boy) Pair (find '((P) (== Girl (cdr P))) *Couples))
(nond
(Pair (push '*Couples (cons Boy Girl))) # Girl is free
((memq Boy (memq (car Pair) (val Girl))) # Girl prefers Boy
(set Pair Boy) ) ) ) ) )
(for Pair *Couples
(prinl (cdr Pair) " is engaged to " (car Pair)) )
(de checkCouples ()
(unless
(filter
'((Pair)
(let (Boy (car Pair) Girl (cdr Pair))
(find
'((B)
(and
(memq Boy (cdr (memq B (val Girl)))) # Girl prefers B
(memq
(cdr (asoq B *Couples)) # and B prefers Girl
(cdr (memq Girl (val B))) )
(prinl
Girl " likes " B " better than " Boy " and "
B " likes " Girl " better than "
(cdr (asoq B *Couples)) ) ) )
(val Girl) ) ) )
*Couples )
(prinl "All marriages are stable") ) )
(checkCouples)
(prinl)
(prinl "Engage fred with abi and jon with bea")
(con (asoq 'fred *Couples) 'abi)
(con (asoq 'jon *Couples) 'bea)
(checkCouples) |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Icon_and_Unicon | Icon and Unicon | procedure main()
stack := [] # new empty stack
push(stack,1) # add item
push(stack,"hello",table(),set(),[],5) # add more items of mixed types in order left to right
y := top(stack) # peek
x := pop(stack) # remove item
write("The stack is ",if isempty(stack) then "empty" else "not empty")
end
procedure isempty(x) #: test if a datum is empty, return the datum or fail (task requirement)
if *x = 0 then return x # in practice just write *x = 0 or *x ~= 0 for is/isn't empty
end
procedure top(x) #: return top element w/o changing stack
return x[1] # in practice, just use x[1]
end |
http://rosettacode.org/wiki/Spiral_matrix | Spiral matrix | Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
Related tasks
Zig-zag matrix
Identity_matrix
Ulam_spiral_(for_primes)
| #Groovy | Groovy | enum Direction {
East([0,1]), South([1,0]), West([0,-1]), North([-1,0]);
private static _n
private final stepDelta
private bound
private Direction(delta) {
stepDelta = delta
}
public static setN(int n) {
Direction._n = n
North.bound = 0
South.bound = n-1
West.bound = 0
East.bound = n-1
}
public List move(i, j) {
def dir = this
def newIJDir = [[i,j],stepDelta].transpose().collect { it.sum() } + dir
if (((North.bound)..(South.bound)).contains(newIJDir[0])
&& ((West.bound)..(East.bound)).contains(newIJDir[1])) {
newIJDir
} else {
(++dir).move(i, j)
}
}
public Object next() {
switch (this) {
case North: West.bound++; return East;
case East: North.bound++; return South;
case South: East.bound--; return West;
case West: South.bound--; return North;
}
}
}
def spiralMatrix = { n ->
if (n < 1) return []
def M = (0..<n).collect { [0]*n }
def i = 0
def j = 0
Direction.n = n
def dir = Direction.East
(0..<(n**2)).each { k ->
M[i][j] = k
(i,j,dir) = (k < (n**2 - 1)) \
? dir.move(i,j) \
: [i,j,dir]
}
M
} |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Ruby | Ruby | import scala._ // Wild card -- all of scala is imported
import scala.{ Predef => _, _ } // Exception, everything except Predef
def f[M[_]] // Higher kinded type parameter
def f(m: M[_]) // Existential type
_ + _ // Anonymous function placeholder parameter
m _ // Eta expansion of method into method value
m(_) // Partial function application
_ => 5 // Discarded parameter
case _ => // Wild card pattern -- matches anything
val (a, _) = (1, 2) // same thing
for (_ <- 1 to 10) // same thing
f(xs: _*) // Sequence xs is passed as multiple parameters to f(ys: T*)
case Seq(xs @ _*) // Identifier xs is bound to the whole matched sequence
var i: Int = _ // Initialization to the default value
def abc_<>! // An underscore must separate alphanumerics from symbols on identifiers
t._2 // Part of a method name, such as tuple getters
var i: Int = _ // Initialization with a default value
for (_ <- 1 to 10) doIt() // Discarded val
def f: T; def f_=(t: T) // Combo for creating mutable f member. |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Scala | Scala | import scala._ // Wild card -- all of scala is imported
import scala.{ Predef => _, _ } // Exception, everything except Predef
def f[M[_]] // Higher kinded type parameter
def f(m: M[_]) // Existential type
_ + _ // Anonymous function placeholder parameter
m _ // Eta expansion of method into method value
m(_) // Partial function application
_ => 5 // Discarded parameter
case _ => // Wild card pattern -- matches anything
val (a, _) = (1, 2) // same thing
for (_ <- 1 to 10) // same thing
f(xs: _*) // Sequence xs is passed as multiple parameters to f(ys: T*)
case Seq(xs @ _*) // Identifier xs is bound to the whole matched sequence
var i: Int = _ // Initialization to the default value
def abc_<>! // An underscore must separate alphanumerics from symbols on identifiers
t._2 // Part of a method name, such as tuple getters
var i: Int = _ // Initialization with a default value
for (_ <- 1 to 10) doIt() // Discarded val
def f: T; def f_=(t: T) // Combo for creating mutable f member. |
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort | Sorting algorithms/Radix 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
Task
Sort an integer array with the radix sort algorithm.
The primary purpose is to complete the characterization of sort algorithms task.
| #AutoHotkey | AutoHotkey | Radix_Sort(data){
loop, parse, data, `,
n := StrLen(A_LoopField)>n?StrLen(A_LoopField):n
loop % n {
bucket := [] , i := A_Index
loop, parse, data, `,
bucket[SubStr(A_LoopField,1-i)] .= (bucket[SubStr(A_LoopField,1-i)]?",":"") A_LoopField
data := ""
for i, v in bucket
data .= (data?",":"") v
}
return data
} |
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort | Sorting algorithms/Patience 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
Sort an array of numbers (of any convenient size) into ascending order using Patience sorting.
Related task
Longest increasing subsequence
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program patienceSort64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Structures */
/********************************************/
/* structure Doublylinkedlist*/
.struct 0
dllist_head: // head node
.struct dllist_head + 8
dllist_tail: // tail node
.struct dllist_tail + 8
dllist_fin:
/* structure Node Doublylinked List*/
.struct 0
NDlist_next: // next element
.struct NDlist_next + 8
NDlist_prev: // previous element
.struct NDlist_prev + 8
NDlist_value: // element value or key
.struct NDlist_value + 8
NDlist_fin:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSortOk: .asciz "Table sorted.\n"
szMessSortNok: .asciz "Table not sorted !!!!!.\n"
sMessResult: .asciz "Value : @ \n"
szCarriageReturn: .asciz "\n"
.align 4
TableNumber: .quad 1,3,11,6,2,-5,9,10,8,4,7
#TableNumber: .quad 10,9,8,7,6,-5,4,3,2,1
.equ NBELEMENTS, (. - TableNumber) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrTableNumber // address number table
mov x1,0 // first element
mov x2,NBELEMENTS // number of élements
bl patienceSort
ldr x0,qAdrTableNumber // address number table
bl displayTable
ldr x0,qAdrTableNumber // address number table
mov x1,NBELEMENTS // number of élements
bl isSorted // control sort
cmp x0,1 // sorted ?
beq 1f
ldr x0,qAdrszMessSortNok // no !! error sort
bl affichageMess
b 100f
1: // yes
ldr x0,qAdrszMessSortOk
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrsZoneConv: .quad sZoneConv
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrTableNumber: .quad TableNumber
qAdrszMessSortOk: .quad szMessSortOk
qAdrszMessSortNok: .quad szMessSortNok
/******************************************************************/
/* control sorted table */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the number of elements > 0 */
/* x0 return 0 if not sorted 1 if sorted */
isSorted:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
mov x2,0
ldr x4,[x0,x2,lsl 3]
1:
add x2,x2,1
cmp x2,x1
bge 99f
ldr x3,[x0,x2, lsl 3]
cmp x3,x4
blt 98f
mov x4,x3
b 1b
98:
mov x0,0 // not sorted
b 100f
99:
mov x0,1 // sorted
100:
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* patience sort */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains first start index
/* x2 contains the number of elements */
patienceSort:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
stp x8,x9,[sp,-16]! // save registers
lsl x9,x2,1 // compute total size of piles (2 list pointer by pile )
lsl x10,x9,3 // 8 bytes by number
sub sp,sp,x10 // reserve place to stack
mov fp,sp // frame pointer = stack
mov x3,0 // index
mov x4,0
1:
str x4,[fp,x3,lsl 3] // init piles area
add x3,x3,1 // increment index
cmp x3,x9
blt 1b
mov x3,0 // index value
mov x4,0 // counter first pile
mov x8,x0 // save table address
2:
ldr x1,[x8,x3,lsl 3] // load value
add x0,fp,x4,lsl 4 // pile address
bl isEmpty
cmp x0,0 // pile empty ?
bne 3f
add x0,fp,x4,lsl 4 // pile address
bl insertHead // insert value x1
b 5f
3:
add x0,fp,x4,lsl 4 // pile address
ldr x5,[x0,dllist_head]
ldr x5,[x5,NDlist_value] // load first list value
cmp x1,x5 // compare value and last value on the pile
blt 4f
add x0,fp,x4,lsl 4 // pile address
bl insertHead // insert value x1
b 5f
4: // value is smaller créate a new pile
add x4,x4,1
add x0,fp,x4,lsl 4 // pile address
bl insertHead // insert value x1
5:
add x3,x3,1 // increment index value
cmp x3,x2 // end
blt 2b // and loop
/* step 2 */
mov x6,0 // index value table
6:
mov x3,0 // index pile
mov x5, 1<<62 // min
7: // search minimum
add x0,fp,x3,lsl 4
bl isEmpty
cmp x0,0
beq 8f
add x0,fp,x3,lsl 4
bl searchMinList
cmp x0,x5 // compare min global
bge 8f
mov x5,x0 // smaller -> store new min
mov x7,x1 // and pointer to min
add x9,fp,x3,lsl 4 // and head list
8:
add x3,x3,1 // next pile
cmp x3,x4 // end ?
ble 7b
str x5,[x8,x6,lsl 3] // store min to table value
mov x0,x9 // and suppress the value in the pile
mov x1,x7
bl suppressNode
add x6,x6,1 // increment index value
cmp x6,x2 // end ?
blt 6b
add sp,sp,x10 // stack alignement
100:
ldp x8,x9,[sp],16 // restaur 2 registers
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* x0 contains the address of table */
displayTable:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x0 // table address
mov x3,0
1: // loop display table
ldr x0,[x2,x3,lsl 3]
ldr x1,qAdrsZoneConv
bl conversion10S // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at // character
bl affichageMess // display message
add x3,x3,1
cmp x3,NBELEMENTS - 1
ble 1b
ldr x0,qAdrszCarriageReturn
bl affichageMess
mov x0,x2
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* list is empty ? */
/******************************************************************/
/* x0 contains the address of the list structure */
/* x0 return 0 if empty else return 1 */
isEmpty:
ldr x0,[x0,#dllist_head]
cmp x0,0
cset x0,ne
ret // return
/******************************************************************/
/* insert value at list head */
/******************************************************************/
/* x0 contains the address of the list structure */
/* x1 contains value */
insertHead:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
mov x4,x0 // save address
mov x0,x1 // value
bl createNode
cmp x0,#-1 // allocation error ?
beq 100f
ldr x2,[x4,#dllist_head] // load address first node
str x2,[x0,#NDlist_next] // store in next pointer on new node
mov x1,#0
str x1,[x0,#NDlist_prev] // store zero in previous pointer on new node
str x0,[x4,#dllist_head] // store address new node in address head list
cmp x2,#0 // address first node is null ?
beq 1f
str x0,[x2,#NDlist_prev] // no store adresse new node in previous pointer
b 100f
1:
str x0,[x4,#dllist_tail] // else store new node in tail address
100:
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* search value minimum */
/******************************************************************/
/* x0 contains the address of the list structure */
/* x0 return min */
/* x1 return address of node */
searchMinList:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
ldr x0,[x0,#dllist_head] // load first node
mov x3,1<<62
mov x1,0
1:
cmp x0,0 // null -> end
beq 99f
ldr x2,[x0,#NDlist_value] // load node value
cmp x2,x3 // min ?
bge 2f
mov x3,x2 // value -> min
mov x1,x0 // store pointer
2:
ldr x0,[x0,#NDlist_next] // load addresse next node
b 1b // and loop
99:
mov x0,x3 // return minimum
100:
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* suppress node */
/******************************************************************/
/* x0 contains the address of the list structure */
/* x1 contains the address to node to suppress */
suppressNode:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
ldr x2,[x1,#NDlist_next] // load addresse next node
ldr x3,[x1,#NDlist_prev] // load addresse prev node
cmp x3,#0
beq 1f
str x2,[x3,#NDlist_next]
b 2f
1:
str x3,[x0,#NDlist_next]
2:
cmp x2,#0
beq 3f
str x3,[x2,#NDlist_prev]
b 100f
3:
str x2,[x0,#NDlist_prev]
100:
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* Create new node */
/******************************************************************/
/* x0 contains the value */
/* x0 return node address or -1 if allocation error*/
createNode:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x8,[sp,-16]! // save registers
mov x4,x0 // save value
// allocation place on the heap
mov x0,0 // allocation place heap
mov x8,BRK // call system 'brk'
svc 0
mov x3,x0 // save address heap for output string
add x0,x0,NDlist_fin // reservation place one element
mov x8,BRK // call system 'brk'
svc #0
cmp x0,-1 // allocation error
beq 100f
mov x0,x3
str x4,[x0,#NDlist_value] // store value
mov x2,0
str x2,[x0,#NDlist_next] // store zero to pointer next
str x2,[x0,#NDlist_prev] // store zero to pointer previous
100:
ldp x4,x8,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort | Sorting algorithms/Permutation 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
Task
Implement a permutation sort, which proceeds by generating the possible permutations
of the input array/list until discovering the sorted one.
Pseudocode:
while not InOrder(list) do
nextPermutation(list)
done
| #Common_Lisp | Common Lisp | (defun factorial (n)
(loop for result = 1 then (* i result)
for i from 2 to n
finally (return result)))
(defun nth-permutation (k sequence)
(if (zerop (length sequence))
(coerce () (type-of sequence))
(let ((seq (etypecase sequence
(vector (copy-seq sequence))
(sequence (coerce sequence 'vector)))))
(loop for j from 2 to (length seq)
do (setq k (truncate (/ k (1- j))))
do (rotatef (aref seq (mod k j))
(aref seq (1- j)))
finally (return (coerce seq (type-of sequence)))))))
(defun sortedp (fn sequence)
(etypecase sequence
(list (loop for previous = #1='#:foo then i
for i in sequence
always (or (eq previous #1#)
(funcall fn i previous))))
;; copypasta
(vector (loop for previous = #1# then i
for i across sequence
always (or (eq previous #1#)
(funcall fn i previous))))))
(defun permutation-sort (fn sequence)
(loop for i below (factorial (length sequence))
for permutation = (nth-permutation i sequence)
when (sortedp fn permutation)
do (return permutation))) |
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort | Sorting algorithms/Pancake 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
Task
Sort an array of integers (of any convenient size) into ascending order using Pancake sorting.
In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so:
Before: 6 7 8 9 2 5 3 4 1
After: 9 8 7 6 2 5 3 4 1
Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it must be the same end for the entire solution. (The end flipped can't be arbitrarily changed.)
Show both the initial, unsorted list and the final sorted list.
(Intermediate steps during sorting are optional.)
Optimizations are optional (but recommended).
Related tasks
Number reversal game
Topswops
Also see
Wikipedia article: pancake sorting.
| #Ada | Ada | with Ada.Text_IO;
procedure Pancake_Sort is
generic
type Element_Type is private;
type Index_Type is range <>;
type Array_Type is array (Index_Type range <>) of Element_Type;
with function ">" (Left, Right : Element_Type) return Boolean is <>;
procedure Pancake_Sort (Data: in out Array_Type);
procedure Pancake_Sort (Data: in out Array_Type) is
procedure Flip (Up_To : in Index_Type) is
Temp : constant Array_Type := Data (Data'First .. Up_To);
begin
for I in Temp'Range loop
Data (I) := Temp (Temp'First + Up_To - I);
end loop;
end Flip;
Max_Index : Index_Type;
begin
for I in reverse Data'First + 1 .. Data'Last loop
Max_Index := Data'First;
for A in Data'First + 1 .. I loop
if Data(A) > Data (Max_Index) then
Max_Index := A;
end if;
end loop;
if Max_Index /= I then
if Max_Index > Data'First then
Flip (Max_Index);
end if;
Flip (I);
end if;
end loop;
end Pancake_Sort;
type Integer_Array is array (Positive range <>) of Integer;
procedure Int_Pancake_Sort is new Pancake_Sort (Integer, Positive, Integer_Array);
Test_Array : Integer_Array := (3, 14, 1, 5, 9, 2, 6, 3);
begin
Int_Pancake_Sort (Test_Array);
for I in Test_Array'Range loop
Ada.Text_IO.Put (Integer'Image (Test_Array (I)));
end loop;
Ada.Text_IO.New_Line;
end Pancake_Sort; |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Nim | Nim | var f = open(r"C:\texts\text.txt") # a raw string, so ``\t`` is no tab |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #OASYS_Assembler | OASYS Assembler | ; Comment (to end of line)
- Introduces a negative number (not used for subtraction)
= Load an include file or define a macro
& Prefix for a method
% Prefix for a global variable
! Prefix for an object
. Prefix for a property
' Prefix for a vocabulary word
? Prefix for a class; check if an object is of this class
* Prefix for a class; create a new object of this class
: Prefix for a label; define the label
/ Prefix for a label; jump if true
\ Prefix for a label; jump if false
| Prefix for a label; jump unconditionally
, Prefix for a local variable or argument
[ Begin a declaration heading or phrase
] End a declaration heading or phrase
( Begin a dispatch method
) End a dispatch method
< Read through a pointer
> Write through a pointer
+ The object that the method was called on
" Begin string literal
{ Begin string literal
~ Special (used for advanced macros)
^ Suffix for pointer types
@ Suffix for object type
# Suffix for integer type
$ Suffix for string type
|
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort | Sorting algorithms/Stooge 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 Stooge sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Show the Stooge Sort for an array of integers.
The Stooge Sort algorithm is as follows:
algorithm stoogesort(array L, i = 0, j = length(L)-1)
if L[j] < L[i] then
L[i] ↔ L[j]
if j - i > 1 then
t := (j - i + 1)/3
stoogesort(L, i , j-t)
stoogesort(L, i+t, j )
stoogesort(L, i , j-t)
return L
| #Euphoria | Euphoria | function stooge(sequence s, integer i, integer j)
object temp
integer t
if compare(s[j], s[i]) < 0 then
temp = s[i]
s[i] = s[j]
s[j] = temp
end if
if j - i > 1 then
t = floor((j - i + 1)/3)
s = stooge(s, i , j-t)
s = stooge(s, i+t, j )
s = stooge(s, i , j-t)
end if
return s
end function
function stoogesort(sequence s)
return stooge(s,1,length(s))
end function
constant s = rand(repeat(1000,10))
? s
? stoogesort(s) |
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort | Sorting algorithms/Sleep 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
In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time.
Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required.
Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
| #Go | Go | package main
import (
"fmt"
"log"
"os"
"strconv"
"time"
)
func main() {
out := make(chan uint64)
for _, a := range os.Args[1:] {
i, err := strconv.ParseUint(a, 10, 64)
if err != nil {
log.Fatal(err)
}
go func(n uint64) {
time.Sleep(time.Duration(n) * time.Millisecond)
out <- n
}(i)
}
for _ = range os.Args[1:] {
fmt.Println(<-out)
}
} |
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort | Sorting algorithms/Sleep 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
In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time.
Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required.
Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
| #Groovy | Groovy |
@Grab(group = 'org.codehaus.gpars', module = 'gpars', version = '1.2.1')
import groovyx.gpars.GParsPool
GParsPool.withPool args.size(), {
args.eachParallel {
sleep(it.toInteger() * 10)
println it
}
}
|
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort | Sorting algorithms/Selection 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
Task
Sort an array (or list) of elements using the Selection sort algorithm.
It works as follows:
First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted.
Its asymptotic complexity is O(n2) making it inefficient on large arrays.
Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM.
No other sorting algorithm has less data movement.
References
Rosetta Code: O (complexity).
Wikipedia: Selection sort.
Wikipedia: [Big O notation].
| #AutoHotkey | AutoHotkey | MsgBox % SelecSort("")
MsgBox % SelecSort("xxx")
MsgBox % SelecSort("3,2,1")
MsgBox % SelecSort("dog,000000,xx,cat,pile,abcde,1,cat,zz,xx,z")
SelecSort(var) { ; SORT COMMA SEPARATED LIST
StringSplit a, var, `, ; make array, size = a0
Loop % a0-1 {
i := A_Index, mn := a%i%, j := m := i
Loop % a0-i { ; find minimum
j++
If (a%j% < mn)
mn := a%j%, m := j
}
t := a%i%, a%i% := a%m%, a%m% := t ; swap first with minimum
}
Loop % a0 ; construct string from sorted array
sorted .= "," . a%A_Index%
Return SubStr(sorted,2) ; drop leading comma
} |
http://rosettacode.org/wiki/Soundex | Soundex | Soundex is an algorithm for creating indices for words based on their pronunciation.
Task
The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling (from the soundex Wikipedia article).
Caution
There is a major issue in many of the implementations concerning the separation of two consonants that have the same soundex code! According to the official Rules [[1]]. So check for instance if Ashcraft is coded to A-261.
If a vowel (A, E, I, O, U) separates two consonants that have the same soundex code, the consonant to the right of the vowel is coded. Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored (see "Side-by-Side" rule above), 2 for the K). Since the vowel "A" separates the Z and K, the K is coded.
If "H" or "W" separate two consonants that have the same soundex code, the consonant to the right of the vowel is not coded. Example: Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 for the F). It is not coded A-226.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
namespace Soundex
{
internal static class Program
{
private static void Main()
{
var testWords = new TestWords
{
{"Soundex", "S532"},
{"Example", "E251"},
{"Sownteks", "S532"},
{"Ekzampul", "E251"},
{"Euler", "E460"},
{"Gauss", "G200"},
{"Hilbert", "H416"},
{"Knuth", "K530"},
{"Lloyd", "L300"},
{"Lukasiewicz", "L222"},
{"Ellery", "E460"},
{"Ghosh", "G200"},
{"Heilbronn", "H416"},
{"Kant", "K530"},
{"Ladd", "L300"},
{"Lissajous", "L222"},
{"Wheaton", "W350"},
{"Burroughs", "B620"},
{"Burrows", "B620"},
{"O'Hara", "O600"},
{"Washington", "W252"},
{"Lee", "L000"},
{"Gutierrez", "G362"},
{"Pfister", "P236"},
{"Jackson", "J250"},
{"Tymczak", "T522"},
{"VanDeusen", "V532"},
{"Ashcraft", "A261"}
};
foreach (var testWord in testWords)
Console.WriteLine("{0} -> {1} ({2})", testWord.Word.PadRight(11), testWord.ActualSoundex,
(testWord.ExpectedSoundex == testWord.ActualSoundex));
}
// List<TestWord> wrapper to make declaration simpler.
private class TestWords : List<TestWord>
{
public void Add(string word, string expectedSoundex)
{
Add(new TestWord(word, expectedSoundex));
}
}
private class TestWord
{
public TestWord(string word, string expectedSoundex)
{
Word = word;
ExpectedSoundex = expectedSoundex;
ActualSoundex = Soundex(word);
}
public string Word { get; private set; }
public string ExpectedSoundex { get; private set; }
public string ActualSoundex { get; private set; }
}
private static string Soundex(string word)
{
const string soundexAlphabet = "0123012#02245501262301#202";
string soundexString = "";
char lastSoundexChar = '?';
word = word.ToUpper();
foreach (var c in from ch in word
where ch >= 'A' &&
ch <= 'Z' &&
soundexString.Length < 4
select ch)
{
char thisSoundexChar = soundexAlphabet[c - 'A'];
if (soundexString.Length == 0)
soundexString += c;
else if (thisSoundexChar == '#')
continue;
else if (thisSoundexChar != '0' &&
thisSoundexChar != lastSoundexChar)
soundexString += thisSoundexChar;
lastSoundexChar = thisSoundexChar;
}
return soundexString.PadRight(4, '0');
}
}
} |
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort | Sorting algorithms/Shell 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
Task
Sort an array of elements using the Shell sort algorithm, a diminishing increment sort.
The Shell sort (also known as Shellsort or Shell's method) is named after its inventor, Donald Shell, who published the algorithm in 1959.
Shell sort is a sequence of interleaved insertion sorts based on an increment sequence.
The increment size is reduced after each pass until the increment size is 1.
With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case".
Any sequence will sort the data as long as it ends in 1, but some work better than others.
Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice.
[1]
Other good sequences are found at the On-Line Encyclopedia of Integer Sequences.
| #Common_Lisp | Common Lisp | (defun gap-insertion-sort (array predicate gap)
(let ((length (length array)))
(if (< length 2) array
(do ((i 1 (1+ i))) ((eql i length) array)
(do ((x (aref array i))
(j i (- j gap)))
((or (< (- j gap) 0)
(not (funcall predicate x (aref array (1- j)))))
(setf (aref array j) x))
(setf (aref array j) (aref array (- j gap))))))))
(defconstant +gaps+
'(1750 701 301 132 57 23 10 4 1)
"The best sequence of gaps, according to Marcin Ciura.")
(defun shell-sort (array predicate &optional (gaps +gaps+))
(assert (eql 1 (car (last gaps))) (gaps)
"Last gap of ~w is not 1." gaps)
(dolist (gap gaps array)
(gap-insertion-sort array predicate gap))) |
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a sparkline-type bar graph of the values on a single line of output.
The eight characters: '▁▂▃▄▅▆▇█'
(Unicode values U+2581 through U+2588).
Use your program to show sparklines for the following input,
here on this page:
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5
(note the mix of separators in this second case)!
Notes
A space is not part of the generated sparkline.
The sparkline may be accompanied by simple statistics of the data such as its range.
A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:
"0, 1, 19, 20" -> ▁▁██
(Aiming to use just two spark levels)
"0, 999, 4000, 4999, 7000, 7999" -> ▁▁▅▅██
(Aiming to use just three spark levels)
It may be helpful to include these cases in output tests.
You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.
| #Perl | Perl | binmode(STDOUT, ":utf8");
our @sparks=map {chr} 0x2581 .. 0x2588;
sub sparkline(@) {
my @n=map {0+$_} grep {length} @_ or return "";
my($min,$max)=($n[0])x2;
if (@n>1) {
for (@n[1..$#n]) {
if ($_<$min) { $min=$_ }
elsif ($_>$max) { $max=$_ }
}
}
my $sparkline="";
for(@n) {
my $height=int( $max==$min ? @sparks/2 : ($_-$min)/($max-$min)*@sparks );
$height=$#sparks if $height>$#sparks;
$sparkline.=$sparks[$height];
}
my $summary=sprintf "%d values; range %s..%s", scalar(@n), $min, $max;
return wantarray ? ($summary, "\n", $sparkline, "\n") : $sparkline;
}
# one number per line
# print sparkline( <> );
# in scalar context, get just the sparkline without summary or trailing newline
# my $sl=sparkline( <> ); print $sl;
# one sparkline per line
print sparkline( split /[\s,]+/ ) while <>;
|
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand 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 Strand sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Strand sort.
This is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list.
| #Python | Python | def merge_list(a, b):
out = []
while len(a) and len(b):
if a[0] < b[0]:
out.append(a.pop(0))
else:
out.append(b.pop(0))
out += a
out += b
return out
def strand(a):
i, s = 0, [a.pop(0)]
while i < len(a):
if a[i] > s[-1]:
s.append(a.pop(i))
else:
i += 1
return s
def strand_sort(a):
out = strand(a)
while len(a):
out = merge_list(out, strand(a))
return out
print strand_sort([1, 6, 3, 2, 1, 7, 5, 3]) |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.
Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.
Task Specifics
Given ten males:
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
And ten females:
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
And a complete list of ranked preferences, where the most liked is to the left:
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope
abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan
Use the Gale Shapley algorithm to find a stable set of engagements
Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.
References
The Stable Marriage Problem. (Eloquent description and background information).
Gale-Shapley Algorithm Demonstration.
Another Gale-Shapley Algorithm Demonstration.
Stable Marriage Problem - Numberphile (Video).
Stable Marriage Problem (the math bit) (Video).
The Stable Marriage Problem and School Choice. (Excellent exposition)
| #Prolog | Prolog | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% facts
prefere(abe,[ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay]).
prefere( bob,[ cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay]).
prefere( col,[ hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan]).
prefere( dan,[ ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi]).
prefere( ed,[ jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay]).
prefere( fred,[ bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay]).
prefere( gav,[ gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay]).
prefere( hal,[ abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee]).
prefere( ian,[ hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve]).
prefere( jon,[ abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope]).
prefere( abi,[ bob, fred, jon, gav, ian, abe, dan, ed, col, hal]).
prefere( bea,[ bob, abe, col, fred, gav, dan, ian, ed, jon, hal]).
prefere( cath,[ fred, bob, ed, gav, hal, col, ian, abe, dan, jon]).
prefere( dee,[ fred, jon, col, abe, ian, hal, gav, dan, bob, ed]).
prefere( eve,[ jon, hal, fred, dan, abe, gav, col, ed, ian, bob]).
prefere( fay,[ bob, abe, ed, ian, jon, dan, fred, gav, col, hal]).
prefere( gay,[ jon, gav, hal, fred, bob, abe, col, ed, dan, ian]).
prefere( hope,[ gav, jon, bob, abe, ian, dan, hal, ed, col, fred]).
prefere( ivy,[ ian, col, hal, gav, fred, bob, abe, ed, jon, dan]).
prefere( jan,[ ed, hal, gav, abe, bob, jon, col, ian, fred, dan]).
man(abe).
man(bob).
man(col).
man(dan).
man(ed).
man(fred).
man(gav).
man(hal).
man(ian).
man(jon).
woman(abi).
woman(bea).
woman(cath).
woman(dee).
woman(eve).
woman(fay).
woman(gay).
woman(hope).
woman(ivy).
woman(jan).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% rules
stable_mariage :-
new(LstMan, chain),
forall(man(X),
( prefere(X, Lst),
new(P, man(X, Lst)),
send(LstMan, append, P))),
new(LstWoman, chain),
forall(woman(X),
( prefere(X, Lst),
new(P, woman(X, Lst)),
send(LstWoman, append, P))),
send(LstMan, for_all, message(@arg1, init_liste, LstWoman)),
send(LstWoman, for_all, message(@arg1, init_liste, LstMan)),
round(LstMan, LstWoman),
new(LstCouple, chain),
% creation of the couple.
send(LstWoman, for_all, and(message(@prolog, create_couple, @arg1, LstCouple),
message(@pce, write_ln, @arg1?name, with, @arg1?elu?name))),
nl,
% test of the stability of couples
stability(LstCouple),
nl,
% Perturbation of couples
get(LstCouple, size, Len),
get_two_random_couples(Len, V1, V2),
get(LstCouple, nth0, V1, C1),
get(LstCouple, nth0, V2, C2),
new(NC1, tuple(C1?first, C2?second)),
new(NC2, tuple(C2?first, C1?second)),
send(LstCouple, nth0, V1, NC1),
send(LstCouple, nth0, V2, NC2),
send(@pce, write_ln, 'perturbation of couples'),
send(@pce, write_ln, NC1?second, with, NC1?first),
send(@pce, write_ln, NC2?second, with, NC2?first),
nl,
stability(LstCouple).
get_two_random_couples(Len, C1, C2) :-
C1 is random(Len),
repeat,
C2 is random(Len),
C1 \= C2.
create_couple(Woman, LstCouple ) :-
send(LstCouple, append, new(_, tuple(Woman?elu?name, Woman?name))).
% iterations of the algorithm
round(LstMan, LstWoman) :-
send(LstMan, for_some, message(@arg1, propose)),
send(LstWoman, for_some, message(@arg1, dispose)),
( \+send(LstWoman, for_all, @arg1?status == maybe)
->
round(LstMan, LstWoman)
;
true
).
:-pce_begin_class(person, object, "description of a person").
variable(name, object, both, "name of the person").
variable(preference, chain, both, "list of priority").
variable(status, object, both, "statut of engagement : maybe / free").
initialise(P, Name, Pref) :->
send(P, send_super, initialise),
send(P, slot, name, Name),
send(P, slot, preference, Pref),
send(P, slot, status, free).
% reception of the list of partners
init_liste(P, Lst) :->
% we replace the list of name of partners
% with the list of persons partners.
new(NLP, chain),
get(P, slot, preference, LP),
send(LP, for_all, message(@prolog, find_person,@arg1, Lst, NLP)),
send(P, slot, preference, NLP).
:- pce_end_class(person).
find_person(Name, LstPerson, LstPref) :-
get(LstPerson, find, @arg1?name == Name, Elem),
send(LstPref, append, Elem).
:-pce_begin_class(man, person, "description of a man").
initialise(P, Name, Pref) :->
send(P, send_super, initialise, Name, Pref).
% a man propose "la botte" to a woman
propose(P) :->
get(P, slot, status, free),
get(P, slot, preference, XPref),
get(XPref, delete_head, Pref),
send(P, slot, preference, XPref),
send(Pref, proposition, P).
refuse(P) :->
send(P, slot, status, free).
accept(P) :->
send(P, slot, status, maybe).
:- pce_end_class(man).
:-pce_begin_class(woman, person, "description of a woman").
variable(elu, object, both, "name of the elu").
variable(contact, chain, both, "men that have contact this woman").
initialise(P, Name, Pref) :->
send(P, send_super, initialise, Name, Pref),
send(P, slot, contact, new(_, chain)),
send(P, slot, elu, @nil).
% a woman decide Maybe/No
dispose(P) :->
get(P, slot, contact, Contact),
get(P, slot, elu, Elu),
( Elu \= @nil
->
send(Contact, append, Elu)
;
true),
new(R, chain),
send(Contact, for_all, message(P, fetch, @arg1, R)),
send(R, sort, ?(@arg1?first, compare, @arg2?first)),
get(R, delete_head, Tete),
send(Tete?second, accept),
send(P, slot, status, maybe),
send(P, slot, elu, Tete?second),
send(R, for_some, message(@arg1?second, refuse)),
send(P, slot, contact, new(_, chain)) .
% looking for the person of the given name Contact
% Adding it in the chain Chain
fetch(P, Contact, Chain) :->
get(P, slot, preference, Lst),
get(Lst, find, @arg1?name == Contact?name, Elem),
get(Lst, index, Elem, Ind),
send(Chain, append, new(_, tuple(Ind, Contact))).
% a woman receive a proposition from a man
proposition(P, Name) :->
get(P, slot, contact, C),
send(C, append, Name),
send(P, slot, contact, C).
:- pce_end_class(woman).
% computation of the stability od couple
stability(LstCouple) :-
chain_list(LstCouple, LstPceCouple),
maplist(transform, LstPceCouple, PrologLstCouple),
study_couples(PrologLstCouple, [], UnstableCouple),
( UnstableCouple = []
->
writeln('Couples are stable')
;
sort(UnstableCouple, SortUnstableCouple),
writeln('Unstable couples are'),
maplist(print_unstable_couple, SortUnstableCouple),
nl
).
print_unstable_couple((C1, C2)) :-
format('~w and ~w~n', [C1, C2]).
transform(PceCouple, couple(First, Second)):-
get(PceCouple?first, value, First),
get(PceCouple?second, value, Second).
study_couples([], UnstableCouple, UnstableCouple).
study_couples([H | T], CurrentUnstableCouple, UnstableCouple):-
include(unstable_couple(H), T, Lst),
( Lst \= []
->
maplist(build_one_couple(H), Lst, Lst1),
append(CurrentUnstableCouple, Lst1,CurrentUnstableCouple1)
;
CurrentUnstableCouple1 = CurrentUnstableCouple
),
study_couples(T, CurrentUnstableCouple1, UnstableCouple).
build_one_couple(C1, C2, (C1, C2)).
unstable_couple(couple(X1, Y1), couple(X2, Y2)) :-
prefere(X1, PX1),
prefere(X2, PX2),
prefere(Y1, PY1),
prefere(Y2, PY2),
% index of women for X1
nth0(IY12, PX1, Y2),
nth0(IY11, PX1, Y1),
% index of men for Y2
nth0(IX21, PY2, X1),
nth0(IX22, PY2, X2),
% index of women for X2
nth0(IY21, PX2, Y1),
nth0(IY22, PX2, Y2),
% index of men for Y1
nth0(IX11, PY1, X1),
nth0(IX12, PY1, X2),
% A couple is unstable
( (IY12 < IY11 , IX21 < IX22);
(IY21 < IY22 , IX12 < IX11)).
|
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Io | Io | Node := Object clone do(
next := nil
obj := nil
)
Stack := Object clone do(
node := nil
pop := method(
obj := node obj
node = node next
obj
)
push := method(obj,
nn := Node clone
nn obj = obj
nn next = self node
self node = nn
)
) |
http://rosettacode.org/wiki/Spiral_matrix | Spiral matrix | Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
Related tasks
Zig-zag matrix
Identity_matrix
Ulam_spiral_(for_primes)
| #Haskell | Haskell | import Data.List
import Control.Monad
grade xs = map snd. sort $ zip xs [0..]
values n = cycle [1,n,-1,-n]
counts n = (n:).concatMap (ap (:) return) $ [n-1,n-2..1]
reshape n = unfoldr (\xs -> if null xs then Nothing else Just (splitAt n xs))
spiral n = reshape n . grade. scanl1 (+). concat $ zipWith replicate (counts n) (values n)
displayRow = putStrLn . intercalate " " . map show
main = mapM displayRow $ spiral 5 |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Smalltalk | Smalltalk | Smalltalk keys |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Tcl | Tcl | # contains arguments passed to the ursa
# interpreter on the command line
string<> args
# iodevice that points to the console by default
iodevice console
# contains "\n"
string endl
# represents false
boolean false
# represents true
boolean true |
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort | Sorting algorithms/Radix 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
Task
Sort an integer array with the radix sort algorithm.
The primary purpose is to complete the characterization of sort algorithms task.
| #B4X | B4X | Sub RadixSort (Old() As Int)
Dim i, j As Int
Dim tmp(Old.Length) As Int
For shift = 31 To 0 Step - 1
j = 0
For i = 0 To Old.Length - 1
Dim move As Boolean = Bit.ShiftLeft(Old(i), shift) >= 0
If (shift = 0 And move = False) Or (shift <> 0 And move) Then
Old(i - j) = Old(i)
Else
tmp(j) = Old(i)
j = j + 1
End If
Next
Bit.ArrayCopy(tmp, 0, Old, Old.Length - j, j)
Next
End Sub
Sub Test
Dim arr() As Int = Array As Int(34, 23, 54, -123, 543, 123)
RadixSort(arr)
For Each i As Int In arr
Log(i)
Next
End Sub |
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort | Sorting algorithms/Radix 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
Task
Sort an integer array with the radix sort algorithm.
The primary purpose is to complete the characterization of sort algorithms task.
| #BBC_BASIC | BBC BASIC | DIM test%(9)
test%() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
PROCradixsort(test%(), 10, 10)
FOR i% = 0 TO 9
PRINT test%(i%) ;
NEXT
PRINT
END
DEF PROCradixsort(a%(), n%, r%)
LOCAL d%, e%, i%, l%, m%, b%(), bucket%()
DIM b%(n%-1), bucket%(r%-1)
FOR i% = 0 TO n%-1
IF a%(i%) < l% l% = a%(i%)
IF a%(i%) > m% m% = a%(i%)
NEXT
a%() -= l%
m% -= l%
e% = 1
WHILE m% DIV e%
bucket%() = 0
FOR i% = 0 TO n%-1
bucket%(a%(i%) DIV e% MOD r%) += 1
NEXT
FOR i% = 1 TO r%-1
bucket%(i%) += bucket%(i% - 1)
NEXT
FOR i% = n%-1 TO 0 STEP -1
d% = a%(i%) DIV e% MOD r%
bucket%(d%) -= 1
b%(bucket%(d%)) = a%(i%)
NEXT
a%() = b%()
e% *= r%
ENDWHILE
a%() += l%
ENDPROC |
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort | Sorting algorithms/Quicksort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other 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 Quicksort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Sort an array (or list) elements using the quicksort algorithm.
The elements must have a strict weak 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.
Quicksort, also known as partition-exchange sort, uses these steps.
Choose any element of the array to be the pivot.
Divide all other elements (except the pivot) into two partitions.
All elements less than the pivot must be in the first partition.
All elements greater than the pivot must be in the second partition.
Use recursion to sort both partitions.
Join the first sorted partition, the pivot, and the second sorted partition.
The best pivot creates partitions of equal length (or lengths differing by 1).
The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array).
The run-time of Quicksort ranges from O(n log n) with the best pivots, to O(n2) with the worst pivots, where n is the number of elements in the array.
This is a simple quicksort algorithm, adapted from Wikipedia.
function quicksort(array)
less, equal, greater := three empty arrays
if length(array) > 1
pivot := select any element of array
for each x in array
if x < pivot then add x to less
if x = pivot then add x to equal
if x > pivot then add x to greater
quicksort(less)
quicksort(greater)
array := concatenate(less, equal, greater)
A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays.
function quicksort(array)
if length(array) > 1
pivot := select any element of array
left := first index of array
right := last index of array
while left ≤ right
while array[left] < pivot
left := left + 1
while array[right] > pivot
right := right - 1
if left ≤ right
swap array[left] with array[right]
left := left + 1
right := right - 1
quicksort(array from first index to right)
quicksort(array from left to last index)
Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with merge sort, because both sorts have an average time of O(n log n).
"On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html
Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end.
Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort.
Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase.
With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention!
This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
| #11l | 11l | F _quicksort(&array, start, stop) -> N
I stop - start > 0
V pivot = array[start]
V left = start
V right = stop
L left <= right
L array[left] < pivot
left++
L array[right] > pivot
right--
I left <= right
swap(&array[left], &array[right])
left++
right--
_quicksort(&array, start, right)
_quicksort(&array, left, stop)
F quicksort(&array)
_quicksort(&array, 0, array.len - 1)
V arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
quicksort(&arr)
print(arr) |
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort | Sorting algorithms/Patience 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
Sort an array of numbers (of any convenient size) into ascending order using Patience sorting.
Related task
Longest increasing subsequence
| #Ada | Ada | ----------------------------------------------------------------------
with Ada.Text_IO;
procedure patience_sort_task is
use Ada.Text_IO;
function next_power_of_two
(n : in Natural)
return Positive is
-- This need not be a fast implementation.
pow2 : Positive;
begin
pow2 := 1;
while pow2 < n loop
pow2 := pow2 + pow2;
end loop;
return pow2;
end next_power_of_two;
generic
type t is private;
type t_array is array (Integer range <>) of t;
type sorted_t_indices is array (Integer range <>) of Integer;
procedure patience_sort
(less : access function
(x, y : t)
return Boolean;
ifirst : in Integer;
ilast : in Integer;
arr : in t_array;
sorted : out sorted_t_indices);
procedure patience_sort
(less : access function
(x, y : t)
return Boolean;
ifirst : in Integer;
ilast : in Integer;
arr : in t_array;
sorted : out sorted_t_indices) is
num_piles : Integer;
piles : array (1 .. ilast - ifirst + 1) of Integer :=
(others => 0);
links : array (1 .. ilast - ifirst + 1) of Integer :=
(others => 0);
function find_pile
(q : in Positive)
return Positive is
--
-- Bottenbruch search for the leftmost pile whose top is greater
-- than or equal to some element x. Return an index such that:
--
-- * if x is greater than the top element at the far right, then
-- the index returned will be num-piles.
--
-- * otherwise, x is greater than every top element to the left
-- of index, and less than or equal to the top elements at
-- index and to the right of index.
--
-- References:
--
-- * H. Bottenbruch, "Structure and use of ALGOL 60", Journal of
-- the ACM, Volume 9, Issue 2, April 1962, pp.161-221.
-- https://doi.org/10.1145/321119.321120
--
-- The general algorithm is described on pages 214 and 215.
--
-- * https://en.wikipedia.org/w/index.php?title=Binary_search_algorithm&oldid=1062988272#Alternative_procedure
--
index : Positive;
i, j, k : Natural;
begin
if num_piles = 0 then
index := 1;
else
j := 0;
k := num_piles - 1;
while j /= k loop
i := (j + k) / 2;
if less
(arr (piles (j + 1) + ifirst - 1), arr (q + ifirst - 1))
then
j := i + 1;
else
k := i;
end if;
end loop;
if j = num_piles - 1 then
if less
(arr (piles (j + 1) + ifirst - 1), arr (q + ifirst - 1))
then
-- A new pile is needed.
j := j + 1;
end if;
end if;
index := j + 1;
end if;
return index;
end find_pile;
procedure deal is
i : Positive;
begin
for q in links'range loop
i := find_pile (q);
links (q) := piles (i);
piles (i) := q;
num_piles := Integer'max (num_piles, i);
end loop;
end deal;
procedure k_way_merge is
--
-- k-way merge by tournament tree.
--
-- See Knuth, volume 3, and also
-- https://en.wikipedia.org/w/index.php?title=K-way_merge_algorithm&oldid=1047851465#Tournament_Tree
--
-- However, I store a winners tree instead of the recommended
-- losers tree. If the tree were stored as linked nodes, it
-- would probably be more efficient to store a losers
-- tree. However, I am storing the tree as an array, and one
-- can find an opponent quickly by simply toggling the least
-- significant bit of a competitor's array index.
--
total_external_nodes : Positive;
total_nodes : Positive;
begin
total_external_nodes := next_power_of_two (num_piles);
total_nodes := (2 * total_external_nodes) - 1;
declare
-- In Fortran I had the length-2 dimension come first, to
-- take some small advantage of column-major order. The
-- recommendation for Ada compilers, however, is to use
-- row-major order. So I have reversed the order.
winners : array (1 .. total_nodes, 1 .. 2) of Integer :=
(others => (0, 0));
function find_opponent
(i : Natural)
return Natural is
begin
return (if i rem 2 = 0 then i + 1 else i - 1);
end find_opponent;
function play_game
(i : Positive)
return Positive is
j, iwinner : Positive;
begin
j := find_opponent (i);
if winners (i, 1) = 0 then
iwinner := j;
elsif winners (j, 1) = 0 then
iwinner := i;
elsif less
(arr (winners (j, 1) + ifirst - 1),
arr (winners (i, 1) + ifirst - 1))
then
iwinner := j;
else
iwinner := i;
end if;
return iwinner;
end play_game;
procedure replay_games
(i : Positive) is
j, iwinner : Positive;
begin
j := i;
while j /= 1 loop
iwinner := play_game (j);
j := j / 2;
winners (j, 1) := winners (iwinner, 1);
winners (j, 2) := winners (iwinner, 2);
end loop;
end replay_games;
procedure build_tree is
istart, i, iwinner : Positive;
begin
for i in 1 .. total_external_nodes loop
-- Record which pile a winner will have come from.
winners (total_external_nodes - 1 + i, 2) := i;
end loop;
for i in 1 .. num_piles loop
-- The top of each pile becomes a starting competitor.
winners (total_external_nodes + i - 1, 1) := piles (i);
end loop;
for i in 1 .. num_piles loop
-- Discard the top of each pile
piles (i) := links (piles (i));
end loop;
istart := total_external_nodes;
while istart /= 1 loop
i := istart;
while i <= (2 * istart) - 1 loop
iwinner := play_game (i);
winners (i / 2, 1) := winners (iwinner, 1);
winners (i / 2, 2) := winners (iwinner, 2);
i := i + 2;
end loop;
istart := istart / 2;
end loop;
end build_tree;
isorted, i, next : Integer;
begin
build_tree;
isorted := 0;
while winners (1, 1) /= 0 loop
sorted (sorted'first + isorted) :=
winners (1, 1) + ifirst - 1;
isorted := isorted + 1;
i := winners (1, 2);
next := piles (i); -- The next top of pile i.
if next /= 0 then
piles (i) := links (next); -- Drop that top.
end if;
i := (total_nodes / 2) + i;
winners (i, 1) := next;
replay_games (i);
end loop;
end;
end k_way_merge;
begin
deal;
k_way_merge;
end patience_sort;
begin
-- A demonstration.
declare
type integer_array is array (Integer range <>) of Integer;
procedure integer_patience_sort is new patience_sort
(Integer, integer_array, integer_array);
subtype int25_array is integer_array (1 .. 25);
example_numbers : constant int25_array :=
(22, 15, 98, 82, 22, 4, 58, 70, 80, 38, 49, 48, 46, 54, 93, 8,
54, 2, 72, 84, 86, 76, 53, 37, 90);
sorted_numbers : int25_array := (others => 0);
function less
(x, y : Integer)
return Boolean is
begin
return (x < y);
end less;
begin
integer_patience_sort
(less'access, example_numbers'first, example_numbers'last,
example_numbers, sorted_numbers);
Put ("unsorted ");
for i of example_numbers loop
Put (Integer'image (i));
end loop;
Put_Line ("");
Put ("sorted ");
for i of sorted_numbers loop
Put (Integer'image (example_numbers (i)));
end loop;
Put_Line ("");
end;
end patience_sort_task;
---------------------------------------------------------------------- |
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort | Sorting algorithms/Permutation 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
Task
Implement a permutation sort, which proceeds by generating the possible permutations
of the input array/list until discovering the sorted one.
Pseudocode:
while not InOrder(list) do
nextPermutation(list)
done
| #Crystal | Crystal | def sorted?(items : Array)
prev = items[0]
items.each do |item|
if item < prev
return false
end
prev = item
end
return true
end
def permutation_sort(items : Array)
items.each_permutation do |permutation|
if sorted?(permutation)
return permutation
end
end
end |
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort | Sorting algorithms/Permutation 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
Task
Implement a permutation sort, which proceeds by generating the possible permutations
of the input array/list until discovering the sorted one.
Pseudocode:
while not InOrder(list) do
nextPermutation(list)
done
| #D | D | import std.stdio, std.algorithm, permutations2;
void permutationSort(T)(T[] items) pure nothrow @safe @nogc {
foreach (const perm; items.permutations!false)
if (perm.isSorted)
break;
}
void main() {
auto data = [2, 7, 4, 3, 5, 1, 0, 9, 8, 6, -1];
data.permutationSort;
data.writeln;
} |
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort | Sorting algorithms/Pancake 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
Task
Sort an array of integers (of any convenient size) into ascending order using Pancake sorting.
In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so:
Before: 6 7 8 9 2 5 3 4 1
After: 9 8 7 6 2 5 3 4 1
Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it must be the same end for the entire solution. (The end flipped can't be arbitrarily changed.)
Show both the initial, unsorted list and the final sorted list.
(Intermediate steps during sorting are optional.)
Optimizations are optional (but recommended).
Related tasks
Number reversal game
Topswops
Also see
Wikipedia article: pancake sorting.
| #ALGOL_68 | ALGOL 68 | PROC flip = ([]INT s, INT n) []INT:
BEGIN
[UPB s]INT ss := s;
INT temp;
FOR i TO n OVER 2 DO
temp := ss[i];
ss[i] := ss[n-i+1];
ss[n-i+1] := temp
OD;
ss
END;
PROC pancake sort = ([]INT s) []INT:
BEGIN
INT m;
[UPB s]INT ss := s;
FOR i FROM UPB s DOWNTO 2 DO
m := 1;
FOR j FROM 2 TO i DO
IF ss[j] > ss[m] THEN
m := j
FI
OD;
IF m < i THEN
IF m > 1 THEN
ss := flip (ss,m)
FI;
ss := flip (ss,i)
FI
OD;
ss
END;
[10]INT s;
FOR i TO UPB s DO
s[i] := ENTIER (next random * 100-50)
OD;
printf (($"Pancake sort demonstration"l$));
printf (($"unsorted: "10(g(4) )l$, s));
printf (($"sorted: "10(g(4) )l$, pancake sort(s)))
|
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Objeck | Objeck |
\b //Backspace
\n //Line Feed
\r //Carriage Return
\t //Tab
\0 //Null
\' //Single Quote
\" //Double Q
|
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #OCaml | OCaml | \\ backslash
\" double quote
\' single quote
\n line feed
\r carriage return
\t tab
\b backspace
\ (backslash followed by a space) space
\DDD where D is a decimal digit; the character with code DDD in decimal
\xHH where H is a hex digit; the character with code HH in hex
|
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort | Sorting algorithms/Stooge 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 Stooge sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Show the Stooge Sort for an array of integers.
The Stooge Sort algorithm is as follows:
algorithm stoogesort(array L, i = 0, j = length(L)-1)
if L[j] < L[i] then
L[i] ↔ L[j]
if j - i > 1 then
t := (j - i + 1)/3
stoogesort(L, i , j-t)
stoogesort(L, i+t, j )
stoogesort(L, i , j-t)
return L
| #Factor | Factor | USING: kernel locals math prettyprint sequences ;
IN: rosetta-code.stooge-sort
<PRIVATE
:: (stooge-sort) ( seq i j -- )
j i [ seq nth ] bi@ < [
j i seq exchange
] when
j i - 1 > [
j i - 1 + 3 /i :> t
seq i j t - (stooge-sort)
seq i t + j (stooge-sort)
seq i j t - (stooge-sort)
] when ;
PRIVATE>
: stooge-sort ( seq -- sortedseq )
[ clone dup ] [ drop 0 ] [ length 1 - ] tri (stooge-sort) ;
: stooge-sort-demo ( -- )
{ 1 4 5 3 -6 3 7 10 -2 -5 } stooge-sort . ;
MAIN: stooge-sort-demo |
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort | Sorting algorithms/Stooge 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 Stooge sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Show the Stooge Sort for an array of integers.
The Stooge Sort algorithm is as follows:
algorithm stoogesort(array L, i = 0, j = length(L)-1)
if L[j] < L[i] then
L[i] ↔ L[j]
if j - i > 1 then
t := (j - i + 1)/3
stoogesort(L, i , j-t)
stoogesort(L, i+t, j )
stoogesort(L, i , j-t)
return L
| #Fortran | Fortran | program Stooge
implicit none
integer :: i
integer :: array(50) = (/ (i, i = 50, 1, -1) /) ! Reverse sorted array
call Stoogesort(array)
write(*,"(10i5)") array
contains
recursive subroutine Stoogesort(a)
integer, intent(in out) :: a(:)
integer :: j, t, temp
j = size(a)
if(a(j) < a(1)) then
temp = a(j)
a(j) = a(1)
a(1) = temp
end if
if(j > 2) then
t = j / 3
call Stoogesort(a(1:j-t))
call Stoogesort(a(1+t:j))
call Stoogesort(a(1:j-t))
end if
end subroutine
end program |
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort | Sorting algorithms/Sleep 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
In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time.
Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required.
Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
| #Haskell | Haskell | import System.Environment
import Control.Concurrent
import Control.Monad
sleepSort :: [Int] -> IO ()
sleepSort values = do
chan <- newChan
forM_ values (\time -> forkIO (threadDelay (50000 * time) >> writeChan chan time))
forM_ values (\_ -> readChan chan >>= print)
main :: IO ()
main = getArgs >>= sleepSort . map read |
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort | Sorting algorithms/Sleep 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
In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time.
Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required.
Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
| #Icon_and_Unicon | Icon and Unicon | procedure main(A)
every insert(t:=set(),mkThread(t,!A))
every spawn(!t) # start threads as closely grouped as possible
while (*t > 0) do write(<<@)
end
procedure mkThread(t,n) # 10ms delay scale factor
return create (delay(n*10),delete(t,¤t),n@>&main)
end |
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort | Sorting algorithms/Selection 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
Task
Sort an array (or list) of elements using the Selection sort algorithm.
It works as follows:
First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted.
Its asymptotic complexity is O(n2) making it inefficient on large arrays.
Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM.
No other sorting algorithm has less data movement.
References
Rosetta Code: O (complexity).
Wikipedia: Selection sort.
Wikipedia: [Big O notation].
| #AWK | AWK | function getminindex(gl, gi, gs)
{
min = gl[gi]
gm = gi
for(gj=gi; gj <= gs; gj++) {
if ( gl[gj] < min ) {
min = gl[gj]
gm = gj
}
}
return gm
}
{
line[NR] = $0
}
END { # sort it with selection sort
for(i=1; i <= NR; i++) {
mi = getminindex(line, i, NR)
t = line[i]
line[i] = line[mi];
line[mi] = t
}
#print it
for(i=1; i <= NR; i++) {
print line[i]
}
} |
http://rosettacode.org/wiki/Soundex | Soundex | Soundex is an algorithm for creating indices for words based on their pronunciation.
Task
The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling (from the soundex Wikipedia article).
Caution
There is a major issue in many of the implementations concerning the separation of two consonants that have the same soundex code! According to the official Rules [[1]]. So check for instance if Ashcraft is coded to A-261.
If a vowel (A, E, I, O, U) separates two consonants that have the same soundex code, the consonant to the right of the vowel is coded. Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored (see "Side-by-Side" rule above), 2 for the K). Since the vowel "A" separates the Z and K, the K is coded.
If "H" or "W" separate two consonants that have the same soundex code, the consonant to the right of the vowel is not coded. Example: Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 for the F). It is not coded A-226.
| #C.2B.2B | C++ |
#include <iostream> // required for debug code in main() only
#include <iomanip> // required for debug code in main() only
#include <string>
std::string soundex( char const* s )
{
static char const code[] = { 0, -1, 1, 2, 3, -1, 1, 2, 0, -1, 2, 2, 4, 5, 5, -1, 1, 2, 6, 2, 3, -1, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0 };
if( !s || !*s )
return std::string();
std::string out( "0000" );
out[0] = (*s >= 'a' && *s <= 'z') ? *s - ('a' - 'A') : *s;
++s;
char prev = code[out[0] & 0x1F]; // first letter, though not coded, can still affect next letter: Pfister
for( unsigned i = 1; *s && i < 4; ++s )
{
if( (*s & 0xC0) != 0x40 ) // process only letters in range [0x40 - 0x7F]
continue;
auto const c = code[*s & 0x1F];
if( c == prev )
continue;
if( c == -1 )
prev = 0; // vowel as separator
else if( c )
{
out[i] = c + '0';
++i;
prev = c;
}
}
return out;
}
int main()
{
static char const * const names[][2] =
{
{"Ashcraft", "A261"},
{"Burroughs", "B620"},
{"Burrows", "B620"},
{"Ekzampul", "E251"},
{"Ellery", "E460"},
{"Euler", "E460"},
{"Example", "E251"},
{"Gauss", "G200"},
{"Ghosh", "G200"},
{"Gutierrez", "G362"},
{"Heilbronn", "H416"},
{"Hilbert", "H416"},
{"Jackson", "J250"},
{"Kant", "K530"},
{"Knuth", "K530"},
{"Ladd", "L300"},
{"Lee", "L000"},
{"Lissajous", "L222"},
{"Lloyd", "L300"},
{"Lukasiewicz", "L222"},
{"O'Hara", "O600"},
{"Pfister", "P236"},
{"Soundex", "S532"},
{"Sownteks", "S532"},
{"Tymczak", "T522"},
{"VanDeusen", "V532"},
{"Washington", "W252"},
{"Wheaton", "W350"}
};
for( auto const& name : names )
{
auto const sdx = soundex( name[0] );
std::cout << std::left << std::setw( 16 ) << name[0] << std::setw( 8 ) << sdx << (sdx == name[1] ? " ok" : " ERROR") << std::endl;
}
return 0;
}
|
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort | Sorting algorithms/Shell 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
Task
Sort an array of elements using the Shell sort algorithm, a diminishing increment sort.
The Shell sort (also known as Shellsort or Shell's method) is named after its inventor, Donald Shell, who published the algorithm in 1959.
Shell sort is a sequence of interleaved insertion sorts based on an increment sequence.
The increment size is reduced after each pass until the increment size is 1.
With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case".
Any sequence will sort the data as long as it ends in 1, but some work better than others.
Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice.
[1]
Other good sequences are found at the On-Line Encyclopedia of Integer Sequences.
| #D | D | import std.stdio: writeln;
void shellSort(T)(T[] seq) pure nothrow {
int inc = seq.length / 2;
while (inc) {
foreach (ref i, el; seq) {
while (i >= inc && seq[i - inc] > el) {
seq[i] = seq[i - inc];
i -= inc;
}
seq[i] = el;
}
inc = (inc == 2) ? 1 : cast(int)(inc * 5.0 / 11);
}
}
void main() {
auto data = [22, 7, 2, -5, 8, 4];
shellSort(data);
writeln(data);
} |
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a sparkline-type bar graph of the values on a single line of output.
The eight characters: '▁▂▃▄▅▆▇█'
(Unicode values U+2581 through U+2588).
Use your program to show sparklines for the following input,
here on this page:
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5
(note the mix of separators in this second case)!
Notes
A space is not part of the generated sparkline.
The sparkline may be accompanied by simple statistics of the data such as its range.
A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:
"0, 1, 19, 20" -> ▁▁██
(Aiming to use just two spark levels)
"0, 999, 4000, 4999, 7000, 7999" -> ▁▁▅▅██
(Aiming to use just three spark levels)
It may be helpful to include these cases in output tests.
You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.
| #Phix | Phix | with javascript_semantics
requires("1.0.2") -- (a fix for JS)
include builtins\unicode_console.e
constant tests = {"0 1 19 20", "0 0 1 1",
"0 999 4000 4999 7000 7999", "1 1 2 2 3 3",
"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1",
"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5"}
for i=1 to length(tests) do
sequence ti = split_any(tests[i]," ,")
for j=1 to length(ti) do
{{ti[j]}} = scanf(ti[j],"%f")
end for
atom mn = min(ti),
mx = max(ti),
range = mx-mn
printf(1,"Min :%g, Max :%g, Range :%g\n",{mn,mx,range})
if unicode_console() then
for j=1 to length(ti) do
ti[j] = #2581 + min(7,floor((ti[j]-mn)/range*8))
end for
printf(1,"%s\n",{utf32_to_utf8(ti)})
else
puts(1,"unicode is not supported\n")
end if
end for
|
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand 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 Strand sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Strand sort.
This is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list.
| #Racket | Racket |
#lang racket
(require mzlib/list)
(define (merge xs ys) (merge-sorted-lists xs ys <=))
(define (strand-sort xs)
(let loop ([xs xs] [ys '[]])
(cond [(empty? xs) ys]
[else (define-values (sorted unsorted) (extract-strand xs))
(loop unsorted (merge sorted ys))])))
(define (extract-strand xs)
(for/fold ([strand '()] [unsorted '[]]) ([x xs])
(if (or (empty? strand) (< x (first strand)))
(values (cons x strand) unsorted)
(values strand (cons x unsorted)))))
(strand-sort (build-list 10 (λ(_) (random 15))))
|
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand 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 Strand sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Strand sort.
This is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list.
| #Raku | Raku | sub infix:<M> (@x-in, @y-in) {
my @x = | @x-in;
my @y = | @y-in;
flat @x, @y,
reverse gather while @x and @y {
take do given @x[*-1] cmp @y[*-1] {
when More { pop @x }
when Less { pop @y }
when Same { pop(@x), pop(@y) }
}
}
}
sub strand (@x) {
my $i = 0;
my $prev = -Inf;
gather while $i < @x {
@x[$i] before $prev ?? $i++ !! take $prev = splice(@x, $i, 1)[0];
}
}
sub strand_sort (@x is copy) {
my @out;
@out M= strand(@x) while @x;
@out;
}
my @a = (^100).roll(10);
say "Before {@a}";
@a = strand_sort(@a);
say "After {@a}";
@a = <The quick brown fox jumps over the lazy dog>;
say "Before {@a}";
@a = strand_sort(@a);
say "After {@a}"; |
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.
Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.
Task Specifics
Given ten males:
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
And ten females:
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
And a complete list of ranked preferences, where the most liked is to the left:
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope
abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan
Use the Gale Shapley algorithm to find a stable set of engagements
Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.
References
The Stable Marriage Problem. (Eloquent description and background information).
Gale-Shapley Algorithm Demonstration.
Another Gale-Shapley Algorithm Demonstration.
Stable Marriage Problem - Numberphile (Video).
Stable Marriage Problem (the math bit) (Video).
The Stable Marriage Problem and School Choice. (Excellent exposition)
| #PureBasic | PureBasic | #coupleCount = 10
DataSection
;guys
Data.s "abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay"
Data.s "bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay"
Data.s "col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan"
Data.s "dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi"
Data.s "ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay"
Data.s "fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay"
Data.s "gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay"
Data.s "hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee"
Data.s "ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve"
Data.s "jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope"
;gals
Data.s "abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal"
Data.s "bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal"
Data.s "cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon"
Data.s "dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed"
Data.s "eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob"
Data.s "fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal"
Data.s "gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian"
Data.s "hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred"
Data.s "ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan"
Data.s "jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan"
EndDataSection
Structure message
source.s ;person that message is from
dest.s ;person that message is for
action.s ;{'P', 'A', 'D', 'B'} for proposal, accept, decline, break-up
EndStructure
Structure person
name.s
isEngagedTo.s
List prefs.s()
EndStructure
Global NewList messages.message()
Procedure setupPersons(List persons.person(), count)
Protected i, j, start, pref$
For i = 1 To count
Read.s pref$
pref$ = LCase(pref$)
start = FindString(pref$, ":", 1)
AddElement(persons())
persons()\name = Left(pref$, start - 1)
pref$ = Trim(Right(pref$, Len(pref$) - start))
For j = 1 To count
AddElement(persons()\prefs())
persons()\prefs() = Trim(StringField(pref$, j, ","))
Next
Next
EndProcedure
Procedure sendMessage(source.s, dest.s, action.s)
LastElement(messages())
AddElement(messages())
With messages()
\source = source
\dest = dest
\action = action
EndWith
ResetList(messages())
EndProcedure
Procedure selectPerson(name.s, List persons.person())
ForEach persons()
If persons()\name = name
Break
EndIf
Next
EndProcedure
Procedure rankPerson(name.s, List prefs.s())
ForEach prefs()
If prefs() = name
ProcedureReturn #coupleCount - ListIndex(prefs()) ;higher is better
EndIf
Next
ProcedureReturn -1 ;no rank, shouldn't occur
EndProcedure
Procedure stabilityCheck(List guys.person(), List gals.person())
Protected isStable = #True
ForEach guys()
rankPerson(guys()\isEngagedTo, guys()\prefs())
While PreviousElement(guys()\prefs())
selectPerson(guys()\prefs(), gals())
If rankPerson(guys()\name, gals()\prefs()) > rankPerson(gals()\isEngagedTo, gals()\prefs())
Print(" " + gals()\name + " loves " + guys()\name + " more than " + gals()\isEngagedTo + ",")
PrintN(" And " + guys()\name + " loves " + gals()\name + " more than " + guys()\isEngagedTo + ".")
isStable = #False
EndIf
Wend
Next
If isStable
PrintN(#CRLF$ + "Marriage stability check PASSED.")
Else
PrintN(#CRLF$ + "Marriage stability check FAILED.")
EndIf
EndProcedure
NewList guys.person()
NewList gals.person()
setupPersons(guys(), #coupleCount)
setupPersons(gals(), #coupleCount)
;make initial round of proposals
ForEach guys()
FirstElement(guys()\prefs())
sendMessage(guys()\name, guys()\prefs(), "P")
Next
;dispatch messages
Define source.s, dest.s, action.s
ForEach messages()
source = messages()\source
dest = messages()\dest
action = messages()\action
DeleteElement(messages())
Select action
Case "P" ;propose ;only message received by gals
selectPerson(dest, gals())
selectPerson(source, guys())
If rankPerson(guys()\name, gals()\prefs()) < rankPerson(gals()\isEngagedTo, gals()\prefs())
sendMessage(dest, source, "D") ;decline proposal
ElseIf rankPerson(guys()\name, gals()\prefs()) > rankPerson(gals()\isEngagedTo, gals()\prefs())
If gals()\isEngagedTo
sendMessage(dest, gals()\isEngagedTo, "B") ;break-up engagement
EndIf
gals()\isEngagedTo = source
sendMessage(dest, source, "A") ;accept proposal
EndIf
Case "A", "D", "B" ;messages received by guys
selectPerson(dest, guys())
If action = "A" ;proposal accepted
guys()\isEngagedTo = source
Else
If action = "B" ;broke-up
guys()\isEngagedTo = ""
EndIf
NextElement(guys()\prefs())
sendMessage(dest, guys()\prefs(),"P") ;propose to next pref
EndIf
EndSelect
Next
If OpenConsole()
PrintN("Marriages:")
ForEach guys()
PrintN(" " + guys()\name + " And " + guys()\isEngagedTo + ".")
Next
stabilityCheck(guys(), gals())
Define *person_1.person, *person_2.person
PrintN(#CRLF$ + "Introducing an error by swapping partners of abi and bea.")
selectPerson("abi", gals()): *person_1 = @gals()
selectPerson("bea", gals()): *person_2 = @gals()
Swap *person_1\isEngagedTo, *person_2\isEngagedTo
selectPerson(*person_1\isEngagedTo, guys()): *person_1 = @guys()
selectPerson(*person_1\isEngagedTo, guys()): *person_2 = @guys()
Swap *person_1\isEngagedTo, *person_2\isEngagedTo
PrintN(" " + *person_1\name + " is now with " + *person_1\isEngagedTo + ".")
PrintN(" " + *person_2\name + " is now with " + *person_2\isEngagedTo + ".")
PrintN("")
stabilityCheck(guys(), gals())
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf |
http://rosettacode.org/wiki/Stack | Stack |
Data Structure
This illustrates a data structure, a means of storing data within a program.
You may see other such structures in the Data Structures category.
A stack is a container of elements with last in, first out access policy. Sometimes it also called LIFO.
The stack is accessed through its top.
The basic stack operations are:
push stores a new element onto the stack top;
pop returns the last pushed stack element, while removing it from the stack;
empty tests if the stack contains no elements.
Sometimes the last pushed stack element is made accessible for immutable access (for read) or mutable access (for write):
top (sometimes called peek to keep with the p theme) returns the topmost element without modifying the stack.
Stacks allow a very simple hardware implementation.
They are common in almost all processors.
In programming, stacks are also very popular for their way (LIFO) of resource management, usually memory.
Nested scopes of language objects are naturally implemented by a stack (sometimes by multiple stacks).
This is a classical way to implement local variables of a re-entrant or recursive subprogram. Stacks are also used to describe a formal computational framework.
See stack machine.
Many algorithms in pattern matching, compiler construction (e.g. recursive descent parsers), and machine learning (e.g. based on tree traversal) have a natural representation in terms of stacks.
Task
Create a stack supporting the basic operations: push, pop, empty.
See also
Array
Associative array: Creation, Iteration
Collections
Compound data type
Doubly-linked list: Definition, Element definition, Element insertion, List Traversal, Element Removal
Linked list
Queue: Definition, Usage
Set
Singly-linked list: Element definition, Element insertion, List Traversal, Element Removal
Stack
| #Ioke | Ioke | Stack = Origin mimic do(
initialize = method(@elements = [])
pop = method(@elements pop!)
empty = method(@elements empty?)
push = method(element, @elements push!(element))
) |
http://rosettacode.org/wiki/Spiral_matrix | Spiral matrix | Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
Related tasks
Zig-zag matrix
Identity_matrix
Ulam_spiral_(for_primes)
| #Icon_and_Unicon | Icon and Unicon | procedure main(A) # spiral matrix
N := 0 < integer(\A[1]|5) # N=1... (dfeault 5)
WriteMatrix(SpiralMatrix(N))
end
procedure WriteMatrix(M) #: write the matrix
every x := M[r := 1 to *M, c := 1 to *M[r]] do
writes(right(\x|"-", 3), if c = *M[r] then "\n" else "")
return
end
procedure SpiralMatrix(N) #: create spiral matrix
every (!(M := list(N))):= list(N) # build empty matrix NxN
# setup before starting first turn
corner := 0 # . corner we're at
i := -1 # . cell contents
r:= 1 ; c :=0 # . row & col
cincr := integer(sin(0)) # . column incr
until i > N^2 do {
rincr := cincr # row incr follows col
cincr := integer(sin(&pi/2*(corner+:=1))) # col incr at each corner
if (run := N-corner/2) = 0 then break # shorten run to 0 at U/R & L/L
every run to 1 by -1 do
M[r +:= rincr,c +:= cincr] := i +:= 1 # move, count, and fill
}
return M
end |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #UNIX_Shell | UNIX Shell | # contains arguments passed to the ursa
# interpreter on the command line
string<> args
# iodevice that points to the console by default
iodevice console
# contains "\n"
string endl
# represents false
boolean false
# represents true
boolean true |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Ursa | Ursa | # contains arguments passed to the ursa
# interpreter on the command line
string<> args
# iodevice that points to the console by default
iodevice console
# contains "\n"
string endl
# represents false
boolean false
# represents true
boolean true |
http://rosettacode.org/wiki/Sorting_algorithms/Radix_sort | Sorting algorithms/Radix 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
Task
Sort an integer array with the radix sort algorithm.
The primary purpose is to complete the characterization of sort algorithms task.
| #C | C | #include <stdio.h>
#include <limits.h>
#include <stdlib.h>
#include <time.h>
// Get size of statically allocated array
#define ARR_LEN(ARR) (sizeof ARR / sizeof *ARR)
// Generate random number in the interval [M,N]
#define RAND_RNG(M,N) (M + rand() / (RAND_MAX / (N - M + 1) + 1));
static void swap(unsigned *a, unsigned *b) {
unsigned tmp = *a;
*a = *b;
*b = tmp;
}
/* sort unsigned ints */
static void rad_sort_u(unsigned *from, unsigned *to, unsigned bit)
{
if (!bit || to < from + 1) return;
unsigned *ll = from, *rr = to - 1;
for (;;) {
/* find left most with bit, and right most without bit, swap */
while (ll < rr && !(*ll & bit)) ll++;
while (ll < rr && (*rr & bit)) rr--;
if (ll >= rr) break;
swap(ll, rr);
}
if (!(bit & *ll) && ll < to) ll++;
bit >>= 1;
rad_sort_u(from, ll, bit);
rad_sort_u(ll, to, bit);
}
/* sort signed ints: flip highest bit, sort as unsigned, flip back */
static void radix_sort(int *a, const size_t len)
{
size_t i;
unsigned *x = (unsigned*) a;
for (i = 0; i < len; i++)
x[i] ^= INT_MIN;
rad_sort_u(x, x + len, INT_MIN);
for (i = 0; i < len; i++)
x[i] ^= INT_MIN;
}
int main(void)
{
srand(time(NULL));
int x[16];
for (size_t i = 0; i < ARR_LEN(x); i++)
x[i] = RAND_RNG(-128,127)
radix_sort(x, ARR_LEN(x));
for (size_t i = 0; i < ARR_LEN(x); i++)
printf("%d%c", x[i], i + 1 < ARR_LEN(x) ? ' ' : '\n');
} |
http://rosettacode.org/wiki/Sorting_algorithms/Quicksort | Sorting algorithms/Quicksort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other 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 Quicksort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Sort an array (or list) elements using the quicksort algorithm.
The elements must have a strict weak 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.
Quicksort, also known as partition-exchange sort, uses these steps.
Choose any element of the array to be the pivot.
Divide all other elements (except the pivot) into two partitions.
All elements less than the pivot must be in the first partition.
All elements greater than the pivot must be in the second partition.
Use recursion to sort both partitions.
Join the first sorted partition, the pivot, and the second sorted partition.
The best pivot creates partitions of equal length (or lengths differing by 1).
The worst pivot creates an empty partition (for example, if the pivot is the first or last element of a sorted array).
The run-time of Quicksort ranges from O(n log n) with the best pivots, to O(n2) with the worst pivots, where n is the number of elements in the array.
This is a simple quicksort algorithm, adapted from Wikipedia.
function quicksort(array)
less, equal, greater := three empty arrays
if length(array) > 1
pivot := select any element of array
for each x in array
if x < pivot then add x to less
if x = pivot then add x to equal
if x > pivot then add x to greater
quicksort(less)
quicksort(greater)
array := concatenate(less, equal, greater)
A better quicksort algorithm works in place, by swapping elements within the array, to avoid the memory allocation of more arrays.
function quicksort(array)
if length(array) > 1
pivot := select any element of array
left := first index of array
right := last index of array
while left ≤ right
while array[left] < pivot
left := left + 1
while array[right] > pivot
right := right - 1
if left ≤ right
swap array[left] with array[right]
left := left + 1
right := right - 1
quicksort(array from first index to right)
quicksort(array from left to last index)
Quicksort has a reputation as the fastest sort. Optimized variants of quicksort are common features of many languages and libraries. One often contrasts quicksort with merge sort, because both sorts have an average time of O(n log n).
"On average, mergesort does fewer comparisons than quicksort, so it may be better when complicated comparison routines are used. Mergesort also takes advantage of pre-existing order, so it would be favored for using sort() to merge several sorted arrays. On the other hand, quicksort is often faster for small arrays, and on arrays of a few distinct values, repeated many times." — http://perldoc.perl.org/sort.html
Quicksort is at one end of the spectrum of divide-and-conquer algorithms, with merge sort at the opposite end.
Quicksort is a conquer-then-divide algorithm, which does most of the work during the partitioning and the recursive calls. The subsequent reassembly of the sorted partitions involves trivial effort.
Merge sort is a divide-then-conquer algorithm. The partioning happens in a trivial way, by splitting the input array in half. Most of the work happens during the recursive calls and the merge phase.
With quicksort, every element in the first partition is less than or equal to every element in the second partition. Therefore, the merge phase of quicksort is so trivial that it needs no mention!
This task has not specified whether to allocate new arrays, or sort in place. This task also has not specified how to choose the pivot element. (Common ways to are to choose the first element, the middle element, or the median of three elements.) Thus there is a variety among the following implementations.
| #360_Assembly | 360 Assembly | * Quicksort 14/09/2015 & 23/06/2016
QUICKSOR CSECT
USING QUICKSOR,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13) "
LR R13,R15 "
MVC A,=A(1) a(1)=1
MVC B,=A(NN) b(1)=hbound(t)
L R6,=F'1' k=1
DO WHILE=(LTR,R6,NZ,R6) do while k<>0 ==================
LR R1,R6 k
SLA R1,2 ~
L R10,A-4(R1) l=a(k)
LR R1,R6 k
SLA R1,2 ~
L R11,B-4(R1) m=b(k)
BCTR R6,0 k=k-1
LR R4,R11 m
C R4,=F'2' if m<2
BL ITERATE then iterate
LR R2,R10 l
AR R2,R11 +m
BCTR R2,0 -1
ST R2,X x=l+m-1
LR R2,R11 m
SRA R2,1 m/2
AR R2,R10 +l
ST R2,Y y=l+m/2
L R1,X x
SLA R1,2 ~
L R4,T-4(R1) r4=t(x)
L R1,Y y
SLA R1,2 ~
L R5,T-4(R1) r5=t(y)
LR R1,R10 l
SLA R1,2 ~
L R3,T-4(R1) r3=t(l)
IF CR,R4,LT,R3 if t(x)<t(l) ---+
IF CR,R5,LT,R4 if t(y)<t(x) |
LR R7,R4 p=t(x) |
L R1,X x |
SLA R1,2 ~ |
ST R3,T-4(R1) t(x)=t(l) |
ELSEIF CR,R5,GT,R3 elseif t(y)>t(l) |
LR R7,R3 p=t(l) |
ELSE , else |
LR R7,R5 p=t(y) |
L R1,Y y |
SLA R1,2 ~ |
ST R3,T-4(R1) t(y)=t(l) |
ENDIF , end if |
ELSE , else |
IF CR,R5,LT,R3 if t(y)<t(l) |
LR R7,R3 p=t(l) |
ELSEIF CR,R5,GT,R4 elseif t(y)>t(x) |
LR R7,R4 p=t(x) |
L R1,X x |
SLA R1,2 ~ |
ST R3,T-4(R1) t(x)=t(l) |
ELSE , else |
LR R7,R5 p=t(y) |
L R1,Y y |
SLA R1,2 ~ |
ST R3,T-4(R1) t(y)=t(l) |
ENDIF , end if |
ENDIF , end if ---+
LA R8,1(R10) i=l+1
L R9,X j=x
FOREVER EQU * do forever --------------------+
LR R1,R8 i |
SLA R1,2 ~ |
LA R2,T-4(R1) @t(i) |
L R0,0(R2) t(i) |
DO WHILE=(CR,R8,LE,R9,AND, while i<=j and ---+ | X
CR,R0,LE,R7) t(i)<=p | |
AH R8,=H'1' i=i+1 | |
AH R2,=H'4' @t(i) | |
L R0,0(R2) t(i) | |
ENDDO , end while ---+ |
LR R1,R9 j |
SLA R1,2 ~ |
LA R2,T-4(R1) @t(j) |
L R0,0(R2) t(j) |
DO WHILE=(CR,R8,LT,R9,AND, while i<j and ---+ | X
CR,R0,GE,R7) t(j)>=p | |
SH R9,=H'1' j=j-1 | |
SH R2,=H'4' @t(j) | |
L R0,0(R2) t(j) | |
ENDDO , end while ---+ |
CR R8,R9 if i>=j |
BNL LEAVE then leave (segment finished) |
LR R1,R8 i |
SLA R1,2 ~ |
LA R2,T-4(R1) @t(i) |
LR R1,R9 j |
SLA R1,2 ~ |
LA R3,T-4(R1) @t(j) |
L R0,0(R2) w=t(i) + |
MVC 0(4,R2),0(R3) t(i)=t(j) |swap t(i),t(j) |
ST R0,0(R3) t(j)=w + |
B FOREVER end do forever ----------------+
LEAVE EQU *
LR R9,R8 j=i
BCTR R9,0 j=i-1
LR R1,R9 j
SLA R1,2 ~
LA R3,T-4(R1) @t(j)
L R2,0(R3) t(j)
LR R1,R10 l
SLA R1,2 ~
ST R2,T-4(R1) t(l)=t(j)
ST R7,0(R3) t(j)=p
LA R6,1(R6) k=k+1
LR R1,R6 k
SLA R1,2 ~
LA R4,A-4(R1) r4=@a(k)
LA R5,B-4(R1) r5=@b(k)
IF C,R8,LE,Y if i<=y ----+
ST R8,0(R4) a(k)=i |
L R2,X x |
SR R2,R8 -i |
LA R2,1(R2) +1 |
ST R2,0(R5) b(k)=x-i+1 |
LA R6,1(R6) k=k+1 |
ST R10,4(R4) a(k)=l |
LR R2,R9 j |
SR R2,R10 -l |
ST R2,4(R5) b(k)=j-l |
ELSE , else |
ST R10,4(R4) a(k)=l |
LR R2,R9 j |
SR R2,R10 -l |
ST R2,0(R5) b(k)=j-l |
LA R6,1(R6) k=k+1 |
ST R8,4(R4) a(k)=i |
L R2,X x |
SR R2,R8 -i |
LA R2,1(R2) +1 |
ST R2,4(R5) b(k)=x-i+1 |
ENDIF , end if ----+
ITERATE EQU *
ENDDO , end while =====================
* *** ********* print sorted table
LA R3,PG ibuffer
LA R4,T @t(i)
DO WHILE=(C,R4,LE,=A(TEND)) do i=1 to hbound(t)
L R2,0(R4) t(i)
XDECO R2,XD edit t(i)
MVC 0(4,R3),XD+8 put in buffer
LA R3,4(R3) ibuffer=ibuffer+1
LA R4,4(R4) i=i+1
ENDDO , end do
XPRNT PG,80 print buffer
L R13,4(0,R13) epilog
LM R14,R12,12(R13) "
XR R15,R15 "
BR R14 exit
T DC F'10',F'9',F'9',F'6',F'7',F'16',F'1',F'16',F'17',F'15'
DC F'1',F'9',F'18',F'16',F'8',F'20',F'18',F'2',F'19',F'8'
TEND DS 0F
NN EQU (TEND-T)/4)
A DS (NN)F same size as T
B DS (NN)F same size as T
X DS F
Y DS F
PG DS CL80
XD DS CL12
YREGS
END QUICKSOR |
http://rosettacode.org/wiki/Sorting_algorithms/Patience_sort | Sorting algorithms/Patience 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
Sort an array of numbers (of any convenient size) into ascending order using Patience sorting.
Related task
Longest increasing subsequence
| #AppleScript | AppleScript | -- In-place patience sort.
on patienceSort(theList, l, r) -- Sort items l thru r of theList.
set listLen to (count theList)
if (listLen < 2) then return
-- Convert any negative and/or transposed range indices.
if (l < 0) then set l to listLen + l + 1
if (r < 0) then set r to listLen + r + 1
if (l > r) then set {l, r} to {r, l}
script o
property lst : theList
property piles : {}
end script
-- Build piles.
repeat with i from l to r
set v to o's lst's item i
set unplaced to true
repeat with thisPile in o's piles
if (v > thisPile's end) then
else
set thisPile's end to v
set unplaced to false
exit repeat
end if
end repeat
if (unplaced) then set o's piles's end to {v}
end repeat
-- Remove successive lowest end values to the original list.
set pileCount to (count o's piles)
repeat with i from l to r
set min to o's piles's beginning's end
set minPile to 1
repeat with j from 2 to pileCount
set v to o's piles's item j's end
if (v < min) then
set min to v
set minPile to j
end if
end repeat
set o's lst's item i to min
if ((count o's piles's item minPile) > 1) then
set o's piles's item minPile to o's piles's item minPile's items 1 thru -2
else
set o's piles's item minPile to missing value
set o's piles to o's piles's lists
set pileCount to pileCount - 1
end if
end repeat
return -- nothing
end patienceSort
property sort : patienceSort
local aList
set aList to {62, 86, 59, 65, 92, 85, 71, 71, 27, -52, 67, 59, 65, 80, 3, 65, 2, 46, 83, 72, 47, 5, 26, 18, 63}
sort(aList, 1, -1)
return aList |
http://rosettacode.org/wiki/Sorting_algorithms/Permutation_sort | Sorting algorithms/Permutation 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
Task
Implement a permutation sort, which proceeds by generating the possible permutations
of the input array/list until discovering the sorted one.
Pseudocode:
while not InOrder(list) do
nextPermutation(list)
done
| #E | E | def swap(container, ixA, ixB) {
def temp := container[ixA]
container[ixA] := container[ixB]
container[ixB] := temp
}
/** Reverse order of elements of 'sequence' whose indexes are in the interval [ixLow, ixHigh] */
def reverseRange(sequence, var ixLow, var ixHigh) {
while (ixLow < ixHigh) {
swap(sequence, ixLow, ixHigh)
ixLow += 1
ixHigh -= 1
}
}
/** Algorithm from <http://marknelson.us/2002/03/01/next-permutation>, allegedly from a version of the C++ STL */
def nextPermutation(sequence) {
def last := sequence.size() - 1
var i := last
while (true) {
var ii := i
i -= 1
if (sequence[i] < sequence[ii]) {
var j := last + 1
while (!(sequence[i] < sequence[j -= 1])) {} # buried side effect
swap(sequence, i, j)
reverseRange(sequence, ii, last)
return true
}
if (i == 0) {
reverseRange(sequence, 0, last)
return false
}
}
}
/** Note: Worst case on sorted list */
def permutationSort(flexList) {
while (nextPermutation(flexList)) {}
} |
http://rosettacode.org/wiki/Sorting_algorithms/Pancake_sort | Sorting algorithms/Pancake 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
Task
Sort an array of integers (of any convenient size) into ascending order using Pancake sorting.
In short, instead of individual elements being sorted, the only operation allowed is to "flip" one end of the list, like so:
Before: 6 7 8 9 2 5 3 4 1
After: 9 8 7 6 2 5 3 4 1
Only one end of the list can be flipped; this should be the low end, but the high end is okay if it's easier to code or works better, but it must be the same end for the entire solution. (The end flipped can't be arbitrarily changed.)
Show both the initial, unsorted list and the final sorted list.
(Intermediate steps during sorting are optional.)
Optimizations are optional (but recommended).
Related tasks
Number reversal game
Topswops
Also see
Wikipedia article: pancake sorting.
| #AppleScript | AppleScript | on pancake_sort(aList)
script o
property lst : aList
property len : (count my lst)
on flip(n)
if (n < len) then
set my lst to (reverse of items 1 thru n of my lst) & (items (n + 1) thru len of my lst)
else
set my lst to reverse of my lst
end if
end flip
end script
repeat with i from (count o's lst) to 2 by -1
set maxIdx to 1
set maxVal to beginning of o's lst
repeat with j from 2 to i
tell item j of o's lst
if (it > maxVal) then
set maxIdx to j
set maxVal to it
end if
end tell
end repeat
(* Performancewise, there's little to choose between doing the two 'if' tests below every time and
occasionally flipping unnecessarily. The flips themselves are of of course a daft way to achieve:
set item maxIdx of o's lst to item i of o's lst
set item i of o's lst to maxVal
*)
-- if (maxIdx < i) then
-- if (maxIdx > 1) then ¬
o's flip(maxIdx)
o's flip(i)
-- end if
end repeat
return o's lst
end pancake_sort
-- Task code:
local pre, post, astid, output
set pre to {}
repeat 20 times
set end of pre to (random number 100)
end repeat
set post to pancake_sort(pre)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to ", "
set output to "Before: {" & pre & ("}" & linefeed & "After: {" & post & "}")
set AppleScript's text item delimiters to astid
return output |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ol | Ol | #[]\(){}',|`
() List
[]{} Reserved for feature use
#\ Character constant
' Quote
` Backquote
, Unquote
| Used by code blocks (like multiline comment, symbol name container)
|
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PARI.2FGP | PARI/GP | is square(9) |
http://rosettacode.org/wiki/Sorting_algorithms/Stooge_sort | Sorting algorithms/Stooge 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 Stooge sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Show the Stooge Sort for an array of integers.
The Stooge Sort algorithm is as follows:
algorithm stoogesort(array L, i = 0, j = length(L)-1)
if L[j] < L[i] then
L[i] ↔ L[j]
if j - i > 1 then
t := (j - i + 1)/3
stoogesort(L, i , j-t)
stoogesort(L, i+t, j )
stoogesort(L, i , j-t)
return L
| #FreeBASIC | FreeBASIC | ' version 23-10-2016
' compile with: fbc -s console
Sub stoogesort(s() As Long, l As Long, r As Long)
If s(r) < s(l) Then
Swap s(r), s(l)
End If
If r - l > 1 Then
Var t = (r - l +1) \ 3
stoogesort(s(), l , r - t)
stoogesort(s(), l + t, r )
stoogesort(s(), l , r - t)
End If
End Sub
' ------=< MAIN >=------
Dim As Long i, array(-7 To 7)
Dim As Long a = LBound(array), b = UBound(array)
Randomize Timer
For i = a To b : array(i) = i : Next
For i = a To b ' little shuffle
Swap array(i), array(Int(Rnd * (b - a +1)) + a)
Next
Print "unsorted ";
For i = a To b : Print Using "####"; array(i); : Next : Print
stoogesort(array(), LBound(array), UBound(array))
Print " sorted ";
For i = a To b : Print Using "####"; array(i); : Next : Print
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End |
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort | Sorting algorithms/Sleep 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
In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time.
Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required.
Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
| #J | J | scheduledumb=: {{
id=:'dumb',":x:6!:9''
wd 'pc ',id
(t)=: u {{u y[erase n}} t=. id,'_timer'
wd 'ptimer ',":n p.y
}}
ssort=: {{
R=: ''
poly=. 1,>./ y
poly{{ y{{R=:R,m[y}}scheduledumb m y}}"0 y
{{echo R}} scheduledumb poly"0 >:>./ y
EMPTY
}} |
http://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort | Sorting algorithms/Sleep 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
In general, sleep sort works by starting a separate task for each item to be sorted, where each task sleeps for an interval corresponding to the item's sort key, then emits the item. Items are then collected sequentially in time.
Task: Write a program that implements sleep sort. Have it accept non-negative integers on the command line and print the integers in sorted order. If this is not idomatic in your language or environment, input and output may be done differently. Enhancements for optimization, generalization, practicality, robustness, and so on are not required.
Sleep sort was presented anonymously on 4chan and has been discussed on Hacker News.
| #Java | Java | import java.util.concurrent.CountDownLatch;
public class SleepSort {
public static void sleepSortAndPrint(int[] nums) {
final CountDownLatch doneSignal = new CountDownLatch(nums.length);
for (final int num : nums) {
new Thread(new Runnable() {
public void run() {
doneSignal.countDown();
try {
doneSignal.await();
//using straight milliseconds produces unpredictable
//results with small numbers
//using 1000 here gives a nifty demonstration
Thread.sleep(num * 1000);
System.out.println(num);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
public static void main(String[] args) {
int[] nums = new int[args.length];
for (int i = 0; i < args.length; i++)
nums[i] = Integer.parseInt(args[i]);
sleepSortAndPrint(nums);
}
} |
http://rosettacode.org/wiki/Sorting_algorithms/Selection_sort | Sorting algorithms/Selection 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
Task
Sort an array (or list) of elements using the Selection sort algorithm.
It works as follows:
First find the smallest element in the array and exchange it with the element in the first position, then find the second smallest element and exchange it with the element in the second position, and continue in this way until the entire array is sorted.
Its asymptotic complexity is O(n2) making it inefficient on large arrays.
Its primary purpose is for when writing data is very expensive (slow) when compared to reading, eg. writing to flash memory or EEPROM.
No other sorting algorithm has less data movement.
References
Rosetta Code: O (complexity).
Wikipedia: Selection sort.
Wikipedia: [Big O notation].
| #BBC_BASIC | BBC BASIC | DEF PROC_SelectionSort(Size%)
FOR I% = 1 TO Size%-1
lowest% = I%
FOR J% = (I% + 1) TO Size%
IF data%(J%) < data%(lowest%) lowest% = J%
NEXT J%
IF I%<>lowest% SWAP data%(I%),data%(lowest%)
NEXT I%
ENDPROC |
http://rosettacode.org/wiki/Soundex | Soundex | Soundex is an algorithm for creating indices for words based on their pronunciation.
Task
The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling (from the soundex Wikipedia article).
Caution
There is a major issue in many of the implementations concerning the separation of two consonants that have the same soundex code! According to the official Rules [[1]]. So check for instance if Ashcraft is coded to A-261.
If a vowel (A, E, I, O, U) separates two consonants that have the same soundex code, the consonant to the right of the vowel is coded. Tymczak is coded as T-522 (T, 5 for the M, 2 for the C, Z ignored (see "Side-by-Side" rule above), 2 for the K). Since the vowel "A" separates the Z and K, the K is coded.
If "H" or "W" separate two consonants that have the same soundex code, the consonant to the right of the vowel is not coded. Example: Ashcraft is coded A-261 (A, 2 for the S, C ignored, 6 for the R, 1 for the F). It is not coded A-226.
| #Cach.C3.A9_ObjectScript | Caché ObjectScript |
Class Utils.Phonetic [ Abstract ]
{
ClassMethod ToSoundex(String As %String) As %String [ Language = mvbasic ]
{
Return Soundex(String)
}
}
|
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort | Sorting algorithms/Shell 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
Task
Sort an array of elements using the Shell sort algorithm, a diminishing increment sort.
The Shell sort (also known as Shellsort or Shell's method) is named after its inventor, Donald Shell, who published the algorithm in 1959.
Shell sort is a sequence of interleaved insertion sorts based on an increment sequence.
The increment size is reduced after each pass until the increment size is 1.
With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case".
Any sequence will sort the data as long as it ends in 1, but some work better than others.
Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice.
[1]
Other good sequences are found at the On-Line Encyclopedia of Integer Sequences.
| #Dart | Dart |
void main() {
List<int> a = shellSort([1100, 2, 56, 200, -52, 3, 99, 33, 177, -199]);
print('$a');
}
shellSort(List<int> array) {
int n = array.length;
// Start with a big gap, then reduce the gap
for (int gap = n~/2; gap > 0; gap ~/= 2)
{
// Do a gapped insertion sort for this gap size.
// The first gap elements a[0..gap-1] are already
// in gapped order keep adding one more element
// until the entire array is gap sorted
for (int i = gap; i < n; i += 1)
{
// add a[i] to the elements that have been gap
// sorted save a[i] in temp and make a hole at
// position i
int temp = array[i];
// shift earlier gap-sorted elements up until
// the correct location for a[i] is found
int j;
for (j = i; j >= gap && array[j - gap] > temp; j -= gap)
array[j] = array[j - gap];
// put temp (the original a[i]) in its correct
// location
array[j] = temp;
}
}
return array;
}
|
http://rosettacode.org/wiki/Sorting_algorithms/Shell_sort | Sorting algorithms/Shell 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
Task
Sort an array of elements using the Shell sort algorithm, a diminishing increment sort.
The Shell sort (also known as Shellsort or Shell's method) is named after its inventor, Donald Shell, who published the algorithm in 1959.
Shell sort is a sequence of interleaved insertion sorts based on an increment sequence.
The increment size is reduced after each pass until the increment size is 1.
With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case".
Any sequence will sort the data as long as it ends in 1, but some work better than others.
Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice.
[1]
Other good sequences are found at the On-Line Encyclopedia of Integer Sequences.
| #Delphi | Delphi | Procedure ShellSort(var buf:Array of Integer);
const
gaps:array[0..7] of Integer = (701, 301, 132, 57, 23, 10, 4, 1);
var
whichGap, i, j, n, gap, temp : Integer;
begin
n := high(buf);
for whichGap := 0 to high(gaps) do begin
gap := gaps[whichGap];
for i := gap to n do begin
temp := buf[i];
j := i;
while ( (j >= gap ) and ( (buf[j-gap] > dt) ) do begin
buf[j] := buf[j-gap];
dec(j, gap);
end;
buf[j] := temp;
end;
end;
end; |
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a sparkline-type bar graph of the values on a single line of output.
The eight characters: '▁▂▃▄▅▆▇█'
(Unicode values U+2581 through U+2588).
Use your program to show sparklines for the following input,
here on this page:
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5
(note the mix of separators in this second case)!
Notes
A space is not part of the generated sparkline.
The sparkline may be accompanied by simple statistics of the data such as its range.
A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:
"0, 1, 19, 20" -> ▁▁██
(Aiming to use just two spark levels)
"0, 999, 4000, 4999, 7000, 7999" -> ▁▁▅▅██
(Aiming to use just three spark levels)
It may be helpful to include these cases in output tests.
You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.
| #PicoLisp | PicoLisp | (de sparkLine (Lst)
(let (Min (apply min Lst) Max (apply max Lst) Rng (- Max Min))
(for N Lst
(prin
(char (+ 9601 (*/ (- N Min) 7 Rng)) ) ) )
(prinl) ) ) |
http://rosettacode.org/wiki/Sparkline_in_unicode | Sparkline in unicode | A sparkline is a graph of successive values laid out horizontally
where the height of the line is proportional to the values in succession.
Task
Use the following series of Unicode characters to create a program
that takes a series of numbers separated by one or more whitespace or comma characters
and generates a sparkline-type bar graph of the values on a single line of output.
The eight characters: '▁▂▃▄▅▆▇█'
(Unicode values U+2581 through U+2588).
Use your program to show sparklines for the following input,
here on this page:
1 2 3 4 5 6 7 8 7 6 5 4 3 2 1
1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5
(note the mix of separators in this second case)!
Notes
A space is not part of the generated sparkline.
The sparkline may be accompanied by simple statistics of the data such as its range.
A suggestion emerging in later discussion (see Discussion page) is that the bounds between bins should ideally be set to yield the following results for two particular edge cases:
"0, 1, 19, 20" -> ▁▁██
(Aiming to use just two spark levels)
"0, 999, 4000, 4999, 7000, 7999" -> ▁▁▅▅██
(Aiming to use just three spark levels)
It may be helpful to include these cases in output tests.
You may find that the unicode sparklines on this page are rendered less noisily by Google Chrome than by Firefox or Safari.
| #Python | Python | # -*- coding: utf-8 -*-
# Unicode: 9601, 9602, 9603, 9604, 9605, 9606, 9607, 9608
bar = '▁▂▃▄▅▆▇█'
barcount = len(bar)
def sparkline(numbers):
mn, mx = min(numbers), max(numbers)
extent = mx - mn
sparkline = ''.join(bar[min([barcount - 1,
int((n - mn) / extent * barcount)])]
for n in numbers)
return mn, mx, sparkline
if __name__ == '__main__':
import re
for line in ("0 0 1 1; 0 1 19 20; 0 999 4000 4999 7000 7999;"
"1 2 3 4 5 6 7 8 7 6 5 4 3 2 1;"
"1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5 ").split(';'):
print("\nNumbers:", line)
numbers = [float(n) for n in re.split(r'[\s,]+', line.strip())]
mn, mx, sp = sparkline(numbers)
print(' min: %5f; max: %5f' % (mn, mx))
print(" " + sp) |
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand 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 Strand sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Strand sort.
This is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list.
| #REXX | REXX | /*REXX program sorts a random list of words (or numbers) using the strand sort algorithm*/
parse arg size minv maxv old /*obtain optional arguments from the CL*/
if size=='' | size=="," then size=20 /*Not specified? Then use the default.*/
if minv=='' | minv=="," then minv= 0 /*Not specified? Then use the default.*/
if maxv=='' | maxv=="," then maxv=size /*Not specified? Then use the default.*/
do i=1 for size /*generate a list of random numbers. */
old=old random(0,maxv-minv)+minv /*append a random number to a list. */
end /*i*/
old=space(old) /*elide extraneous blanks from the list*/
say center('unsorted list', length(old), "─"); say old
new=strand_sort(old) /*sort the list of the random numbers. */
say; say center('sorted list' , length(new), "─"); say new
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
strand_sort: procedure; parse arg x; y=
do while words(x)\==0; w=words(x)
do j=1 for w-1 /*anything out of order?*/
if word(x,j)>word(x,j+1) then do; w=j; leave; end
end /*j*/
y=merge(y,subword(x,1,w)); x=subword(x,w+1)
end /*while*/
return y
/*──────────────────────────────────────────────────────────────────────────────────────*/
merge: procedure; parse arg a.1,a.2; p=
do forever; w1=words(a.1); w2=words(a.2) /*do while 2 lists exist*/
if w1==0 | if w2==0 then leave /*Any list empty? Stop.*/
if word(a.1,w1) <= word(a.2,1) then leave /*lists are now sorted? */
if word(a.2,w2) <= word(a.1,1) then return space(p a.2 a.1)
#=1+(word(a.1,1) >= word(a.2,1)); p=p word(a.#,1); a.#=subword(a.#,2)
end /*forever*/
return space(p a.1 a.2) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.