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/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #Oforth | Oforth | true
false
null
System.Out
System.In
System.Err
System.Console
System.Args
Systel.NbCores
System.CELLSIZE
System.VERSION
SYstem.MAXTHREADS
System.ASSERTMODE
System.ISWIN
System.ISLUNIX
|
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.
| #Pascal | Pascal | program foo(input, output);
begin
{ In this program, `input` and `output` have special meaning. }
end. |
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.
| #11l | 11l | F flatten(some_list)
[Int] new_list
L(sub_list) some_list
new_list [+]= sub_list
R new_list
F radix_sort(l, =p = -1, =s = -1)
I s == -1
s = String(max(l)).len
I p == -1
p = s
V i = s - p
I i >= s
R l
V bins = [[Int]()] * 10
L(e) l
bins[Int(String(e).zfill(s)[i])] [+]= e
R flatten(bins.map(b -> radix_sort(b, @p - 1, @s)))
V arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
print(radix_sort(arr)) |
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
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program permutationSort.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSortOk: .asciz "Table sorted.\n"
szMessSortNok: .asciz "Table not sorted !!!!!.\n"
sMessResult: .asciz "Value : @ \n"
szCarriageReturn: .asciz "\n"
.align 4
#TableNumber: .int 1,3,6,2,5,9,10,8,5,7 @ for test 2 sames values
TableNumber: .int 10,9,8,7,6,5,4,3,2,1
#TableNumber: .int 1,2,3
.equ NBELEMENTS, (. - TableNumber) / 4
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrTableNumber @ address number table
mov r1,#NBELEMENTS @ number of élements
bl heapIteratif
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
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrTableNumber: .int TableNumber
iAdrszMessSortOk: .int szMessSortOk
iAdrszMessSortNok: .int szMessSortNok
/******************************************************************/
/* permutation by heap iteratif (wikipedia) */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the eléments number */
heapIteratif:
push {r3-r9,lr} @ save registers
mov r8,r0 @ save table address
lsl r9,r1,#2 @ four bytes by count
sub sp,sp,r9
mov fp,sp
mov r3,#0
mov r4,#0 @ index
1: @ init area counter
str r4,[fp,r3,lsl #2]
add r3,r3,#1
cmp r3,r1
blt 1b
//bl displayTable
bl isSorted @ control sort
cmp r0,#1 @ sorted ?
beq 99f
mov r0,r8 @ restaur table address
mov r3,#0 @ index
2:
ldr r4,[fp,r3,lsl #2] @ load count [i]
cmp r4,r3 @ compare with i
bge 5f
tst r3,#1 @ even ?
bne 3f
ldr r5,[r0] @ yes load value A[0]
ldr r6,[r0,r3,lsl #2] @ ans swap with value A[i]
str r6,[r0]
str r5,[r0,r3,lsl #2]
b 4f
3:
ldr r5,[r0,r4,lsl #2] @ load value A[count[i]]
ldr r6,[r0,r3,lsl #2] @ and swap with value A[i]
str r6,[r0,r4,lsl #2]
str r5,[r0,r3,lsl #2]
4:
//bl displayTable
bl isSorted @ control sort
cmp r0,#1 @ sorted ?
beq 99f @ yes
mov r0,r8 @ restaur table address
add r4,r4,#1 @ increment count i
str r4,[fp,r3,lsl #2] @ and store on stack
mov r3,#0 @ raz index
b 2b @ and loop
5:
mov r4,#0 @ raz count [i]
str r4,[fp,r3,lsl #2]
add r3,r3,#1 @ increment index
cmp r3,r1 @ end ?
blt 2b @ no -> loop
99:
add sp,sp,r9 @ stack alignement
100:
pop {r3-r9,lr}
bx lr @ return
/******************************************************************/
/* 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
/******************************************************************/
/* 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,iAdrsZoneConv @
bl conversion10S @ décimal conversion
ldr r0,iAdrsMessResult
ldr r1,iAdrsZoneConv @ insert conversion
bl strInsertAtCharInc
bl affichageMess @ display message
add r3,#1
cmp r3,#NBELEMENTS - 1
ble 1b
ldr r0,iAdrszCarriageReturn
bl affichageMess
mov r0,r2
100:
pop {r0-r3,lr}
bx lr
iAdrsZoneConv: .int sZoneConv
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
|
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
| #Icon_and_Unicon | Icon and Unicon | \b backspace
\d delete
\e escape
\f formfeed
\l linefeed
\n newline
\r return
\t horizontal tab
\v vertical tab
\' single quote
\" double quote
\\ backslash
\ddd octal code
\xdd hexadecimal code
\^c control code |
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
| #J | J | '' NB. empty string
'''' NB. one quote character
'
'''''' NB. two quote characters
'' |
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
| #C.2B.2B | C++ |
#include <iostream>
#include <time.h>
//------------------------------------------------------------------------------
using namespace std;
//------------------------------------------------------------------------------
class stooge
{
public:
void sort( int* arr, int start, int end )
{
if( arr[start] > arr[end - 1] ) swap( arr[start], arr[end - 1] );
int n = end - start; if( n > 2 )
{
n /= 3; sort( arr, start, end - n );
sort( arr, start + n, end ); sort( arr, start, end - n );
}
}
};
//------------------------------------------------------------------------------
int main( int argc, char* argv[] )
{
srand( static_cast<unsigned int>( time( NULL ) ) ); stooge s; int a[80], m = 80;
cout << "before:\n";
for( int x = 0; x < m; x++ ) { a[x] = rand() % 40 - 20; cout << a[x] << " "; }
s.sort( a, 0, m ); cout << "\n\nafter:\n";
for( int x = 0; x < m; x++ ) cout << a[x] << " "; cout << "\n\n";
return system( "pause" );
}
|
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.
| #D | D | void main(string[] args)
{
import core.thread, std;
args.drop(1).map!(a => a.to!uint).parallel.each!((a)
{
Thread.sleep(dur!"msecs"(a));
write(a, " ");
});
} |
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].
| #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 SelectionSort(INT ARRAY a INT size)
INT i,j,minpos,tmp
FOR i=0 TO size-2
DO
minpos=i
FOR j=i+1 TO size-1
DO
IF a(minpos)>a(j) THEN
minpos=j
FI
OD
IF minpos#i THEN
tmp=a(i)
a(i)=a(minpos)
a(minpos)=tmp
FI
OD
RETURN
PROC Test(INT ARRAY a INT size)
PrintE("Array before sort:")
PrintArray(a,size)
SelectionSort(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/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.
| #Arturo | Arturo | code: #[
"aeiouy": `W`
"bfpv": `1`
"cgjkqsxz": `2`
"dt": `3`
"l": `4`
"mn": `5`
"r": `6`
]
getCode: function [ch][
loop keys code 'k [
if contains? k lower to :string ch -> return code\[k]
]
return ` `
]
soundex: function [str][
result: new to :string first str
prev: getCode first str
loop.with:'i str 'c [
curr: getCode c
if curr <> ` ` [
if and? curr <> `W`
curr <> prev -> 'result ++ curr
prev: curr
]
]
if? 4 < size result ->
result: new slice result 0 3
else [
do.times: 4-size result ->
'result ++ `0`
]
return result
]
loop ["Robert", "Rupert", "Rubin", "Ashcraft", "Ashcroft", "Tymczak",
"Pfister", "Honeyman", "Moses", "O'Mally", "O'Hara", "D day"] 'name ->
print [pad name 10 "->" soundex name] |
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.
| #AutoHotkey | AutoHotkey | MsgBox % ShellSort("")
MsgBox % ShellSort("xxx")
MsgBox % ShellSort("3,2,1")
MsgBox % ShellSort("dog,000000,xx,cat,pile,abcde,1,cat,zz,xx,z")
MsgBox % ShellSort("12,11,10,9,8,4,5,6,7,3,2,1,10,13,14,15,19,17,18,16,20,10")
ShellSort(var) { ; SORT COMMA SEPARATED LIST
StringSplit a, var, `, ; make array (length = a0)
inc := a0
While inc:=round(inc/2.2) ; geometric gap sequence
Loop % a0-inc { ; insertion sort:
i := A_Index+inc, t := a%i%, j := i, k := j-inc
While j > inc && a%k% > t
a%j% := a%k%, j := k, k -= inc
a%j% := t
}
Loop % a0 ; construct string from sorted array
s .= "," . a%A_Index%
Return SubStr(s,2) ; drop leading comma
} |
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.
| #JavaScript | JavaScript | (() => {
'use strict';
const main = () => {
// sparkLine :: [Num] -> String
const sparkLine = xs => {
const hist = dataBins(8)(xs);
return unlines([
concat(map(
i => '▁▂▃▄▅▆▇█' [i],
hist.indexes
)),
unwords(xs),
[
'Min: ' + hist.min,
'Mean: ' + hist.mean.toFixed(2),
'Median: ' + hist.median,
'Max: ' + hist.max,
].join('\t'),
''
]);
};
// dataBins :: Int -> [Num] ->
// {indexes:: [Int], min:: Float, max:: Float,
// range :: Float, lbounds :: [Float]}
const dataBins = intBins => xs => {
const
iLast = intBins - 1,
ys = sort(xs),
mn = ys[0],
mx = last(ys),
rng = mx - mn,
w = rng / intBins,
lng = xs.length,
mid = lng / 2,
lbounds = map(
i => mn + (w * i),
enumFromTo(1, iLast)
);
return {
indexes: map(
x => {
const mb = findIndex(b => b > x, lbounds);
return mb.Nothing ? (
iLast
) : mb.Just;
},
xs
),
lbounds: lbounds,
min: mn,
median: even(lng) ? (
sum([ys[mid - 1], ys[mid]]) / 2
) : ys[Math.floor(mid)],
mean: sum(xs) / lng,
max: mx,
range: rng
};
};
// numbersFromString :: String -> [Float]
const numbersFromString = s =>
map(x => parseFloat(x, 10),
s.split(/[,\s]+/)
);
return unlines(map(
compose(sparkLine, numbersFromString),
[
'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'
]
));
};
// GENERIC FUNCTIONS ----------------------------
// Just :: a -> Maybe a
const Just = x => ({
type: 'Maybe',
Nothing: false,
Just: x
});
// Nothing :: Maybe a
const Nothing = () => ({
type: 'Maybe',
Nothing: true,
});
// compose (<<<) :: (b -> c) -> (a -> b) -> a -> c
const compose = (f, g) => x => f(g(x));
// concat :: [[a]] -> [a]
// concat :: [String] -> String
const concat = xs =>
0 < xs.length ? (() => {
const unit = 'string' !== typeof xs[0] ? (
[]
) : '';
return unit.concat.apply(unit, xs);
})() : [];
// enumFromTo :: (Int, Int) -> [Int]
const enumFromTo = (m, n) =>
Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// even :: Int -> Bool
const even = n => 0 === n % 2;
// last :: [a] -> a
const last = xs =>
0 < xs.length ? xs.slice(-1)[0] : undefined;
// map :: (a -> b) -> [a] -> [b]
const map = (f, xs) =>
(Array.isArray(xs) ? (
xs
) : xs.split('')).map(f);
// sort :: Ord a => [a] -> [a]
const sort = xs => xs.slice()
.sort((a, b) => a < b ? -1 : (a > b ? 1 : 0));
// findIndex :: (a -> Bool) -> [a] -> Maybe Int
const findIndex = (p, xs) => {
const
i = (
'string' !== typeof xs ? (
xs
) : xs.split('')
).findIndex(p);
return -1 !== i ? (
Just(i)
) : Nothing();
};
// sum :: [Num] -> Num
const sum = xs => xs.reduce((a, x) => a + x, 0);
// unlines :: [String] -> String
const unlines = xs => xs.join('\n');
// unwords :: [String] -> String
const unwords = xs => xs.join(' ');
// MAIN ---
return main();
})(); |
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.
| #PARI.2FGP | PARI/GP | strandSort(v)={
my(sorted=[],unsorted=v,remaining,working);
while(#unsorted,
remaining=working=List();
listput(working, unsorted[1]);
for(i=2,#unsorted,
if(unsorted[i]<working[#working],
listput(remaining, unsorted[i])
,
listput(working, unsorted[i])
)
);
unsorted=Vec(remaining);
sorted=merge(sorted, Vec(working))
);
sorted
};
merge(u,v)={
my(ret=vector(#u+#v),i=1,j=1);
for(k=1,#ret,
if(i<=#u & (j>#v | u[i]<v[j]),
ret[k]=u[i];
i++
,
ret[k]=v[j];
j++
)
);
ret
}; |
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)
| #Mathematica_.2F_Wolfram_Language | Mathematica / Wolfram Language | <<Combinatorica`;
ClearAll[CheckStability]
CheckStabilityHelp[male_, female_, ml_List, fl_List, pairing_List] := Module[{prefs, currentmale},
prefs = fl[[female]];
currentmale = Sort[Reverse /@ pairing][[female, 2]];
FirstPosition[prefs, currentmale][[1]] < FirstPosition[prefs, male][[1]]
]
CheckStabilityHelp[male_, ml_List, fl_List, pairing_List] := Module[{prefs, m, f, p, otherf, reversepair, pos, othermen},
prefs = ml[[male]];
{m, f} = pairing[[male]];
p = FirstPosition[prefs, f][[1]];
otherf = Take[prefs, p - 1];
AllTrue[otherf, CheckStabilityHelp[male, #, ml, fl, pairing] &]
]
CheckStability[ml_List, fl_List, pairing_List] := AllTrue[pairing[[All, 1]], CheckStabilityHelp[#, ml, fl, pairing] &]
males = {"abe", "bob", "col", "dan", "ed", "fred", "gav", "hal",
"ian", "jon"};
females = {"abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope",
"ivy", "jan"};
ml = {{"abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea",
"hope", "gay"}, {"cath", "hope", "abi", "dee", "eve", "fay",
"bea", "jan", "ivy", "gay"}, {"hope", "eve", "abi", "dee", "bea",
"fay", "ivy", "gay", "cath", "jan"}, {"ivy", "fay", "dee", "gay",
"hope", "eve", "jan", "bea", "cath", "abi"}, {"jan", "dee", "bea",
"cath", "fay", "eve", "abi", "ivy", "hope", "gay"}, {"bea",
"abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope",
"fay"}, {"gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope",
"jan", "fay"}, {"abi", "eve", "hope", "fay", "ivy", "cath",
"jan", "bea", "gay", "dee"}, {"hope", "cath", "dee", "gay", "bea",
"abi", "fay", "ivy", "jan", "eve"}, {"abi", "fay", "jan", "gay",
"eve", "bea", "dee", "cath", "ivy", "hope"}};
fl = {{"bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col",
"hal"}, {"bob", "abe", "col", "fred", "gav", "dan", "ian", "ed",
"jon", "hal"}, {"fred", "bob", "ed", "gav", "hal", "col", "ian",
"abe", "dan", "jon"}, {"fred", "jon", "col", "abe", "ian", "hal",
"gav", "dan", "bob", "ed"}, {"jon", "hal", "fred", "dan", "abe",
"gav", "col", "ed", "ian", "bob"}, {"bob", "abe", "ed", "ian",
"jon", "dan", "fred", "gav", "col", "hal"}, {"jon", "gav", "hal",
"fred", "bob", "abe", "col", "ed", "dan", "ian"}, {"gav", "jon",
"bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"}, {"ian",
"col", "hal", "gav", "fred", "bob", "abe", "ed", "jon",
"dan"}, {"ed", "hal", "gav", "abe", "bob", "jon", "col", "ian",
"fred", "dan"}};
ml = ml /. Thread[females -> Range[Length[males]]];
fl = fl /. Thread[males -> Range[Length[females]]];
pairing = StableMarriage[ml, fl];
pairing = {Range[Length[pairing]], pairing} // Transpose;
pairing
CheckStability[ml, fl, pairing]
pairing[[{2, 7}, 2]] //= Reverse;
pairing
CheckStability[ml, fl, pairing] |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #VBA | VBA |
Option Explicit
Sub Split_string_based_on_change_character()
Dim myArr() As String, T As String
Const STRINPUT As String = "gHHH5YY++///\"
Const SEP As String = ", "
myArr = Split_Special(STRINPUT)
T = Join(myArr, SEP)
Debug.Print Left(T, Len(T) - Len(SEP))
End Sub
Function Split_Special(Ch As String) As String()
'return an array of Strings
Dim tb, i&, st As String, cpt As Long, R() As String
tb = Split(StrConv(Ch, vbUnicode), Chr(0))
st = tb(LBound(tb))
ReDim R(cpt)
R(cpt) = st
For i = 1 To UBound(tb)
If tb(i) = st Then
R(cpt) = R(cpt) & st
Else
st = tb(i)
cpt = cpt + 1
ReDim Preserve R(cpt)
R(cpt) = st
End If
Next
Split_Special = R
End Function
|
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #Wren | Wren | var split = Fn.new { |s|
if (s.count == 0) return ""
var res = []
var last = s[0]
var curr = last
for (c in s.skip(1)) {
if (c == last) {
curr = curr + c
} else {
res.add(curr)
curr = c
}
last = c
}
res.add(curr)
return res.join(", ")
}
var s = "gHHH5YY++///\\"
System.print(split.call(s)) |
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
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
' stack_rosetta.bi
' simple generic Stack type
#Define Stack(T) Stack_##T
#Macro Declare_Stack(T)
Type Stack(T)
Public:
Declare Constructor()
Declare Destructor()
Declare Property capacity As Integer
Declare Property count As Integer
Declare Property empty As Boolean
Declare Property top As T
Declare Function pop() As T
Declare Sub push(item As T)
Private:
a(any) As T
count_ As Integer = 0
Declare Function resize(size As Integer) As Integer
End Type
Constructor Stack(T)()
Redim a(0 To 0) '' create a default T instance for various purposes
End Constructor
Destructor Stack(T)()
Erase a
End Destructor
Property Stack(T).capacity As Integer
Return UBound(a)
End Property
Property Stack(T).count As Integer
Return count_
End Property
Property Stack(T).empty As Boolean
Return count_ = 0
End Property
Property Stack(T).top As T
If count_ > 0 Then
Return a(count_)
End If
Print "Error: Attempted to access 'top' element of an empty stack"
Return a(0) '' return default element
End Property
Function Stack(T).pop() As T
If count_ > 0 Then
Dim value As T = a(count_)
a(count_) = a(0) '' zero element to be removed
count_ -= 1
Return value
End If
Print "Error: Attempted to remove 'top' element of an empty stack"
Return a(0) '' return default element
End Function
Sub Stack(T).push(item As T)
Dim size As Integer = UBound(a)
count_ += 1
If count_ > size Then
size = resize(size)
Redim Preserve a(0 to size)
End If
a(count_) = item
End Sub
Function Stack(T).resize(size As Integer) As Integer
If size = 0 Then
size = 4
ElseIf size <= 32 Then
size = 2 * size
Else
size += 32
End If
Return size
End Function
#EndMacro |
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)
| #F.23 | F# | let Spiral n =
let sq = Array2D.create n n 0 // Set up an output array
let nCur = ref -1 // Current value being inserted
let NextN() = nCur := (!nCur+1) ; !nCur // Inc current value and return new value
let Frame inset = // Create the "frame" at an offset from the outside
let rangeF = [inset..(n - inset - 2)] // Range we use going forward
let rangeR = [(n - inset - 1)..(-1)..(inset + 1)] // Range we use going backward
rangeF |> Seq.iter (fun i -> sq.[inset,i] <- NextN()) // Top of frame
rangeF |> Seq.iter (fun i -> sq.[i,n-inset-1] <- NextN()) // Right side of frame
rangeR |> Seq.iter (fun i -> sq.[n-inset-1,i] <- NextN()) // Bottom of frame
rangeR |> Seq.iter (fun i -> sq.[i,inset] <- NextN()) // Left side of frame
[0..(n/2 - 1)] |> Seq.iter (fun i -> Frame i) // Fill in all frames
if n &&& 1 = 1 then sq.[n/2,n/2] <- n*n - 1 // If n is odd, fill in the last single value
sq // Return our output array |
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.
| #PARI.2FGP | PARI/GP | use English; # enables use of long variable names
$. $INPUT_LINE_NUMBER # sequence number
$, $OUTPUT_FIELD_SEPARATOR # output field separator
$; $SUBSCRIPT_SEPARATOR # subscript separator for multidimensional array emulation
$_ $ARG # topic/current/default variable
$" $LIST_SEPARATOR # alternative output field separator
$+ $LAST_PAREN_MATCH # last substring matched to a regular expression subpattern
$0 $PROGRAM_NAME # name of the program being executed
$! $ERRNO # error number from host operating system
$@ $EVAL_ERROR # error from the last "eval" operator
$/ $INPUT_RECORD_SEPARATOR # input record separator
$\ $OUTPUT_RECORD_SEPARATOR # output record separator for 'print'
$| $OUTPUT_AUTOFLUSH # controls output buffering
$& $MATCH # string matched by last regular expression
$' $POSTMATCH # substring following last matched regular expression
$` $PREMATCH # substring preceding last matched regular expression
@ARGV # array containing the command line parameters
@F # array of fields of each line read in when auto-split is on
@INC # array of library search paths
%ENV # associative container holding the environment variables
%SIG # associative container holding signal handlers |
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.
| #Perl | Perl | use English; # enables use of long variable names
$. $INPUT_LINE_NUMBER # sequence number
$, $OUTPUT_FIELD_SEPARATOR # output field separator
$; $SUBSCRIPT_SEPARATOR # subscript separator for multidimensional array emulation
$_ $ARG # topic/current/default variable
$" $LIST_SEPARATOR # alternative output field separator
$+ $LAST_PAREN_MATCH # last substring matched to a regular expression subpattern
$0 $PROGRAM_NAME # name of the program being executed
$! $ERRNO # error number from host operating system
$@ $EVAL_ERROR # error from the last "eval" operator
$/ $INPUT_RECORD_SEPARATOR # input record separator
$\ $OUTPUT_RECORD_SEPARATOR # output record separator for 'print'
$| $OUTPUT_AUTOFLUSH # controls output buffering
$& $MATCH # string matched by last regular expression
$' $POSTMATCH # substring following last matched regular expression
$` $PREMATCH # substring preceding last matched regular expression
@ARGV # array containing the command line parameters
@F # array of fields of each line read in when auto-split is on
@INC # array of library search paths
%ENV # associative container holding the environment variables
%SIG # associative container holding signal handlers |
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.
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program radixSort64.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"
szCarriageReturn: .asciz "\n"
.align 4
TableNumber: .quad 12485,301,16,25,5006,9,-154389710,26,4400,71,115
#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 radixSort
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
/******************************************************************/
/* radix sort */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the first element */
/* r2 contains the number of element */
/* no registers save */
radixSort:
str lr,[sp,-16]! // save 1 register
mov x7,0b1111 // mask one digit hexa
mov x10,0 // digit counter
1:
add x3,x1,1 // start index i
2: // start loop
ldr x4,[x0,x3,lsl 3] // load value A[i]
and x8,x4,x7 // and mask
sub x5,x3,1 // index j
3:
ldr x6,[x0,x5,lsl 3] // load value A[j]
and x9,x6,x7 // and mask
cmp x9,x8 // compare one digit hexa
ble 4f
add x5,x5,1 // increment index j
str x6,[x0,x5,lsl 3] // store value A[j+1]
sub x5,x5,2 // j = j - 1
cmp x5,x1
bge 3b // loop if j >= first item
4:
add x5,x5,1 // increment index j
str x4,[x0,x5,lsl 3] // store value A[i] in A[j+1]
add x3,x3,1 // increment index i
cmp x3,x2 // end ?
blt 2b // no -> loop
//bl displayTable
lsl x7,x7,4 // shift mask 4 bits left
add x10,x10,1 // increment counter
cmp x10,16 // 16 digits ?
blt 1b // no loop
100:
ldr lr,[sp],16 // restaur 1 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/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
| #Arturo | Arturo | sorted?: function [arr][
previous: first arr
loop slice arr 1 (size arr)-1 'item [
if not? item > previous -> return false
previous: item
]
return true
]
permutationSort: function [items][
loop permutate items 'perm [
if sorted? perm -> return perm
]
]
print permutationSort [3 1 2 8 5 7 9 4 6] |
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
| #Java | Java | & | ^ ~ //bitwise AND, OR, XOR, and NOT
>> << //bitwise arithmetic shift
>>> //bitwise logical shift
+ - * / = % //+ can be used for String concatenation) |
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
| #JavaScript | JavaScript | ^[a-zA-Z_][a-zA-Z_0-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
| #Clojure | Clojure | (defn swap [v x y]
(assoc! v y (v x) x (v y)))
(defn stooge-sort
([v] (persistent! (stooge-sort (transient v) 0 (dec (count v)))))
([v i j]
(if (> (v i) (v j)) (swap v i j) v)
(if (> (- j i) 1)
(let [t (int (Math/floor (/ (inc (- j i)) 3)))]
(stooge-sort v i (- j t))
(stooge-sort v (+ i t) j)
(stooge-sort v i (- j t))))
v)) |
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.
| #Dart | Dart |
void main() async {
Future<void> sleepsort(Iterable<int> input) => Future.wait(input
.map((i) => Future.delayed(Duration(milliseconds: i), () => print(i))));
await sleepsort([3, 10, 2, 120, 122, 121, 54]);
}
|
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.
| #Delphi | Delphi | program SleepSortDemo;
{$APPTYPE CONSOLE}
uses
Windows, SysUtils, Classes;
type
TSleepThread = class(TThread)
private
FValue: Integer;
FLock: PRTLCriticalSection;
protected
constructor Create(AValue: Integer; ALock: PRTLCriticalSection);
procedure Execute; override;
end;
constructor TSleepThread.Create(AValue: Integer; ALock: PRTLCriticalSection);
begin
FValue:= AValue;
FLock:= ALock;
inherited Create(False);
end;
procedure TSleepThread.Execute;
begin
Sleep(1000 * FValue);
EnterCriticalSection(FLock^);
Write(FValue:3);
LeaveCriticalSection(FLock^);
end;
var
A: array[0..15] of Integer;
Handles: array[0..15] of THandle;
Threads: array[0..15] of TThread;
Lock: TRTLCriticalSection;
I: Integer;
begin
for I:= Low(A) to High(A) do
A[I]:= Random(15);
for I:= Low(A) to High(A) do
Write(A[I]:3);
Writeln;
InitializeCriticalSection(Lock);
for I:= Low(A) to High(A) do begin
Threads[I]:= TSleepThread.Create(A[I], @Lock);
Handles[I]:= Threads[I].Handle;
end;
WaitForMultipleObjects(Length(A), @Handles, True, INFINITE);
for I:= Low(A) to High(A) do
Threads[I].Free;
DeleteCriticalSection(Lock);
Writeln;
ReadLn;
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].
| #ActionScript | ActionScript | function selectionSort(input: Array):Array {
//find the i'th element
for (var i:uint = 0; i < input.length; i++) {
//set minIndex to an arbitrary value
var minIndex:uint=i;
//find the smallest number
for (var j:uint = i; j < input.length; j++) {
if (input[j]<input[minIndex]) {
minIndex=j;
}
}
//swap the smallest number into place
var tmp:Number=input[i];
input[i]=input[minIndex];
input[minIndex]=tmp;
}
return input;
} |
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.
| #AutoHotkey | AutoHotkey | getCode(c){
If c in B,F,P,V
return 1
If c in C,G,J,K,Q,S,X,Z
return 2
If c in D,T
return 3
If c = L
return 4
If c in M,N
return 5
If c = R
return 6
}
soundex(s){
code := SubStr(s, 1, 1)
,previous := 7
,i := 1
While ++i <= StrLen(s){
current := getCode(SubStr(s, i, 1))
If StrLen(current) > 0 And current <> previous
code := code . current
previous := current
}
soundex := SubStr(code, 1, 4)
If StrLen(code) < 4
soundex .= String(4 - StrLen(code), "0")
return soundex
}
String(a, n){
Loop n
o .= a
return a
}
MsgBox % Soundex("Soundex") "`n" Soundex("Sowndeks") "`n" Soundex("Ashcroft") "`n" Soundex("Ashkrofd") |
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.
| #AWK | AWK | {
line[NR] = $0
}
END { # sort it with shell sort
increment = int(NR / 2)
while ( increment > 0 ) {
for(i=increment+1; i <= NR; i++) {
j = i
temp = line[i]
while ( (j >= increment+1) && (line[j-increment] > temp) ) {
line[j] = line[j-increment]
j -= increment
}
line[j] = temp
}
if ( increment == 2 )
increment = 1
else
increment = int(increment*5/11)
}
#print it
for(i=1; i <= NR; i++) {
print line[i]
}
} |
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.
| #jq | jq | def sparkline:
min as $min
| ( (max - $min) / 7 ) as $div
| map( 9601 + (. - $min) * $div )
| implode ;
def string2array:
def tidy: select( length > 0 );
[split(" ") | .[] | split(",") | .[] | tidy | tonumber]; |
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.
| #Julia | Julia | function sparklineit(arr)
sparkchars = '\u2581':'\u2588'
dyn = length(sparkchars)
lo, hi = extrema(arr)
b = @. max(ceil(Int, dyn * (arr - lo) / (hi - lo)), 1)
return join(sparkchars[b])
end
v = rand(0:10, 10)
println("$v → ", sparklineit(v))
v = 10rand(10)
println("$(round.(v, 2)) → ", sparklineit(v))
lines = strip.(split("""
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""", "\n"))
arrays = map(lin -> split(lin, r"\s+|\s*,\s*") .|> s -> parse(Float64, s), lines)
foreach(v -> println("$v → ", sparklineit(v)), arrays)
|
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.
| #Pascal | Pascal | program StrandSortDemo;
type
TIntArray = array of integer;
function merge(left: TIntArray; right: TIntArray): TIntArray;
var
i, j, k: integer;
begin
setlength(merge, length(left) + length(right));
i := low(merge);
j := low(left);
k := low(right);
repeat
if ((left[j] <= right[k]) and (j <= high(left))) or (k > high(right)) then
begin
merge[i] := left[j];
inc(j);
end
else
begin
merge[i] := right[k];
inc(k);
end;
inc(i);
until i > high(merge);
end;
function StrandSort(s: TIntArray): TIntArray;
var
strand: TIntArray;
i, j: integer;
begin
setlength(StrandSort, length(s));
setlength(strand, length(s));
i := low(s);
repeat
StrandSort[i] := s[i];
inc(i);
until (s[i] < s[i-1]);
setlength(StrandSort, i);
repeat
setlength(strand, 1);
j := low(strand);
strand[j] := s[i];
while (s[i+1] > s[i]) and (i < high(s)) do
begin
inc(i);
inc(j);
setlength(strand, length(strand) + 1);
Strand[j] := s[i];
end;
StrandSort := merge(StrandSort, strand);
inc(i);
until (i > high(s));
end;
var
data: TIntArray;
i: integer;
begin
setlength(data, 8);
Randomize;
writeln('The data before sorting:');
for i := low(data) to high(data) do
begin
data[i] := Random(high(data));
write(data[i]:4);
end;
writeln;
data := StrandSort(data);
writeln('The data after sorting:');
for i := low(data) to high(data) do
begin
write(data[i]:4);
end;
writeln;
end. |
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)
| #Nim | Nim | import sequtils, random, strutils
const
Pairs = 10
MNames = ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
FNames = ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
MPreferences = [
["abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"],
["cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"],
["hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"],
["ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"],
["jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"],
["bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"],
["gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"],
["abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"],
["hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"],
["abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"]
]
FPreferences = [
["bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"],
["bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"],
["fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"],
["fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"],
["jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"],
["bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"],
["jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"],
["gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"],
["ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"],
["ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan"]
]
# recipient's preferences hold the preference score for each contender's id
func getRecPreferences[N: static int](prefs: array[N, array[N, string]],
names: openArray[string]): array[N, array[N, int]] {.compileTime.} =
for r, prefArray in pairs(prefs):
for c, contender in pairs(prefArray):
result[r][c] = prefArray.find(MNames[c])
# contender's preferences hold the recipient ids in descending order of preference
func getContPreferences[N: static int](prefs: array[N, array[N, string]],
names: openArray[string]): array[N, array[N, int]] {.compileTime.} =
for c, pref_seq in pairs(prefs):
for r, pref in pairs(pref_seq):
result[c][r] = names.find(pref)
const
RecipientPrefs = getRecPreferences(FPreferences, MNames)
ContenderPrefs = getContPreferences(MPreferences, FNames)
proc printCoupleNames(contPairs: seq[int]) =
for c, r in pairs(contPairs):
echo MNames[c] & " 💑 " & FNames[contPairs[c]]
func pair(): (seq[int], seq[int]) =
# double booking to avoid inverse lookup using find
var
recPairs = newSeqWith(10, -1)
contPairs = newSeqWith(10, -1)
template engage(c, r: int) =
#echo FNames[r] & " accepted " & MNames[c]
contPairs[c] = r
recPairs[r] = c
var contQueue = newSeqWith(10, 0)
while contPairs.contains(-1):
for c in 0..<Pairs:
if contPairs[c] == -1:
let r = ContenderPrefs[c][contQueue[c]] #proposing to first in queue
contQueue[c] += 1 #increment contender's queue for following iterations
let curPair = recPairs[r] # current pair's index or -1 = vacant
if curPair == -1:
engage(c, r)
# contender is more preferable than current
elif RecipientPrefs[r][c] < RecipientPrefs[r][curPair]:
contPairs[curPair] = -1 # vacate current pair
#echo MNames[curPair] & " was dumped by " & FNames[r]
engage(c, r)
result = (contPairs, recPairs)
proc randomPair(max: int): (int, int) =
let a = rand(max)
var b = rand(max - 1)
if b == a:
b = max
result = (a, b)
proc perturbPairs(contPairs, recPairs: var seq[int]) =
randomize()
let (a, b) = randomPair(Pairs-1)
echo("Swapping ", MNames[a], " & ", MNames[b], " partners")
swap(contPairs[a], contPairs[b])
swap(recPairs[contPairs[a]], recPairs[contPairs[b]])
proc checkPairStability(contPairs, recPairs: seq[int]): bool =
for c in 0..<Pairs: # each contender
let curPairScore = ContenderPrefs[c].find(contPairs[c]) # pref. score for current pair
for preferredRec in 0..<curPairScore: # try every recipient with higher score
let
checkedRec = ContenderPrefs[c][preferredRec]
curRecPair = recPairs[checkedRec] # current pair of checked recipient
# if score of the curRecPair is worse (>) than score of checked contender
if RecipientPrefs[checkedRec][curRecPair] > RecipientPrefs[checkedRec][c]:
echo("💔 ", MNames[c], " prefers ", FNames[checkedRec], " over ", FNames[contPairs[c]])
echo("💔 ", FNames[checkedRec], " prefers ", MNames[c], " over ", MNames[curRecPair])
echo "✗ Unstable"
return false # unstable
echo "✓ Stable"
result = true
when isMainModule:
var (contPairs, recPairs) = pair()
printCoupleNames(contPairs)
echo "Current pair analysis:"
discard checkPairStability(contPairs, recPairs)
perturbPairs(contPairs, recPairs)
printCoupleNames(contPairs)
echo "Current pair analysis:"
discard checkPairStability(contPairs, recPairs)
|
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #XLISP | XLISP | (defun delimit (s)
(defun delim (old-list new-list current-char)
(if (null old-list)
new-list
(delim (cdr old-list) (append new-list
(if (not (equal (car old-list) current-char))
`(#\, #\Space ,(car old-list))
(cons (car old-list) nil) ) )
(car old-list) ) ) )
(list->string (delim (string->list s) '() (car (string->list s)))) )
(display (delimit "gHHH5YY++///\\")) ;; NB. The "\" character needs to be escaped |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #XPL0 | XPL0 | string 0; \change to zero-terminated convention
char S;
[S:= "gHHH5YY++///\";
while S(0) do
[ChOut(0, S(0));
if S(1)#S(0) & S(1)#0 then Text(0, ", ");
S:= S+1;
];
] |
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
| #Frink | Frink | a = new array
a.push[1]
a.push[2]
a.peek[]
while ! a.isEmpty[]
println[a.pop[]] |
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)
| #Factor | Factor | USING: arrays grouping io kernel math math.combinatorics
math.ranges math.statistics prettyprint sequences
sequences.repeating ;
IN: rosetta-code.spiral-matrix
: counts ( n -- seq ) 1 [a,b] 2 repeat rest ;
: vals ( n -- seq )
[ 1 swap 2dup [ neg ] bi@ 4array ] [ 2 * 1 - cycle ] bi ;
: evJKT2 ( n -- seq )
[ counts ] [ vals ] bi [ <array> ] 2map concat ;
: spiral ( n -- matrix )
[ evJKT2 cum-sum inverse-permutation ] [ group ] bi ;
: spiral-demo ( -- ) 5 9 [ spiral simple-table. nl ] bi@ ;
MAIN: spiral-demo |
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.
| #Phix | Phix | - Global variables start with an asterisk '*'
- Functions and other global symbols start with a lower case letter
- Locally bound symbols start with an upper case letter
- Local functions start with an underscore '_'
- Classes start with a plus-sign '+', where the first letter
- is in lower case for abstract classes
- and in upper case for normal classes
- Methods end with a right arrow '>'
- Class variables may be indicated by an upper case letter |
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.
| #PicoLisp | PicoLisp | - Global variables start with an asterisk '*'
- Functions and other global symbols start with a lower case letter
- Locally bound symbols start with an upper case letter
- Local functions start with an underscore '_'
- Classes start with a plus-sign '+', where the first letter
- is in lower case for abstract classes
- and in upper case for normal classes
- Methods end with a right arrow '>'
- Class variables may be indicated by an upper case letter |
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.
| #Ada | Ada | with Ada.Text_IO;
procedure Radix_Sort is
type Integer_Array is array (Positive range <>) of Integer;
procedure Least_Significant_Radix_Sort (Data : in out Integer_Array; Base : Positive := 10) is
type Bucket is record
Count : Natural := 0;
Content : Integer_Array (Data'Range);
end record;
subtype Bucket_Index is Integer range -Base + 1 .. Base - 1;
type Bucket_Array is array (Bucket_Index) of Bucket;
procedure Append (To : in out Bucket; Item : Integer) is
begin
To.Count := To.Count + 1;
To.Content (To.Count) := Item;
end Append;
function Get_Nth_Digit (Value : Integer; N : Positive) return Integer is
Result : Integer := (Value / (Base ** (N - 1))) mod Base;
begin
if Value < 0 then
Result := -Result;
end if;
return Result;
end Get_Nth_Digit;
function Get_Maximum return Natural is
Result : Natural := 0;
begin
for I in Data'Range loop
if abs (Data (I)) > Result then
Result := abs (Data (I));
end if;
end loop;
return Result;
end Get_Maximum;
function Split (Pass : Positive) return Bucket_Array is
Buckets : Bucket_Array;
begin
for I in Data'Range loop
Append (To => Buckets (Get_Nth_Digit (Data (I), Pass)),
Item => Data (I));
end loop;
return Buckets;
end Split;
function Merge (Buckets : Bucket_Array) return Integer_Array is
Result : Integer_Array (Data'Range);
Current_Index : Positive := 1;
begin
for Sublist in Buckets'Range loop
for Item in 1 .. Buckets (Sublist).Count loop
Result (Current_Index) := Buckets (Sublist).Content (Item);
Current_Index := Current_Index + 1;
end loop;
end loop;
return Result;
end Merge;
Max_Number : Natural := Get_Maximum;
Digit_Count : Positive := 1;
begin
-- count digits of biggest number
while Max_Number > Base loop
Digit_Count := Digit_Count + 1;
Max_Number := Max_Number / Base;
end loop;
for Pass in 1 .. Digit_Count loop
Data := Merge (Split (Pass));
end loop;
end Least_Significant_Radix_Sort;
Test_Array : Integer_Array := (170, 45, 75, -90, -802, 24, 2, 66);
begin
Least_Significant_Radix_Sort (Test_Array, 4);
for I in Test_Array'Range loop
Ada.Text_IO.Put (Integer'Image (Test_Array (I)));
end loop;
Ada.Text_IO.New_Line;
end Radix_Sort; |
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
| #AutoHotkey | AutoHotkey | MsgBox % PermSort("")
MsgBox % PermSort("xxx")
MsgBox % PermSort("3,2,1")
MsgBox % PermSort("dog,000000,xx,cat,pile,abcde,1,cat")
PermSort(var) { ; SORT COMMA SEPARATED LIST
Local i, sorted
StringSplit a, var, `, ; make array, size = a0
v0 := a0 ; auxiliary array for permutations
Loop %v0%
v%A_Index% := A_Index
While unSorted("a","v") ; until sorted
NextPerm("v") ; try new permutations
Loop % a0 ; construct string from sorted array
i := v%A_Index%, sorted .= "," . a%i%
Return SubStr(sorted,2) ; drop leading comma
}
unSorted(a,v) {
Loop % %a%0-1 {
i := %v%%A_Index%, j := A_Index+1, j := %v%%j%
If (%a%%i% > %a%%j%)
Return 1
}
}
NextPerm(v) { ; the lexicographically next LARGER permutation of v1..v%v0%
Local i, i1, j, t
i := %v%0, i1 := i-1
While %v%%i1% >= %v%%i% {
--i, --i1
IfLess i1,1, Return 1 ; Signal the end
}
j := %v%0
While %v%%j% <= %v%%i1%
--j
t := %v%%i1%, %v%%i1% := %v%%j%, %v%%j% := t, j := %v%0
While i < j
t := %v%%i%, %v%%i% := %v%%j%, %v%%j% := t, ++i, --j
} |
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
| #jq | jq | ^[a-zA-Z_][a-zA-Z_0-9]*$ |
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
| #Julia | Julia | # defined local ie. #mylocal will fail if not defined
$ defined variable ie. $myvar will fail if not defined
= assignment
:= assign as return assigned value
? ternary conditional true ? this
| ternary else false ? this | that
|| or
&& and
! negative operator
{ open capture
} close capture
=> specify givenblock / capture
-> invoke method: mytype->mymethod
& retarget: mytype->mymethod& // returns mytype
^ autocollect from capture: {^ 'this will be outputted' ^}
:: tag prefix, ie. ::mytype->gettype // returns myype
:: type constraint, ie. define mymethod(p::integer) => #i * 2
\ escape method: ie. \mymethod->invoke(2)
// comment
/* open comment
*/ close comment |
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
| #COBOL | COBOL | >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. stooge-sort-test.
DATA DIVISION.
WORKING-STORAGE SECTION.
01 Arr-Len CONSTANT 7.
01 arr-area VALUE "00004001000020000005000230000000000".
03 arr-elt PIC 9(5) OCCURS Arr-Len TIMES
INDEXED BY arr-idx.
PROCEDURE DIVISION.
DISPLAY "Unsorted: " NO ADVANCING
PERFORM VARYING arr-idx FROM 1 BY 1 UNTIL Arr-Len < arr-idx
DISPLAY arr-elt (arr-idx) " " NO ADVANCING
END-PERFORM
DISPLAY SPACE
CALL "stooge-sort" USING arr-area, OMITTED, OMITTED
DISPLAY "Sorted: " NO ADVANCING
PERFORM VARYING arr-idx FROM 1 BY 1 UNTIL Arr-Len < arr-idx
DISPLAY arr-elt (arr-idx) " " NO ADVANCING
END-PERFORM
DISPLAY SPACE
.
END PROGRAM stooge-sort-test.
IDENTIFICATION DIVISION.
PROGRAM-ID. stooge-sort RECURSIVE.
DATA DIVISION.
LOCAL-STORAGE SECTION.
01 Arr-Len CONSTANT 7.
01 i PIC 99 COMP.
01 j PIC 99 COMP.
01 temp PIC 9(5).
01 t PIC 99 COMP.
LINKAGE SECTION.
01 arr-area.
03 arr-elt PIC 9(5) OCCURS Arr-Len TIMES.
01 i-val PIC 99 COMP.
01 j-val PIC 99 COMP.
PROCEDURE DIVISION USING arr-area, OPTIONAL i-val, OPTIONAL j-val.
IF i-val IS OMITTED
MOVE 1 TO i
ELSE
MOVE i-val TO i
END-IF
IF j-val IS OMITTED
MOVE Arr-Len TO j
ELSE
MOVE j-val TO j
END-IF
IF arr-elt (j) < arr-elt (i)
MOVE arr-elt (i) TO temp
MOVE arr-elt (j) TO arr-elt (i)
MOVE temp TO arr-elt (j)
END-IF
IF j - i + 1 >= 3
COMPUTE t = (j - i + 1) / 3
SUBTRACT t FROM j
CALL "stooge-sort" USING arr-area, CONTENT i, j
ADD t TO i, j
CALL "stooge-sort" USING arr-area, CONTENT i, j
SUBTRACT t FROM i, j
CALL "stooge-sort" USING arr-area, CONTENT i, j
END-IF
.
END PROGRAM stooge-sort. |
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.
| #Elena | Elena | import extensions;
import system'routines;
import extensions'threading;
import system'threading;
static sync = new object();
extension op
{
sleepSort()
{
self.forEach:(n)
{
threadControl.start(
{
threadControl.sleep(1000 * n);
lock(sync)
{
console.printLine(n)
}
})
}
}
}
public program()
{
program_arguments.skipping:1.selectBy(mssgconst toInt<convertorOp>[1]).toArray().sleepSort();
console.readChar()
} |
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.
| #Elixir | Elixir | defmodule Sort do
def sleep_sort(args) do
Enum.each(args, fn(arg) -> Process.send_after(self, arg, 5 * arg) end)
loop(length(args))
end
defp loop(0), do: :ok
defp loop(n) do
receive do
num -> IO.puts num
loop(n - 1)
end
end
end
Sort.sleep_sort [2, 4, 8, 12, 35, 2, 12, 1] |
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].
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
procedure Test_Selection_Sort is
type Integer_Array is array (Positive range <>) of Integer;
procedure Sort (A : in out Integer_Array) is
Min : Positive;
Temp : Integer;
begin
for I in A'First..A'Last - 1 loop
Min := I;
for J in I + 1..A'Last loop
if A (Min) > A (J) then
Min := J;
end if;
end loop;
if Min /= I then
Temp := A (I);
A (I) := A (Min);
A (Min) := Temp;
end if;
end loop;
end Sort;
A : Integer_Array := (4, 9, 3, -2, 0, 7, -5, 1, 6, 8);
begin
Sort (A);
for I in A'Range loop
Put (Integer'Image (A (I)) & " ");
end loop;
end Test_Selection_Sort; |
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.
| #AWK | AWK | #!/usr/bin/awk -f
BEGIN {
subsep = ", "
delete homs
}
/^[a-zA-Z]/ {
sdx = strToSoundex($0)
addHom(sdx, $0)
}
END {
showHoms(3)
}
function strToSoundex(s, sdx, i, ch, cd, lch) {
if (length(s) == 0) return ""
s = tolower(s)
lch = substr(s, 1, 1);
sdx = toupper(lch)
lch = charToSoundex(lch)
for (i = 2; i <= length(s); i++) {
ch = substr(s, i, 1)
cd = charToSoundex(ch)
if (cd == 7) continue;
if (cd && cd != lch) sdx = sdx cd
lch = cd
}
sdx = substr(sdx "0000", 1, 4)
return sdx
}
function charToSoundex(ch, cd) {
if (ch ~ /[bfpv]/) cd = 1
else if (ch ~ /[cgjkqsxz]/) cd = 2
else if (ch ~ /[dt]/) cd = 3
else if (ch == "l") cd = 4
else if (ch ~ /[mn]/) cd = 5
else if (ch == "r") cd = 6
else if (ch ~ /[hw]/) cd = 7
else cd = 0
return cd;
}
function addHom(sdx, word) {
if (!(homs[sdx])) homs[sdx] = ""
homs[sdx] = homs[sdx] (homs[sdx] == "" ? "" : subsep) word
}
function showHoms(toShow, i, n, wl, j) {
for (i in homs) {
printf i " "
n = split(homs[i], wl, subsep)
for (j = 1; j <= toShow && j <= n; j++) {
printf wl[j] " "
}
print (n > toShow ? "..." : "")
}
}
|
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.
| #BBC_BASIC | BBC BASIC | DIM test(9)
test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
PROCshellsort(test(), 10)
FOR i% = 0 TO 9
PRINT test(i%) ;
NEXT
PRINT
END
DEF PROCshellsort(a(), n%)
LOCAL h%, i%, j%, k
h% = n%
WHILE h%
IF h% = 2 h% = 1 ELSE h% DIV= 2.2
FOR i% = h% TO n% - 1
k = a(i%)
j% = i%
WHILE j% >= h% AND k < a(ABS(j% - h%))
a(j%) = a(j% - h%)
j% -= h%
ENDWHILE
a(j%) = k
NEXT
ENDWHILE
ENDPROC |
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.
| #Kotlin | Kotlin | internal const val bars = "▁▂▃▄▅▆▇█"
internal const val n = bars.length - 1
fun <T: Number> Iterable<T>.toSparkline(): String {
var min = Double.MAX_VALUE
var max = Double.MIN_VALUE
val doubles = map { it.toDouble() }
doubles.forEach { i -> when { i < min -> min = i; i > max -> max = i } }
val range = max - min
return doubles.fold("") { line, d -> line + bars[Math.ceil((d - min) / range * n).toInt()] }
}
fun String.toSparkline() = replace(",", "").split(" ").map { it.toFloat() }.toSparkline()
fun main(args: Array<String>) {
val s1 = "1 2 3 4 5 6 7 8 7 6 5 4 3 2 1"
println(s1)
println(s1.toSparkline())
val s2 = "1.5, 0.5 3.5, 2.5 5.5, 4.5 7.5, 6.5"
println(s2)
println(s2.toSparkline())
} |
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.
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
sub merge {
my ($x, $y) = @_;
my @out;
while (@$x and @$y) {
my $t = $x->[-1] <=> $y->[-1];
if ($t == 1) { unshift @out, pop @$x }
elsif ($t == -1) { unshift @out, pop @$y }
else { splice @out, 0, 0, pop(@$x), pop(@$y) }
}
@$x, @$y, @out
}
sub strand {
my $x = shift;
my @out = shift @$x // return;
for (-@$x .. -1) {
push @out, splice @$x, $_, 1 if $x->[$_] >= $out[-1];
}
@out
}
sub strand_sort {
my @x = @_;
my(@out, @strand);
@out = merge \@out, \@strand while @strand = strand(\@x);
@out
}
my @a = map (int rand(100), 1 .. 10);
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)
| #Objective-C | Objective-C | //--------------------------------------------------------------------
// Person class
@interface Person : NSObject {
NSUInteger _candidateIndex;
}
@property (nonatomic, strong) NSString* name;
@property (nonatomic, strong) NSArray* prefs;
@property (nonatomic, weak) Person* fiance;
@end
@implementation Person
+ (instancetype)named:(NSString *)name {
return [[self alloc] initWithName:name];
}
- (instancetype)initWithName:(NSString *)name {
if ((self = [super init])) {
_name = name;
_prefs = nil;
_fiance = nil;
_candidateIndex = 0;
}
return self;
}
- (BOOL)prefers:(Person *)p {
return [_prefs indexOfObject:p] < [_prefs indexOfObject:_fiance];
}
- (Person *)nextCandidateNotYetProposedTo {
if (_candidateIndex >= _prefs.count) return nil;
return _prefs[_candidateIndex++];
}
- (void)engageTo:(Person *)p {
if (p.fiance) p.fiance.fiance = nil;
p.fiance = self;
if (self.fiance) self.fiance.fiance = nil;
self.fiance = p;
}
- (NSString *)description {
return _name;
}
@end
//--------------------------------------------------------------------
BOOL isStable(NSArray *men) {
NSArray *women = ((Person *)men[0]).prefs;
for (Person *guy in men) {
for (Person *gal in women) {
if ([guy prefers:gal] && [gal prefers:guy])
return NO;
}
}
return YES;
}
//--------------------------------------------------------------------
void doMarriage() {
Person *abe = [Person named:@"abe"];
Person *bob = [Person named:@"bob"];
Person *col = [Person named:@"col"];
Person *dan = [Person named:@"dan"];
Person *ed = [Person named:@"ed"];
Person *fred = [Person named:@"fred"];
Person *gav = [Person named:@"gav"];
Person *hal = [Person named:@"hal"];
Person *ian = [Person named:@"ian"];
Person *jon = [Person named:@"jon"];
Person *abi = [Person named:@"abi"];
Person *bea = [Person named:@"bea"];
Person *cath = [Person named:@"cath"];
Person *dee = [Person named:@"dee"];
Person *eve = [Person named:@"eve"];
Person *fay = [Person named:@"fay"];
Person *gay = [Person named:@"gay"];
Person *hope = [Person named:@"hope"];
Person *ivy = [Person named:@"ivy"];
Person *jan = [Person named:@"jan"];
abe.prefs = @[ abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay ];
bob.prefs = @[ cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay ];
col.prefs = @[ hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan ];
dan.prefs = @[ ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi ];
ed.prefs = @[ jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay ];
fred.prefs = @[ bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay ];
gav.prefs = @[ gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay ];
hal.prefs = @[ abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee ];
ian.prefs = @[ hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve ];
jon.prefs = @[ abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope ];
abi.prefs = @[ bob, fred, jon, gav, ian, abe, dan, ed, col, hal ];
bea.prefs = @[ bob, abe, col, fred, gav, dan, ian, ed, jon, hal ];
cath.prefs = @[ fred, bob, ed, gav, hal, col, ian, abe, dan, jon ];
dee.prefs = @[ fred, jon, col, abe, ian, hal, gav, dan, bob, ed ];
eve.prefs = @[ jon, hal, fred, dan, abe, gav, col, ed, ian, bob ];
fay.prefs = @[ bob, abe, ed, ian, jon, dan, fred, gav, col, hal ];
gay.prefs = @[ jon, gav, hal, fred, bob, abe, col, ed, dan, ian ];
hope.prefs = @[ gav, jon, bob, abe, ian, dan, hal, ed, col, fred ];
ivy.prefs = @[ ian, col, hal, gav, fred, bob, abe, ed, jon, dan ];
jan.prefs = @[ ed, hal, gav, abe, bob, jon, col, ian, fred, dan ];
NSArray *men = abi.prefs;
NSUInteger freeMenCount = men.count;
while (freeMenCount > 0) {
for (Person *guy in men) {
if (guy.fiance == nil) {
Person *gal = [guy nextCandidateNotYetProposedTo];
if (gal.fiance == nil) {
[guy engageTo:gal];
freeMenCount--;
} else if ([gal prefers:guy]) {
[guy engageTo:gal];
}
}
}
}
for (Person *guy in men) {
printf("%s is engaged to %s\n", [guy.name UTF8String], [guy.fiance.name UTF8String]);
}
printf("Stable = %d\n", (int)isStable(men));
printf("\nSwitching fred & jon's partners\n");
[fred engageTo:abi];
[jon engageTo:bea];
printf("Stable = %d\n", (int)isStable(men));
}
//--------------------------------------------------------------------
int main(int argc, const char * argv[])
{
@autoreleasepool {
doMarriage();
}
return 0;
} |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #Yabasic | Yabasic | sub esplit$(instring$)
if len(instring$) < 2 return instring$
ret$ = left$(instring$,1)
for i = 2 to len(instring$)
if mid$(instring$,i,1) <> mid$(instring$, i - 1, 1) ret$ = ret$ + ", "
ret$ = ret$ + mid$(instring$, i, 1)
next i
return ret$
end sub
print esplit$("gHHH5YY++///\\") |
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
| #Genie | Genie | [indent=4]
/*
Stack, in Genie, with GLib double ended Queues
valac stack.gs
*/
init
var stack = new Queue of int()
// push
stack.push_tail(2)
stack.push_tail(1)
// pop (and peek at top)
print stack.pop_tail().to_string()
print stack.peek_tail().to_string()
// empty
print "stack size before clear: " + stack.get_length().to_string()
stack.clear()
print "After clear, stack.is_empty(): " + stack.is_empty().to_string() |
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)
| #Fortran | Fortran | PROGRAM SPIRAL
IMPLICIT NONE
INTEGER, PARAMETER :: size = 5
INTEGER :: i, x = 0, y = 1, count = size, n = 0
INTEGER :: array(size,size)
DO i = 1, count
x = x + 1
array(x,y) = n
n = n + 1
END DO
DO
count = count - 1
DO i = 1, count
y = y + 1
array(x,y) = n
n = n + 1
END DO
DO i = 1, count
x = x - 1
array(x,y) = n
n = n + 1
END DO
IF (n > size*size-1) EXIT
count = count - 1
DO i = 1, count
y = y - 1
array(x,y) = n
n = n + 1
END DO
DO i = 1, count
x = x + 1
array(x,y) = n
n = n + 1
END DO
IF (n > size*size-1) EXIT
END DO
DO y = 1, size
DO x = 1, size
WRITE (*, "(I4)", ADVANCE="NO") array (x, y)
END DO
WRITE (*,*)
END DO
END PROGRAM SPIRAL |
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.
| #PL.2FI | PL/I |
Special variables in PL/I are termed "Pseudo-variables".
They are used only on the LHS of an assignment statement.
They include:
REAL to assign the real part of a COMPLEX variable;
IMAG to assign the imaginary part of a COMPLEX variable;
SUBSTR is used to assign part of a string (used on the LHS of an assignment);
STRING when used on the left-hand of an assignment;
UNSPEC used to assign a bit pattern to a variable;
ENTRYADDR is used to assign an address to an ENTRY variable that is
to be invoked;
ONCHAR resets the current value of the CHAR built-in function (when
a data conversion error occurs, and it is desired to re-attempt
the conversion);
ONSOURCE assigns a new value to the ONSOURCE built-in function
(may be used when a data conversion error occurs,
and a re-try of the conversion is to be attempted with modified data);
ONGSOURCE assigns a new value to the ONGSOURCE built-in function
(may be used when a data conversion error occurs,
and may be used when a re-try of the conversion is to be
attempted with modified data).
|
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.
| #PowerShell | PowerShell |
<#
$$
$?
$^
$_
$Args
$ConsoleFileName
$Error
$Event
$EventSubscriber
$ExecutionContext
$False
$ForEach
$Home
$Host
$Input
$LastExitCode
$Matches
$MyInvocation
$NestedPromptLevel
$NULL
$PID
$Profile
$PSBoundParameters
$PsCmdlet
$PsCulture
$PSDebugContext
$PsHome
$PSitem
$PSScriptRoot
$PsUICulture
$PsVersionTable
$Pwd
$Sender
$ShellID
$SourceArgs
$SourceEventArgs
$This
$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.
| #PureBasic | PureBasic | names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split()))
print( '\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) ) |
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.
| #ALGOL_68 | ALGOL 68 | PROC radixsort = (REF []INT array) VOID:
(
[UPB array]INT zero;
[UPB array]INT one;
BITS mask := 16r01;
INT zero_index := 0,
one_index := 0,
array_index := 1;
WHILE ABS(mask) > 0 DO
WHILE array_index <= UPB array DO
IF (BIN(array[array_index]) AND mask) = 16r0 THEN
zero_index +:= 1;
zero[zero_index] := array[array_index]
ELSE
one_index +:= 1;
one[one_index] := array[array_index]
FI;
array_index +:= 1
OD;
array_index := 1;
FOR i FROM 1 TO zero_index DO
array[array_index] := zero[i];
array_index +:= 1
OD;
FOR i FROM 1 TO one_index DO
array[array_index] := one[i];
array_index +:=1
OD;
array_index := 1;
zero_index := one_index := 0;
mask := mask SHL 1
OD
);
main:
(
[10]INT a;
FOR i FROM 1 TO UPB a DO
a[i] := ROUND(random*1000)
OD;
print(("Before:", a));
print((newline, newline));
radixsort(a);
print(("After: ", a))
) |
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
| #BBC_BASIC | BBC BASIC | DIM test(9)
test() = 4, 65, 2, 31, 0, 99, 2, 83, 782, 1
perms% = 0
WHILE NOT FNsorted(test())
perms% += 1
PROCnextperm(test())
ENDWHILE
PRINT ;perms% " permutations required to sort "; DIM(test(),1)+1 " items."
END
DEF PROCnextperm(a())
LOCAL last%, maxindex%, p%
maxindex% = DIM(a(),1)
IF maxindex% < 1 THEN ENDPROC
p% = maxindex%-1
WHILE a(p%) >= a(p%+1)
p% -= 1
IF p% < 0 THEN
PROCreverse(a(), 0, maxindex%)
ENDPROC
ENDIF
ENDWHILE
last% = maxindex%
WHILE a(last%) <= a(p%)
last% -= 1
ENDWHILE
SWAP a(p%), a(last%)
PROCreverse(a(), p%+1, maxindex%)
ENDPROC
DEF PROCreverse(a(), first%, last%)
WHILE first% < last%
SWAP a(first%), a(last%)
first% += 1
last% -= 1
ENDWHILE
ENDPROC
DEF FNsorted(d())
LOCAL I%
FOR I% = 1 TO DIM(d(),1)
IF d(I%) < d(I%-1) THEN = FALSE
NEXT
= TRUE |
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
| #C | C | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int(*cmp_func)(const void*, const void*);
void perm_sort(void *a, int n, size_t msize, cmp_func _cmp)
{
char *p, *q, *tmp = malloc(msize);
# define A(i) ((char *)a + msize * (i))
# define swap(a, b) {\
memcpy(tmp, a, msize);\
memcpy(a, b, msize);\
memcpy(b, tmp, msize); }
while (1) {
/* find largest k such that a[k - 1] < a[k] */
for (p = A(n - 1); (void*)p > a; p = q)
if (_cmp(q = p - msize, p) > 0)
break;
if ((void*)p <= a) break;
/* find largest l such that a[l] > a[k - 1] */
for (p = A(n - 1); p > q; p-= msize)
if (_cmp(q, p) > 0) break;
swap(p, q); /* swap a[k - 1], a[l] */
/* flip a[k] through a[end] */
for (q += msize, p = A(n - 1); q < p; q += msize, p -= msize)
swap(p, q);
}
free(tmp);
}
int scmp(const void *a, const void *b) { return strcmp(*(const char *const *)a, *(const char *const *)b); }
int main()
{
int i;
const char *strs[] = { "spqr", "abc", "giant squid", "stuff", "def" };
perm_sort(strs, 5, sizeof(*strs), scmp);
for (i = 0; i < 5; i++)
printf("%s\n", strs[i]);
return 0;
} |
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
| #Kotlin | Kotlin | # defined local ie. #mylocal will fail if not defined
$ defined variable ie. $myvar will fail if not defined
= assignment
:= assign as return assigned value
? ternary conditional true ? this
| ternary else false ? this | that
|| or
&& and
! negative operator
{ open capture
} close capture
=> specify givenblock / capture
-> invoke method: mytype->mymethod
& retarget: mytype->mymethod& // returns mytype
^ autocollect from capture: {^ 'this will be outputted' ^}
:: tag prefix, ie. ::mytype->gettype // returns myype
:: type constraint, ie. define mymethod(p::integer) => #i * 2
\ escape method: ie. \mymethod->invoke(2)
// comment
/* open comment
*/ close comment |
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
| #Lasso | Lasso | # defined local ie. #mylocal will fail if not defined
$ defined variable ie. $myvar will fail if not defined
= assignment
:= assign as return assigned value
? ternary conditional true ? this
| ternary else false ? this | that
|| or
&& and
! negative operator
{ open capture
} close capture
=> specify givenblock / capture
-> invoke method: mytype->mymethod
& retarget: mytype->mymethod& // returns mytype
^ autocollect from capture: {^ 'this will be outputted' ^}
:: tag prefix, ie. ::mytype->gettype // returns myype
:: type constraint, ie. define mymethod(p::integer) => #i * 2
\ escape method: ie. \mymethod->invoke(2)
// comment
/* open comment
*/ close comment |
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
| #LaTeX | LaTeX | \documentclass{minimal}
\begin{document}
5\% of \$10
\end{document} |
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
| #Common_Lisp | Common Lisp | (defun stooge-sort (vector &optional (i 0) (j (1- (length vector))))
(when (> (aref vector i) (aref vector j))
(rotatef (aref vector i) (aref vector j)))
(when (> (- j i) 1)
(let ((third (floor (1+ (- j i)) 3)))
(stooge-sort vector i (- j third))
(stooge-sort vector (+ i third) j)
(stooge-sort vector i (- j third))))
vector) |
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.
| #Emacs_Lisp | Emacs Lisp | (dolist (i '(3 1 4 1 5 92 65 3 5 89 79 3))
(run-with-timer (* i 0.001) nil 'message "%d" i)) |
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.
| #Erlang | Erlang | #!/usr/bin/env escript
%% -*- erlang -*-
%%! -smp enable -sname sleepsort
main(Args) ->
lists:foreach(fun(Arg) ->
timer:send_after(5 * list_to_integer(Arg), self(), Arg)
end, Args),
loop(length(Args)).
loop(0) ->
ok;
loop(N) ->
receive
Num ->
io:format("~s~n", [Num]),
loop(N - 1)
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].
| #ALGOL_68 | ALGOL 68 | MODE DATA = REF CHAR;
PROC in place selection sort = (REF[]DATA a)VOID:
BEGIN
INT min;
DATA temp;
FOR i FROM LWB a TO UPB a DO
min := i;
FOR j FROM i + 1 TO UPB a DO
IF a [min] > a [j] THEN
min := j
FI
OD;
IF min /= i THEN
temp := a [i];
a [i] := a [min];
a [min] := temp
FI
OD
END # in place selection sort #;
[32]CHAR data := "big fjords vex quick waltz nymph";
[UPB data]DATA ref data; FOR i TO UPB data DO ref data[i] := data[i] OD;
in place selection sort(ref data);
FOR i TO UPB ref data DO print(ref data[i]) OD; print(new line);
print((data)) |
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.
| #BBC_BASIC | BBC BASIC | DATA Ashcraft, Ashcroft, Gauss, Ghosh, Hilbert, Heilbronn, Lee, Lloyd
DATA Moses, Pfister, Robert, Rupert, Rubin, Tymczak, Soundex, Example
FOR i% = 1 TO 16
READ name$
PRINT """" name$ """" TAB(15) FNsoundex(name$)
NEXT
END
DEF FNsoundex(name$)
LOCAL i%, n%, p%, n$, s$
name$ = FNupper(name$)
n$ = "01230129022455012623019202"
s$ = LEFT$(name$,1)
p% = VALMID$(n$, ASCs$ - 64, 1)
FOR i% = 2 TO LEN(name$)
n% = VALMID$(n$, ASCMID$(name$,i%,1) - 64, 1)
IF n% IF n% <> 9 IF n% <> p% s$ += STR$(n%)
IF n% <> 9 p% = n%
NEXT
= LEFT$(s$ + "000", 4)
DEF FNupper(A$)
LOCAL A%,C%
FOR A% = 1 TO LEN(A$)
C% = ASCMID$(A$,A%)
IF C% >= 97 IF C% <= 122 MID$(A$,A%,1) = CHR$(C%-32)
NEXT
= A$ |
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.
| #BCPL | BCPL | GET "libhdr"
LET shellsort(v, upb) BE
{ LET m = 1
UNTIL m>upb DO m := m*3 + 1 // Find first suitable value in the
// series: 1, 4, 13, 40, 121, 364, ...
{ m := m/3
FOR i = m+1 TO upb DO
{ LET vi = v!i
LET j = i
{ LET k = j - m
IF k<=0 | v!k < vi BREAK
v!j := v!k
j := k
} REPEAT
v!j := vi
}
} REPEATUNTIL m=1
}
MANIFEST { upb = 10000 }
LET start() = VALOF
{ LET v = getvec(upb)
try("shell", shellsort, v, upb)
writes("*nEnd of test*n")
freevec(v)
RESULTIS 0
}
AND try(name, sortroutine, v, upb) BE
{ // delay, referencing the first and last elements of v
FOR i = 1 TO 50000 DO v!upb := v!1
writef("*nSetting %n words of data for %s sort*n", upb, name)
FOR i = 1 TO upb DO v!i := randno(10000)
writef("Entering %s sort routine*n", name)
sortroutine(v, upb)
writes("Sorting complete*n")
TEST sorted(v, upb)
THEN writes("The data is now sorted*n")
ELSE writef("### ERROR: %s sort does not work*n", name)
}
AND sorted(v, n) = VALOF
{ //FOR i = 1 TO n-1 UNLESS v!i<=v!(i+1) RESULTIS FALSE
RESULTIS TRUE
} |
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 | C | #include <stdio.h>
void shell_sort (int *a, int n) {
int h, i, j, t;
for (h = n; h /= 2;) {
for (i = h; i < n; i++) {
t = a[i];
for (j = i; j >= h && t < a[j - h]; j -= h) {
a[j] = a[j - h];
}
a[j] = t;
}
}
}
int main (int ac, char **av) {
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
int n = sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
shell_sort(a, n);
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
return 0;
}
|
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.
| #LiveCode | LiveCode | command sparklines listOfNums
local utfbase=0x2581
local tStats, utfp, tmin,tmax,trange
put listOfNums into tStats
replace ", " with space in tStats
replace space with comma in tStats
put min(tStats) into tmin
put max(tStats) into tmax
put tmax - tmin into trange
put "Min:" && tmin && tab into plot
put "Max:" && tmax && tab after plot
put "Range:" && trange && tab after plot
put "Mean" && average(tStats) && tab after plot
put "Stdev:" && standardDeviation(tStats) && tab after plot
put "Variance:" && variance(tStats) && return after plot
repeat for each item i in tStats
put (round(i - tmin/trange * 7)) + utfbase into utfp
put numToCodepoint(utfp) after plot
end repeat
put plot
end sparklines |
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.
| #M2000_Interpreter | M2000 Interpreter |
Module CheckIt {
Function Row$(a) {
def item$(a)=str$(car(a)#val(0),0)
rep$=item$(a)
while len(a)
rep$+=", "+item$(a)
a=cdr(a)
End While
=rep$
}
Font "Dejavu Sans Mono"
Cls
Const bar$="▁▂▃▄▅▆▇█"
Document doc$
data1=(1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1)
data2=(1.5, 0.5, 3.5, 2.5, 5.5, 4.5, 7.5, 6.5)
SparkLine(data1)
SparkLine(data2)
Clipboard doc$
Sub SparkLine(dat as array)
Local min=dat#min(), range=(dat#max()-dat#min()), range1=7/range
Local item, rep$="Input:"+Row$(dat)+{
}
item=each(dat)
While item
rep$+=Mid$(bar$,(array(item)-min)*range1+1 ,1)
End While
rep$+=" ("+str$(range,1033)+")"
doc$=rep$+{
}
Report rep$
End Sub
}
Checkit
|
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.
| #Phix | Phix | with javascript_semantics
function merge(sequence left, right)
sequence result = {}
while length(left)>0
and length(right)>0 do
if left[$]<=right[1] then
exit
elsif right[$]<=left[1] then
return result & right & left
elsif left[1]<right[1] then
result = append(result,left[1])
left = left[2..$]
else
result = append(result,right[1])
right = right[2..$]
end if
end while
return result & left & right
end function
function strand_sort(sequence s)
sequence result = {}
while length(s)>0 do
integer j = length(s)
for i=1 to length(s)-1 do
if s[i]>s[i+1] then
j = i
exit
end if
end for
result = merge(result,s[1..j])
s = s[j+1..$]
end while
return result
end function
?strand_sort(shuffle(tagset(10)))
|
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)
| #OCaml | OCaml | let men = [
"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"];
]
let women = [
"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"];
]
type woman_name = string
type man_name = string
type man =
{ m_name: man_name;
mutable free: bool;
women_rank: woman_name list;
has_proposed: (woman_name, unit) Hashtbl.t (* a set *)
}
type woman =
{ w_name: woman_name;
men_rank: man_name list;
mutable engaged: man_name option
}
let prefers w m1 m2 =
(* returns true if w has a lower (better) rank for m1 than m2 *)
let rec aux = function
| [] -> invalid_arg "rank_cmp"
| x::_ when x = m1 -> true
| x::_ when x = m2 -> false
| _::xs -> aux xs
in
aux w.men_rank
let take_while f lst =
let rec aux acc = function
| x::xs when f x -> aux (x::acc) xs
| _ -> List.rev acc
in
aux [] lst
let more_ranked_than name =
take_while ((<>) name)
let build_structs ~men ~women =
List.map (fun (name, rank) ->
{ m_name = name;
women_rank = rank;
free = true;
has_proposed = Hashtbl.create 42 }
) men,
List.map (fun (name, rank) ->
{ w_name = name;
men_rank = rank;
engaged = None }
) women
let _stable_matching ms ws =
let men_by_name = Hashtbl.create 42 in
List.iter (fun m -> Hashtbl.add men_by_name m.m_name m) ms;
let women_by_name = Hashtbl.create 42 in
List.iter (fun w -> Hashtbl.add women_by_name w.w_name w) ws;
try
while true do
(*TODO free men who still has some w to propose to *)
let m = List.find (fun m -> m.free) ms in
(* highest ranked woman who the man has not proposed to yet *)
let w_name =
List.find (fun w -> not (Hashtbl.mem m.has_proposed w)) m.women_rank in
Hashtbl.add m.has_proposed w_name ();
let w = Hashtbl.find women_by_name w_name in
match w.engaged with
| None -> (* w is free *)
(* (m, w) become engaged *)
w.engaged <- Some m.m_name;
m.free <- false
| Some m'_name -> (* some pair (m', w) already exists *)
if prefers w m.m_name m'_name
then begin (* w prefers m to m' *)
w.engaged <- Some m.m_name;
let m' = Hashtbl.find men_by_name m'_name in
m'.free <- true;
m.free <- false
end
done;
assert false
with Not_found -> ()
let stable_matching ~men ~women =
let ms, ws = build_structs ~men ~women in
_stable_matching ms ws;
let some = function Some v -> v | None -> "" in
List.map (fun w -> w.w_name, some w.engaged) ws
let is_stable ~men ~women eng =
let ms, ws = build_structs ~men ~women in
not (List.exists (fun (wn, mn) ->
let m = List.find (fun m -> m.m_name = mn) ms in
let prefered_women = more_ranked_than wn m.women_rank in
List.exists (fun pref_w ->
let w = List.find (fun w -> w.w_name = pref_w) ws in
let eng_m = List.assoc pref_w eng in
let prefered_men = more_ranked_than eng_m w.men_rank in
List.mem m.m_name prefered_men (* exists unstable engagement *)
) prefered_women
) eng)
let perturb_engagements eng =
Random.self_init();
let eng = Array.of_list eng in
let len = Array.length eng in
for n = 1 to 3 do
let i = Random.int len
and j = Random.int len in
let w1, m1 = eng.(i)
and w2, m2 = eng.(j) in
eng.(i) <- (w1, m2);
eng.(j) <- (w2, m1);
done;
Array.to_list eng
let print engs =
List.iter (fun (w,m) ->
Printf.printf " %4s is engaged with %s\n" w m) engs;
Printf.printf "# Engagements %s stable\n"
(if is_stable ~men ~women engs then "are" else "are not")
let () =
let engagements = stable_matching ~men ~women in
print engagements;
print_endline "========================";
let engagements = perturb_engagements engagements in
print engagements;
;; |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #Z80_Assembly | Z80 Assembly | PrintChar equ &BB5A ;Amstrad CPC BIOS call
Terminator equ 0 ;marks the end of a string
org &8000
LD HL,StringA
loop:
ld a,(HL) ;load a char from (HL)
cp Terminator ;is it the terminator?
ret z ;if so, exit
ld e,a ;store this char in E temporarily
inc hl ;next char
ld a,(HL) ;get next char
cp Terminator ;is the next char the terminator?
jp z,StringDone ;if so, print E and exit.
;needed to prevent the last char from getting a comma and space.
dec hl ;go back one so we don't skip any chars
cp e ;does (HL) == (HL+1)?
push af
ld a,e
call PrintChar ;either way, print E to screen.
pop af ;retrieve the results of the last compare.
jr z,SkipComma ;if A=E, no comma or space. Just loop again.
ld a,','
call PrintChar
ld a,' '
call PrintChar
SkipComma:
inc hl ;next char
jp loop ;back to start
StringDone:
ld a,e ;last character in string is printed here.
jp PrintChar
ReturnToBasic:
RET
StringA:
byte "gHHH5YY++///\",0 |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #zkl | zkl | fcn group(str){
C,out := str[0],Sink(C);
foreach c in (str[1,*]){ out.write(if(c==C) c else String(", ",C=c)) }
out.close();
}
group("gHHH5YY++///\\").println(); |
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
| #Go | Go | var intStack []int |
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)
| #FreeBASIC | FreeBASIC | ' FB 1.05.0 Win64
Enum Direction
across
down
back
up
End Enum
Dim As Integer n
Do
Input "Enter size of matrix "; n
Loop Until n > 0
Dim spiral(1 To n, 1 To n) As Integer '' all zero by default
' enter the numbers 0 to (n^2 - 1) spirally in the matrix
Dim As Integer row = 1, col = 1, lowRow = 1, highRow = n, lowCol = 1, highCol = n
Dim d As Direction = across
For i As Integer = 0 To (n * n - 1)
spiral(row, col) = i
Select Case d
Case across
col += 1
If col > highCol Then
col = highCol
row += 1
d = down
End if
Case down
row += 1
If row > highRow Then
row = highRow
col -= 1
d = back
End if
Case back
col -= 1
If col < lowCol Then
col = lowCol
row -= 1
d = up
lowRow += 1
End If
Case up
row -= 1
If row < lowRow Then
row = lowRow
col += 1
d = across
highRow -= 1
lowCol += 1
highCol -= 1
End If
End Select
Next
' print spiral matrix if n < 20
Print
If n < 20 Then
For i As Integer = 1 To n
For j As Integer = 1 To n
Print Using "####"; spiral(i, j);
Next j
Print
Next i
Else
Print "Matrix is too big to display on 80 column console"
End If
Print
Print "Press any key to quit"
Sleep |
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.
| #Python | Python | names = sorted((set(globals().keys()) | set(__builtins__.__dict__.keys())) - set('_ names i'.split()))
print( '\n'.join(' '.join(names[i:i+8]) for i in range(0, len(names), 8)) ) |
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.
| #Quackery | Quackery | $foo scalar (object)
@foo ordered array
%foo unordered hash (associative array)
&foo code/rule/token/regex
::foo package/module/class/role/subset/enum/type/grammar |
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.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program radixSort1.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/* for constantes see task include a file in arm assembly */
/************************************/
/* Constantes */
/************************************/
.include "../constantes.inc"
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSortOk: .asciz "Table sorted.\n"
szMessSortNok: .asciz "Table not sorted !!!!!.\n"
sMessResult: .asciz "Value : @ \n"
szCarriageReturn: .asciz "\n"
.align 4
TableNumber: .int 1,110,30,6,201,5004,29,10,1008,4,7,-25000
#TableNumber: .int 10,9,8,7,6,5,4,3,2,1
.equ NBELEMENTS, (. - TableNumber) / 4
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrTableNumber @ address number table
mov r1,#0 @ first element
mov r2,#NBELEMENTS @ number of élements
bl radixSort
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 1f
ldr r0,iAdrszMessSortNok @ no !! error sort
bl affichageMess
b 100f
1: @ 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
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
/******************************************************************/
/* radix sort */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the first element */
/* r2 contains the number of element */
radixSort:
push {r3-r10,lr} @ save registers
mov r7,#0b1111 @ mask one digit hexa
mov r10,#0 @ digit counter
1:
add r3,r1,#1 @ start index i
2: @ start loop
ldr r4,[r0,r3,lsl #2] @ load value A[i]
and r8,r4,r7 @ and mask
sub r5,r3,#1 @ index j
3:
ldr r6,[r0,r5,lsl #2] @ load value A[j]
and r9,r6,r7 @ and mask
cmp r9,r8 @ compare one digit hexa
ble 4f
add r5,#1 @ increment index j
str r6,[r0,r5,lsl #2] @ store value A[j+1]
sub r5,#2 @ j = j - 1
cmp r5,r1
bge 3b @ loop if j >= first item
4:
add r5,#1 @ increment index j
str r4,[r0,r5,lsl #2] @ store value A[i] in A[j+1]
add r3,#1 @ increment index i
cmp r3,r2 @ end ?
blt 2b @ no -> loop
//bl displayTable
lsl r7,#4 @ shift mask 4 bits left
add r10,r10,#1 @ increment counter
cmp r10,#8 @ 8 digits ?
blt 1b @ no loop
100:
pop {r3-r10,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,iAdrsZoneConv @
bl conversion10S @ décimal conversion
ldr r0,iAdrsMessResult
ldr r1,iAdrsZoneConv @ insert conversion
bl strInsertAtCharInc
bl affichageMess @ display message
add r3,#1
cmp r3,#NBELEMENTS - 1
ble 1b
ldr r0,iAdrszCarriageReturn
bl affichageMess
mov r0,r2
100:
pop {r0-r3,lr}
bx lr
iAdrsZoneConv: .int sZoneConv
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.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
| #C.23 | C# |
public static class PermutationSorter
{
public static void Sort<T>(List<T> list) where T : IComparable
{
PermutationSort(list, 0);
}
public static bool PermutationSort<T>(List<T> list, int i) where T : IComparable
{
int j;
if (issorted(list, i))
{
return true;
}
for (j = i + 1; j < list.Count; j++)
{
T temp = list[i];
list[i] = list[j];
list[j] = temp;
if (PermutationSort(list, i + 1))
{
return true;
}
temp = list[i];
list[i] = list[j];
list[j] = temp;
}
return false;
}
public static bool issorted<T>(List<T> list, int i) where T : IComparable
{
for (int j = list.Count-1; j > 0; j--)
{
if(list[j].CompareTo(list[j-1])<0)
{
return false;
}
}
return true;
}
}
|
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
| #Lilypond | Lilypond | str = "Hello " & QUOTE & "world!" & QUOTE
put str
-- "Hello "world!"" |
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
| #D | D | import std.stdio, std.algorithm, std.array;
void stoogeSort(T)(T[] seq) pure nothrow {
if (seq.back < seq.front)
swap(seq.front, seq.back);
if (seq.length > 2) {
immutable m = seq.length / 3;
seq[0 .. $ - m].stoogeSort();
seq[m .. $].stoogeSort();
seq[0 .. $ - m].stoogeSort();
}
}
void main() {
auto data = [1, 4, 5, 3, -6, 3, 7, 10, -2, -5];
data.stoogeSort();
writeln(data);
} |
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.
| #Euphoria | Euphoria | include get.e
integer count
procedure sleeper(integer key)
? key
count -= 1
end procedure
sequence s, val
atom task
s = command_line()
s = s[3..$]
if length(s)=0 then
puts(1,"Nothing to sort.\n")
else
count = 0
for i = 1 to length(s) do
val = value(s[i])
if val[1] = GET_SUCCESS then
task = task_create(routine_id("sleeper"),{val[2]})
task_schedule(task,{val[2],val[2]}/10)
count += 1
end if
end for
while count do
task_yield()
end while
end if |
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].
| #AppleScript | AppleScript | on selectionSort(theList, l, r) -- Sort items l thru r of theList in place.
set listLength to (count theList)
if (listLength < 2) then return
-- Convert negative and/or transposed range indices.
if (l < 0) then set l to listLength + l + 1
if (r < 0) then set r to listLength + r + 1
if (l > r) then set {l, r} to {r, l}
script o
property lst : theList
end script
repeat with i from l to (r - 1)
set iVal to o's lst's item i
set minVal to iVal
set minPos to i
repeat with j from (i + 1) to r
set jVal to o's lst's item j
if (minVal > jVal) then
set minVal to jVal
set minPos to j
end if
end repeat
set o's lst's item minPos to iVal
set o's lst's item i to minVal
end repeat
return -- nothing.
end selectionSort
property sort : selectionSort
on demo()
set theList to {988, 906, 151, 71, 712, 177, 945, 558, 31, 627}
sort(theList, 1, -1)
return theList
end demo
demo() |
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.
| #Befunge | Befunge | >:~>:48*\`#v_::"`"`\"{"\`*v
^$$_v#!*`*8 8\`\"["::-**84<
>$1^>:88*>v>$$1->vp7+2\"0"<
|!-g71:g8-< >1+::3`!>|
>17p\:!v@p7 10,+55$$<$
v+1p7+2_\$17g\17gv>>+:>5`|2
v$$:$$_^#\<1!-"0"<^1,<g7:<<
v??????????????????????????
v01230120022455012623010202 |
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.23 | C# |
public static class ShellSorter
{
public static void Sort<T>(IList<T> list) where T : IComparable
{
int n = list.Count;
int h = 1;
while (h < (n >> 1))
{
h = (h << 1) + 1;
}
while (h >= 1)
{
for (int i = h; i < n; i++)
{
int k = i - h;
for (int j = i; j >= h && list[j].CompareTo(list[k]) < 0; k -= h)
{
T temp = list[j];
list[j] = list[k];
list[k] = temp;
j = k;
}
}
h >>= 1;
}
}
}
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | toSparkline[data_String] := FromCharacterCode[Round[7 Rescale@Flatten@ImportString[data, "Table", "FieldSeparators" -> {" ", ","}]] + 16^^2581]; |
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.
| #PHP | PHP | $lst = new SplDoublyLinkedList();
foreach (array(1,20,64,72,48,75,96,55,42,74) as $v)
$lst->push($v);
foreach (strandSort($lst) as $v)
echo "$v ";
function strandSort(SplDoublyLinkedList $lst) {
$result = new SplDoublyLinkedList();
while (!$lst->isEmpty()) {
$sorted = new SplDoublyLinkedList();
$remain = new SplDoublyLinkedList();
$sorted->push($lst->shift());
foreach ($lst as $item) {
if ($sorted->top() <= $item) {
$sorted->push($item);
} else {
$remain->push($item);
}
}
$result = _merge($sorted, $result);
$lst = $remain;
}
return $result;
}
function _merge(SplDoublyLinkedList $left, SplDoublyLinkedList $right) {
$res = new SplDoublyLinkedList();
while (!$left->isEmpty() && !$right->isEmpty()) {
if ($left->bottom() <= $right->bottom()) {
$res->push($left->shift());
} else {
$res->push($right->shift());
}
}
foreach ($left as $v) $res->push($v);
foreach ($right as $v) $res->push($v);
return $res;
} |
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)
| #Perl | Perl | #!/usr/bin/env perl
use strict;
use warnings;
use feature qw/say/;
use List::Util qw(first);
my %Likes = (
M => {
abe => [qw/ abi eve cath ivy jan dee fay bea hope gay /],
bob => [qw/ cath hope abi dee eve fay bea jan ivy gay /],
col => [qw/ hope eve abi dee bea fay ivy gay cath jan /],
dan => [qw/ ivy fay dee gay hope eve jan bea cath abi /],
ed => [qw/ jan dee bea cath fay eve abi ivy hope gay /],
fred => [qw/ bea abi dee gay eve ivy cath jan hope fay /],
gav => [qw/ gay eve ivy bea cath abi dee hope jan fay /],
hal => [qw/ abi eve hope fay ivy cath jan bea gay dee /],
ian => [qw/ hope cath dee gay bea abi fay ivy jan eve /],
jon => [qw/ abi fay jan gay eve bea dee cath ivy hope /],
},
W => {
abi => [qw/ bob fred jon gav ian abe dan ed col hal /],
bea => [qw/ bob abe col fred gav dan ian ed jon hal /],
cath => [qw/ fred bob ed gav hal col ian abe dan jon /],
dee => [qw/ fred jon col abe ian hal gav dan bob ed /],
eve => [qw/ jon hal fred dan abe gav col ed ian bob /],
fay => [qw/ bob abe ed ian jon dan fred gav col hal /],
gay => [qw/ jon gav hal fred bob abe col ed dan ian /],
hope => [qw/ gav jon bob abe ian dan hal ed col fred /],
ivy => [qw/ ian col hal gav fred bob abe ed jon dan /],
jan => [qw/ ed hal gav abe bob jon col ian fred dan /],
},
);
my %Engaged;
my %Proposed;
match_them();
check_stability();
perturb();
check_stability();
sub match_them {
say 'Matchmaking:';
while(my $man = unmatched_man()) {
my $woman = preferred_choice($man);
$Proposed{$man}{$woman} = 1;
if(! $Engaged{W}{$woman}) {
engage($man, $woman);
say "\t$woman and $man";
}
else {
if(woman_prefers($woman, $man)) {
my $engaged_man = $Engaged{W}{$woman};
engage($man, $woman);
undef $Engaged{M}{$engaged_man};
say "\t$woman dumped $engaged_man for $man";
}
}
}
}
sub check_stability {
say 'Stablility:';
my $stable = 1;
foreach my $m (men()) {
foreach my $w (women()) {
if(man_prefers($m, $w) && woman_prefers($w, $m)) {
say "\t$w prefers $m to $Engaged{W}{$w} and $m prefers $w to $Engaged{M}{$m}";
$stable = 0;
}
}
}
if($stable) {
say "\t(all marriages stable)";
}
}
sub unmatched_man {
return first { ! $Engaged{M}{$_} } men();
}
sub preferred_choice {
my $man = shift;
return first { ! $Proposed{$man}{$_} } @{ $Likes{M}{$man} };
}
sub engage {
my ($man, $woman) = @_;
$Engaged{W}{$woman} = $man;
$Engaged{M}{$man} = $woman;
}
sub prefers {
my $sex = shift;
return sub {
my ($person, $prospect) = @_;
my $choices = join ' ', @{ $Likes{$sex}{$person} };
return index($choices, $prospect) < index($choices, $Engaged{$sex}{$person});
}
}
BEGIN {
*woman_prefers = prefers('W');
*man_prefers = prefers('M');
}
sub perturb {
say 'Perturb:';
say "\tengage abi with fred and bea with jon";
engage('fred' => 'abi');
engage('jon' => 'bea');
}
sub men { keys %{ $Likes{M} } }
sub women { keys %{ $Likes{W} } } |
http://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character | Split a character string based on change of character |
Task
Split a (character) string into comma (plus a blank) delimited
strings based on a change of character (left to right).
Show the output here (use the 1st example below).
Blanks should be treated as any other character (except
they are problematic to display clearly). The same applies
to commas.
For instance, the string:
gHHH5YY++///\
should be split and show:
g, HHH, 5, YY, ++, ///, \
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
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 LET s$="gHHH5YY++///\"
20 LET c$=s$(1)
30 LET n$=c$
40 FOR i=2 TO LEN s$
50 IF s$(i)<>c$ THEN LET n$=n$+", "
60 LET n$=n$+s$(i)
70 LET c$=s$(i)
80 NEXT i
90 PRINT n$ |
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
| #Groovy | Groovy | def stack = []
assert stack.empty
stack.push(55)
stack.push(21)
stack.push('kittens')
assert stack.last() == 'kittens'
assert stack.size() == 3
assert ! stack.empty
println stack
assert stack.pop() == "kittens"
assert stack.size() == 2
println stack
stack.push(-20)
println stack
stack.push( stack.pop() * stack.pop() )
assert stack.last() == -420
assert stack.size() == 2
println stack
stack.push(stack.pop() / stack.pop())
assert stack.size() == 1
println stack
println stack.pop()
assert stack.size() == 0
assert stack.empty
try { stack.pop() } catch (NoSuchElementException e) { println e.message } |
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)
| #GAP | GAP | # Spiral matrix with numbers 1 .. n<sup>2</sup>, more natural in GAP
SpiralMatrix := function(n)
local i, j, k, di, dj, p, vi, vj, imin, imax, jmin, jmax;
a := NullMat(n, n);
vi := [ 1, 0, -1, 0 ];
vj := [ 0, 1, 0, -1 ];
imin := 0;
imax := n;
jmin := 1;
jmax := n + 1;
p := 1;
di := vi[p];
dj := vj[p];
i := 1;
j := 1;
for k in [1 .. n*n] do
a[j][i] := k;
i := i + di;
j := j + dj;
if i < imin or i > imax or j < jmin or j > jmax then
i := i - di;
j := j - dj;
p := RemInt(p, 4) + 1;
di := vi[p];
dj := vj[p];
i := i + di;
j := j + dj;
if p = 1 then
imax := imax - 1;
elif p = 2 then
jmax := jmax - 1;
elif p = 3 then
imin := imin + 1;
else
jmin := jmin + 1;
fi;
fi;
od;
return a;
end;
PrintArray(SpiralMatrix(5));
# [ [ 1, 2, 3, 4, 5 ],
# [ 16, 17, 18, 19, 6 ],
# [ 15, 24, 25, 20, 7 ],
# [ 14, 23, 22, 21, 8 ],
# [ 13, 12, 11, 10, 9 ] ] |
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.
| #Racket | Racket | $foo scalar (object)
@foo ordered array
%foo unordered hash (associative array)
&foo code/rule/token/regex
::foo package/module/class/role/subset/enum/type/grammar |
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.
| #Raku | Raku | $foo scalar (object)
@foo ordered array
%foo unordered hash (associative array)
&foo code/rule/token/regex
::foo package/module/class/role/subset/enum/type/grammar |
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.
| #Arturo | Arturo | radixSort: function [items][
base: 10
a: new items
rounds: inc floor (ln max a)/ln base
loop rounds 'i [
buckets: array.of: 2*base []
baseI: base ^ i
loop a 'n [
digit: last digits n
if n >= 0 -> digit: digit + base
buckets\[digit]: buckets\[digit] ++ n
]
a: new flatten buckets
]
return a
]
print radixSort [3 1 2 8 5 7 9 4 6] |
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
| #C.2B.2B | C++ | #include <algorithm>
template<typename ForwardIterator>
void permutation_sort(ForwardIterator begin, ForwardIterator end)
{
while (std::next_permutation(begin, end))
{
// -- this block intentionally left empty --
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.