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/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
| #Ring | Ring |
see split("gHHH5YY++///\")
func split(s )
c =left (s, 1)
split = ""
for i = 1 to len(s)
d = substr(s, i, 1)
if d != c
split = split + ", "
c = d
ok
split = split + d
next
return split
|
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
| #Ruby | Ruby | def split(str)
puts " input string: #{str}"
s = str.chars.chunk(&:itself).map{|_,a| a.join}.join(", ")
puts "output string: #{s}"
s
end
split("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
| #Erlang | Erlang | -module(stack).
-export([empty/1, new/0, pop/1, push/2, top/1]).
new() -> [].
empty([]) -> true;
empty(_) -> false.
pop([H|T]) -> {H,T}.
push(H,T) -> [H|T].
top([H|_]) -> H. |
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)
| #Common_Lisp | Common Lisp | (defun spiral (rows columns)
(do ((N (* rows columns))
(spiral (make-array (list rows columns) :initial-element nil))
(dx 1) (dy 0) (x 0) (y 0)
(i 0 (1+ i)))
((= i N) spiral)
(setf (aref spiral y x) i)
(let ((nx (+ x dx)) (ny (+ y dy)))
(cond
((and (< -1 nx columns)
(< -1 ny rows)
(null (aref spiral ny nx)))
(setf x nx
y ny))
(t (psetf dx (- dy)
dy dx)
(setf x (+ x dx)
y (+ y dy))))))) |
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.
| #M2000_Interpreter | M2000 Interpreter |
Module Checkit {
Let inkey$="hello", dir$="Something Else"
\\ using a dot we tell to interpreter to skip internal identifiers,
\\ and look for user variables
Print .inkey$="hello", .dir$="Something Else"
Print dir$ ' return current path
do
Print "wait to press space"
Until inkey$=" "
}
Checkit
Module check2 {
Global inkey$="ok"
Print .inkey$="ok"
}
check2
Module Check3 {
Group A {
Module Check3 {
\\ using a dot before the name
.inkey$="ok"
Print .inkey$="ok"
}
}
A.Check3
}
Check3
|
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Grid[Partition[Names["$*"],4]]
->
$Aborted $ActivationGroupID $ActivationKey $ActivationUserRegistered
$AddOnsDirectory $AllowDataUpdates $AllowDocumentationUpdates $AllowInternet
$AssertFunction $Assumptions $BaseDirectory $BatchInput
$BatchOutput $BoxForms $ByteOrdering $Canceled
$CharacterEncoding $CharacterEncodings $CommandLine $CompilationTarget
$ConditionHold $ConfiguredKernels $Context $ContextPath
$ControlActiveSetting $CreationDate $CurrentLink $DateStringFormat
$DefaultFont $DefaultFrontEnd $DefaultImagingDevice $DefaultPath
$Display $DisplayFunction $DistributedContexts $DynamicEvaluation
$Echo $Epilog $ExportFormats $Failed
$FinancialDataSource $FormatType $FrontEnd $FrontEndSession
$GeoLocation $HistoryLength $HomeDirectory $IgnoreEOF
$ImagingDevices $ImportFormats $InitialDirectory $Input
$InputFileName $Inspector $InstallationDate $InstallationDirectory
$InstalledServices $InterfaceEnvironment $InternetProxyRules $IterationLimit
$KernelCount $KernelID $Language $LaunchDirectory
$LibraryPath $LicenseExpirationDate $LicenseID $LicenseProcesses
$LicenseServer $LicenseSubprocesses $LicenseType $Line
$Linked $LinkSupported $LoadedFiles $MachineAddresses
$MachineDomain $MachineDomains $MachineEpsilon $MachineID
$MachineName $MachinePrecision $MachineType $MaxExtraPrecision
$MaxLicenseProcesses $MaxLicenseSubprocesses $MaxMachineNumber $MaxNumber
$MaxPiecewiseCases $MaxPrecision $MaxRootDegree $MessageGroups
$MessageList $MessagePrePrint $Messages $MinMachineNumber
$MinNumber $MinorReleaseNumber $MinPrecision $ModuleNumber
$NetworkLicense $NewMessage $NewSymbol $Notebooks
$NumberMarks $Off $OperatingSystem $Output
$OutputForms $OutputSizeLimit $Packages $PacletSite
$ParentLink $ParentProcessID $PasswordFile $PatchLevelID
$Path $PathnameSeparator $PerformanceGoal $PipeSupported
$Post $Pre $PreferencesDirectory $PrePrint
$PreRead $PrintForms $PrintLiteral $PrintServiceRequest
$PrintServiceResponse $PrintShortErrorMessages $PrintWSDLDebug $ProcessID
$ProcessorCount $ProcessorType $ProductInformation $ProgramName
$RandomState $RecursionLimit $ReleaseNumber $RootDirectory
$ScheduledTask $ScriptCommandLine $SessionID $SetParentLink
$SharedFunctions $SharedVariables $SoundDisplay $SoundDisplayFunction
$SuppressInputFormHeads $SynchronousEvaluation $SyntaxHandler $System
$SystemCharacterEncoding $SystemID $SystemWordLength $TemporaryDirectory
$TemporaryPrefix $TextStyle $TimedOut $TimeUnit
$TimeZone $TopDirectory $TraceOff $TraceOn
$TracePattern $TracePostAction $TracePreAction $Urgent
$UserAddOnsDirectory $UserBaseDirectory $UserBasePacletsDirectory $UserDocumentsDirectory |
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.
| #Maxima | Maxima | /* There are many special variables in Maxima: more than 250 are used for options, for example */
fpprec; /* precision for big floats */
obase; /* number base for output */
/* Other variables are read-only, and give the list of user-defined variables, functions... */
infolists; /* give the names of all available lists */
[labels, values, functions, macros, arrays, myoptions, props, aliases, rules, gradefs, dependencies, let_rule_packages, structures] |
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
| #Erlang | Erlang |
10 \ single cell number
-10 \ negative single cell number
10. \ double cell number
10e \ floating-point number |
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
| #Forth | Forth |
10 \ single cell number
-10 \ negative single cell number
10. \ double cell number
10e \ floating-point number |
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
| #AutoHotkey | AutoHotkey | StoogeSort(L, i:=1, j:=""){
if !j
j := L.MaxIndex()
if (L[j] < L[i]){
temp := L[i]
L[i] := L[j]
L[j] := temp
}
if (j - i > 1){
t := floor((j - i + 1)/3)
StoogeSort(L, i, j-t)
StoogeSort(L, i+t, j)
StoogeSort(L, i, j-t)
}
return L
} |
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.
| #Brainf.2A.2A.2A | Brainf*** |
>>>>>,----------[++++++++
++[->+>+<<]>+>[-<<+>>]+++
+++++[-<------>]>>+>,----
------<<+[->>>>>+<<<<<]>>
]>>>[<<<<[<<<[->>+<<[->+>
[-]<<]]>[-<+>]>[-<<<.>>>>
->>>>>[>>>>>]<-<<<<[<<<<<
]+<]<<<<]>>>>>[>>>>>]<]
|
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.
| #11l | 11l | V inv_code = [
‘1’ = [‘B’, ‘F’, ‘P’, ‘V’],
‘2’ = [‘C’, ‘G’, ‘J’, ‘K’, ‘Q’, ‘S’, ‘X’, ‘Z’],
‘3’ = [‘D’, ‘T’],
‘4’ = [‘L’],
‘5’ = [‘M’, ‘N’],
‘6’ = [‘R’]
]
[Char = Char] _code
L(k, arr) inv_code
L(el) arr
_code[el] = k
F soundex(s)
V code = String(s[0].uppercase())
V previous = :_code.get(s[0].uppercase(), Char("\0"))
L(c) s[1..]
V current = :_code.get(c.uppercase(), Char("\0"))
I current != "\0" & current != previous
code ‘’= current
previous = current
R (code‘0000’)[0.<4]
print(soundex(‘Soundex’))
print(soundex(‘Example’))
print(soundex(‘Sownteks’))
print(soundex(‘Ekzampul’)) |
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.
| #Ada | Ada | generic
type Element_Type is digits <>;
type Index_Type is (<>);
type Array_Type is array(Index_Type range <>) of Element_Type;
package Shell_Sort is
procedure Sort(Item : in out Array_Type);
end Shell_Sort; |
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.
| #Factor | Factor | USING: formatting kernel math math.order math.parser
math.statistics sequences splitting ;
: sparkline-index ( v min max -- i )
[ drop - 8 * ] [ swap - /i ] 2bi 0 7 clamp 9601 + ;
: (sparkline) ( seq -- new-seq )
dup minmax [ sparkline-index ] 2curry "" map-as ;
: sparkline ( str -- new-str )
", " split harvest [ string>number ] map (sparkline) ;
{
"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"
"0, 1, 19, 20"
"0, 999, 4000, 4999, 7000, 7999"
} [ dup sparkline "%u -> %s\n" printf ] each |
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.
| #jq | jq | # merge input array with array x by comparing the heads of the arrays
# in turn; # if both arrays are sorted, the result will be sorted:
def merge(x):
length as $length
| (x|length) as $xl
| if $length == 0 then x
elif $xl == 0 then .
else
. as $in
| reduce range(0; $xl + $length) as $z
# state [ix, xix, ans]
( [0, 0, []];
if .[0] < $length and
((.[1] < $xl and $in[.[0]] <= x[.[1]]) or .[1] == $xl)
then [(.[0] + 1), .[1], (.[2] + [$in[.[0]]]) ]
else [.[0], (.[1] + 1), (.[2] + [x[.[1]]]) ]
end
) | .[2]
end ;
def strand_sort:
# The inner function emits [strand, remainder]
def strand:
if length <= 1 then .
else
reduce .[] as $x
# state: [strand, remainder]
([ [], [] ];
if ((.[0]|length) == 0) or .[0][-1] <= $x
then [ (.[0] + [$x]), .[1] ]
else [ .[0], (.[1] + [$x]) ]
end )
end ;
if length <= 1 then .
else strand as $s
| ($s[0] | merge( $s[1] | strand_sort))
end ;
|
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.
| #Julia | Julia | function mergelist(a, b)
out = Vector{Int}()
while !isempty(a) && !isempty(b)
if a[1] < b[1]
push!(out, popfirst!(a))
else
push!(out, popfirst!(b))
end
end
append!(out, a)
append!(out, b)
out
end
function strand(a)
i, s = 1, [popfirst!(a)]
while i < length(a) + 1
if a[i] > s[end]
append!(s, splice!(a, i))
else
i += 1
end
end
s
end
strandsort(a) = (out = strand(a); while !isempty(a) out = mergelist(out, strand(a)) end; out)
println(strandsort([1, 6, 3, 2, 1, 7, 5, 3]))
|
http://rosettacode.org/wiki/Stable_marriage_problem | Stable marriage problem | Solve the Stable marriage problem using the Gale/Shapley algorithm.
Problem description
Given an equal number of men and women to be paired for marriage, each man ranks all the women in order of his preference and each woman ranks all the men in order of her preference.
A stable set of engagements for marriage is one where no man prefers a woman over the one he is engaged to, where that other woman also prefers that man over the one she is engaged to. I.e. with consulting marriages, there would be no reason for the engagements between the people to change.
Gale and Shapley proved that there is a stable set of engagements for any set of preferences and the first link above gives their algorithm for finding a set of stable engagements.
Task Specifics
Given ten males:
abe, bob, col, dan, ed, fred, gav, hal, ian, jon
And ten females:
abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan
And a complete list of ranked preferences, where the most liked is to the left:
abe: abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay
bob: cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay
col: hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan
dan: ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi
ed: jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay
fred: bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay
gav: gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay
hal: abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee
ian: hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve
jon: abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope
abi: bob, fred, jon, gav, ian, abe, dan, ed, col, hal
bea: bob, abe, col, fred, gav, dan, ian, ed, jon, hal
cath: fred, bob, ed, gav, hal, col, ian, abe, dan, jon
dee: fred, jon, col, abe, ian, hal, gav, dan, bob, ed
eve: jon, hal, fred, dan, abe, gav, col, ed, ian, bob
fay: bob, abe, ed, ian, jon, dan, fred, gav, col, hal
gay: jon, gav, hal, fred, bob, abe, col, ed, dan, ian
hope: gav, jon, bob, abe, ian, dan, hal, ed, col, fred
ivy: ian, col, hal, gav, fred, bob, abe, ed, jon, dan
jan: ed, hal, gav, abe, bob, jon, col, ian, fred, dan
Use the Gale Shapley algorithm to find a stable set of engagements
Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.
References
The Stable Marriage Problem. (Eloquent description and background information).
Gale-Shapley Algorithm Demonstration.
Another Gale-Shapley Algorithm Demonstration.
Stable Marriage Problem - Numberphile (Video).
Stable Marriage Problem (the math bit) (Video).
The Stable Marriage Problem and School Choice. (Excellent exposition)
| #Java | Java | import java.util.*;
public class Stable {
static List<String> guys = Arrays.asList(
new String[]{
"abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"});
static List<String> girls = Arrays.asList(
new String[]{
"abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"});
static Map<String, List<String>> guyPrefers =
new HashMap<String, List<String>>(){{
put("abe",
Arrays.asList("abi", "eve", "cath", "ivy", "jan", "dee", "fay",
"bea", "hope", "gay"));
put("bob",
Arrays.asList("cath", "hope", "abi", "dee", "eve", "fay", "bea",
"jan", "ivy", "gay"));
put("col",
Arrays.asList("hope", "eve", "abi", "dee", "bea", "fay", "ivy",
"gay", "cath", "jan"));
put("dan",
Arrays.asList("ivy", "fay", "dee", "gay", "hope", "eve", "jan",
"bea", "cath", "abi"));
put("ed",
Arrays.asList("jan", "dee", "bea", "cath", "fay", "eve", "abi",
"ivy", "hope", "gay"));
put("fred",
Arrays.asList("bea", "abi", "dee", "gay", "eve", "ivy", "cath",
"jan", "hope", "fay"));
put("gav",
Arrays.asList("gay", "eve", "ivy", "bea", "cath", "abi", "dee",
"hope", "jan", "fay"));
put("hal",
Arrays.asList("abi", "eve", "hope", "fay", "ivy", "cath", "jan",
"bea", "gay", "dee"));
put("ian",
Arrays.asList("hope", "cath", "dee", "gay", "bea", "abi", "fay",
"ivy", "jan", "eve"));
put("jon",
Arrays.asList("abi", "fay", "jan", "gay", "eve", "bea", "dee",
"cath", "ivy", "hope"));
}};
static Map<String, List<String>> girlPrefers =
new HashMap<String, List<String>>(){{
put("abi",
Arrays.asList("bob", "fred", "jon", "gav", "ian", "abe", "dan",
"ed", "col", "hal"));
put("bea",
Arrays.asList("bob", "abe", "col", "fred", "gav", "dan", "ian",
"ed", "jon", "hal"));
put("cath",
Arrays.asList("fred", "bob", "ed", "gav", "hal", "col", "ian",
"abe", "dan", "jon"));
put("dee",
Arrays.asList("fred", "jon", "col", "abe", "ian", "hal", "gav",
"dan", "bob", "ed"));
put("eve",
Arrays.asList("jon", "hal", "fred", "dan", "abe", "gav", "col",
"ed", "ian", "bob"));
put("fay",
Arrays.asList("bob", "abe", "ed", "ian", "jon", "dan", "fred",
"gav", "col", "hal"));
put("gay",
Arrays.asList("jon", "gav", "hal", "fred", "bob", "abe", "col",
"ed", "dan", "ian"));
put("hope",
Arrays.asList("gav", "jon", "bob", "abe", "ian", "dan", "hal",
"ed", "col", "fred"));
put("ivy",
Arrays.asList("ian", "col", "hal", "gav", "fred", "bob", "abe",
"ed", "jon", "dan"));
put("jan",
Arrays.asList("ed", "hal", "gav", "abe", "bob", "jon", "col",
"ian", "fred", "dan"));
}};
public static void main(String[] args){
Map<String, String> matches = match(guys, guyPrefers, girlPrefers);
for(Map.Entry<String, String> couple:matches.entrySet()){
System.out.println(
couple.getKey() + " is engaged to " + couple.getValue());
}
if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){
System.out.println("Marriages are stable");
}else{
System.out.println("Marriages are unstable");
}
String tmp = matches.get(girls.get(0));
matches.put(girls.get(0), matches.get(girls.get(1)));
matches.put(girls.get(1), tmp);
System.out.println(
girls.get(0) +" and " + girls.get(1) + " have switched partners");
if(checkMatches(guys, girls, matches, guyPrefers, girlPrefers)){
System.out.println("Marriages are stable");
}else{
System.out.println("Marriages are unstable");
}
}
private static Map<String, String> match(List<String> guys,
Map<String, List<String>> guyPrefers,
Map<String, List<String>> girlPrefers){
Map<String, String> engagedTo = new TreeMap<String, String>();
List<String> freeGuys = new LinkedList<String>();
freeGuys.addAll(guys);
while(!freeGuys.isEmpty()){
String thisGuy = freeGuys.remove(0); //get a load of THIS guy
List<String> thisGuyPrefers = guyPrefers.get(thisGuy);
for(String girl:thisGuyPrefers){
if(engagedTo.get(girl) == null){//girl is free
engagedTo.put(girl, thisGuy); //awww
break;
}else{
String otherGuy = engagedTo.get(girl);
List<String> thisGirlPrefers = girlPrefers.get(girl);
if(thisGirlPrefers.indexOf(thisGuy) <
thisGirlPrefers.indexOf(otherGuy)){
//this girl prefers this guy to the guy she's engaged to
engagedTo.put(girl, thisGuy);
freeGuys.add(otherGuy);
break;
}//else no change...keep looking for this guy
}
}
}
return engagedTo;
}
private static boolean checkMatches(List<String> guys, List<String> girls,
Map<String, String> matches, Map<String, List<String>> guyPrefers,
Map<String, List<String>> girlPrefers) {
if(!matches.keySet().containsAll(girls)){
return false;
}
if(!matches.values().containsAll(guys)){
return false;
}
Map<String, String> invertedMatches = new TreeMap<String, String>();
for(Map.Entry<String, String> couple:matches.entrySet()){
invertedMatches.put(couple.getValue(), couple.getKey());
}
for(Map.Entry<String, String> couple:matches.entrySet()){
List<String> shePrefers = girlPrefers.get(couple.getKey());
List<String> sheLikesBetter = new LinkedList<String>();
sheLikesBetter.addAll(shePrefers.subList(0, shePrefers.indexOf(couple.getValue())));
List<String> hePrefers = guyPrefers.get(couple.getValue());
List<String> heLikesBetter = new LinkedList<String>();
heLikesBetter.addAll(hePrefers.subList(0, hePrefers.indexOf(couple.getKey())));
for(String guy : sheLikesBetter){
String guysFinace = invertedMatches.get(guy);
List<String> thisGuyPrefers = guyPrefers.get(guy);
if(thisGuyPrefers.indexOf(guysFinace) >
thisGuyPrefers.indexOf(couple.getKey())){
System.out.printf("%s likes %s better than %s and %s"
+ " likes %s better than their current partner\n",
couple.getKey(), guy, couple.getValue(),
guy, couple.getKey());
return false;
}
}
for(String girl : heLikesBetter){
String girlsFinace = matches.get(girl);
List<String> thisGirlPrefers = girlPrefers.get(girl);
if(thisGirlPrefers.indexOf(girlsFinace) >
thisGirlPrefers.indexOf(couple.getValue())){
System.out.printf("%s likes %s better than %s and %s"
+ " likes %s better than their current partner\n",
couple.getValue(), girl, couple.getKey(),
girl, couple.getValue());
return false;
}
}
}
return true;
}
} |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Tcl | Tcl | proc squaregen {{i 0}} {
proc squaregen "{i [incr i]}" [info body squaregen]
expr $i * $i
}
proc is_cube {n} {
for {set i 1} {($i * $i * $i) < $n} {incr i} { }
expr ($i * $i * $i) == $n
}
set cubes {}
set noncubes {}
for {set s [squaregen]} {[llength $noncubes] < 30} {set s [squaregen]} {
if [is_cube $s] {
lappend cubes $s
} else {
lappend noncubes $s
}
}
puts "Squares but not cubes:"
puts $noncubes
puts {}
puts "Both squares and cubes:"
puts $cubes |
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
| #Rust | Rust | fn splitter(string: &str) -> String {
let chars: Vec<_> = string.chars().collect();
let mut result = Vec::new();
let mut last_mismatch = 0;
for i in 0..chars.len() {
if chars.len() == 1 {
return chars[0..1].iter().collect();
}
if i > 0 && chars[i-1] != chars[i] {
let temp_result: String = chars[last_mismatch..i].iter().collect();
result.push(temp_result);
last_mismatch = i;
}
if i == chars.len() - 1 {
let temp_result: String = chars[last_mismatch..chars.len()].iter().collect();
result.push(temp_result);
}
}
result.join(", ")
}
fn main() {
let test_string = "g";
println!("input string: {}", test_string);
println!("output string: {}", splitter(test_string));
let test_string = "";
println!("input string: {}", test_string);
println!("output string: {}", splitter(test_string));
let test_string = "gHHH5YY++///\\";
println!("input string: {}", test_string);
println!("output string: {}", splitter(test_string));
} |
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
| #Scala | Scala | // Split a (character) string into comma (plus a blank) delimited strings
// based on a change of character (left to right).
// See https://rosettacode.org/wiki/Split_a_character_string_based_on_change_of_character#Scala
def runLengthSplit(s: String): String = /// Add a guard letter
(s + 'X').sliding(2).map(pair => pair.head + (if (pair.head != pair.last) ", " else "")).mkString("")
println(runLengthSplit("""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
| #F.23 | F# | type Stack<'a> //'//(workaround for syntax highlighting problem)
(?items) =
let items = defaultArg items []
member x.Push(A) = Stack(A::items)
member x.Pop() =
match items with
| x::xr -> (x, Stack(xr))
| [] -> failwith "Stack is empty."
member x.IsEmpty() = items = []
// example usage
let anEmptyStack = Stack<int>()
let stack2 = anEmptyStack.Push(42)
printfn "%A" (stack2.IsEmpty())
let (x, stack3) = stack2.Pop()
printfn "%d" x
printfn "%A" (stack3.IsEmpty()) |
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)
| #D | D | void main() {
import std.stdio;
enum n = 5;
int[n][n] M;
int pos, side = n;
foreach (immutable i; 0 .. n / 2 + n % 2) {
foreach (immutable j; 0 .. side)
M[i][i + j] = pos++;
foreach (immutable j; 1 .. side)
M[i + j][n - 1 - i] = pos++;
foreach_reverse (immutable j; 0 .. side - 1)
M[n - 1 - i][i + j] = pos++;
foreach_reverse (immutable j; 1 .. side - 1)
M[i + j][i] = pos++;
side -= 2;
}
writefln("%(%(%2d %)\n%)", M);
} |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #ML.2FI | ML/I | MCSKIP "WITH" NL
"" Special variables
"" There are four different kinds of variables in ML/I.
"" Permanent (P) variables - these have no special predefined values.
"" Character (C) variables - these have no special predefined values.
"" Temporary (T) variables - a macro has at least three of these, and
"" those have predefined values.
"" System (S) variables - these are for control and status. The number
"" of these is implementation dependent.
MCSKIP MT,<>
MCINS %.
MCDEF TVARDEMO , NL
AS <T-variables are local to the current macro call
T1 is the number of arguments to current macro call - value is %T1.
T2 is the number of macro calls so far - value is %T2.
T3 is the current depth of nesting - value is %T3.
>
TVARDEMO xxx,yyy
MCDEF SVARDEMO WITHS NL
AS <The first nine S-variables are implementation independent
S1 controls startline insertion - value is %S1.
S2 is the current source text line number - value is %S2.
S3 controls error messages related to warning markers - value is %S3.
S4 controls context printout after a <MCNOTE> - value is %S4.
S5 is the count of processing errors - value is %S5.
S6 enables the definition of an atom to be changed - value is %S6.
S7, S8 and S9 are currently unused.
All other S-variables have implementation defined meanings.
>
SVARDEMO |
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.
| #Nanoquery | Nanoquery | println dumpstack() |
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
| #Fortran | Fortran | C or c in column one mark a comment line.
D or d in column one mark a debugging statement, ignored or compiled according to an option set at compile time.
* in column one for compiler control statements (e.g. Fortran II, Fortran IV)
0 in column six does not indicate a continuation line, even though not a blank.
Space: ignored within source outside text literals, even between parts of a word. Allows G O TO
' Delimits a text literal. Also has been used in READ(F'N) to read record N of the file attached to F.
" Delimits a text literal. Doubling required for each contained in the literal.
! Outside a text literal marks an "escape comment" - only text before it on the line will be compiled. The B6700 used % for this.
& Outside a text literal indicated that further source is continued on the next line.
|
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
| #FreeBASIC | FreeBASIC | -- comment here until end of line
{- comment here -} |
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
| #BASIC | BASIC | DECLARE SUB stoogesort (L() AS LONG, i AS LONG, j AS LONG)
RANDOMIZE TIMER
CONST arraysize = 10
DIM x(arraysize) AS LONG
DIM i AS LONG
PRINT "Before: ";
FOR i = 0 TO arraysize
x(i) = INT(RND * 100)
PRINT x(i); " ";
NEXT
PRINT
stoogesort x(), 0, arraysize
PRINT "After: ";
FOR i = 0 TO arraysize
PRINT x(i); " ";
NEXT
PRINT
SUB stoogesort (L() AS LONG, i AS LONG, j AS LONG)
IF L(j) < L(i) THEN SWAP L(i), L(j)
IF (j - i) > 1 THEN
DIM t AS LONG
t = (j - i + 1) / 3
stoogesort L(), i, j - t
stoogesort L(), i + t, j
stoogesort L(), i, j - t
END IF
END SUB |
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.
| #C | C | #include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int c, char **v)
{
while (--c > 1 && !fork());
sleep(c = atoi(v[c]));
printf("%d\n", c);
wait(0);
return 0;
} |
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.
| #360_Assembly | 360 Assembly | * Soundex 02/04/2017
SOUNDEX CSECT
USING SOUNDEX,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) save previous context
ST R13,4(R15) link backward
ST R15,8(R13) link forward
LR R13,R15 set addressability
LA R6,1 i=1
DO WHILE=(C,R6,LE,=A(NTT)) do i=1 to hbound(tt)
LR R1,R6 i
BCTR R1,0 -1
MH R1,=AL2(L'TT) *length(tt)
LA R4,TT(R1) @tt(i)
MVC S,0(R4) s=tt(i)
LA R1,S @s
LA R2,L'S length(s)
LOOP OI 0(R1),C' ' loop s[l]=ucase(s[l])
LA R1,1(R1) @s++
BCT R2,LOOP endloop
MVC CODE,=C'0000' code='0000'
MVC CODE(1),S code[1]=s[1]
LA R8,1 k=1
LA R7,1 j=1
DO WHILE=(C,R7,LE,=A(L'S)) do j=1 to length(s)
LA R4,S-1 @s[0]
AR R4,R7 +j
MVC CCUR,0(R4) ccur=s[j]
TR CCUR,TABLE ccur=translate(ccur,table)
IF C,R7,EQ,=F'1' THEN if j=1 then
MVC CPREV,CCUR cprev=ccur
ELSE , else
* if ccur<>' ' and ccur<>'-'
IF CLI,CCUR,NE,C' ',AND,CLI,CCUR,NE,C'-', *
AND,CLC,CCUR,NE,CPREV THEN and ccur<>cprev then
IF C,R8,LT,=F'4' THEN if k<4 then
LA R8,1(R8) k=k+1
LA R4,CODE-1(R8) @code[k]
MVC 0(1,R4),CCUR code[k]=ccur
ENDIF , endif
ENDIF , endif
IF CLI,CCUR,NE,C'-' THEN if ccur<>'-' then
MVC CPREV,CCUR cprev=ccur
ENDIF , endif
ENDIF , endif
LA R7,1(R7) j++
ENDDO , enddo j
XDECO R6,XDEC edit i
MVC PG(2),XDEC+10 i
MVC PG+3(L'S),S s
MVC PG+15(L'CODE),CODE code
XPRNT PG,L'PG print
LA R6,1(R6) i++
ENDDO , enddo i
L R13,4(0,R13) restore previous savearea pointer
LM R14,R12,12(R13) restore previous context
XR R15,R15 rc=0
BR R14 exit
TT DC CL12'ashcraft',CL12'ashcroft',CL12'gauss',CL12'ghosh'
DC CL12'hilbert',CL12'heilbronn',CL12'lee',CL12'lloyd'
DC CL12'moses',CL12'pfister',CL12'robert',CL12'rupert'
DC CL12'rubin',CL12'tymczak',CL12'soundex',CL12'example'
TTEND EQU *
NTT EQU (TTEND-TT)/L'TT hbound(tt)
S DS CL12
CCUR DS CL1 current
CPREV DS CL1 previous
CODE DS CL4
PG DC CL80' '
XDEC DS CL12
TABLE DC CL256' ' translation table
ORG TABLE+C'A'
DC CL9' 123 12- ' ABCDEFGHI
ORG TABLE+C'J'
DC CL9'22455 126' JKLMNOPQR
ORG TABLE+C'S'
DC CL9'23 1-2 2' STUVWXYZ
ORG
YREGS
END SOUNDEX |
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.
| #ALGOL_68 | ALGOL 68 | # -*- coding: utf-8 -*- #
COMMENT
REQUIRES(
MODE SORTELEMENT = mode of element of array to be sorted...
OP < = (SORTELEMENT a, b)BOOL: a < b;
)
END COMMENT
MODE SORTELEMENTCMP = PROC(SORTELEMENT,SORTELEMENT)BOOL;
# create a global sort procedure for convenience #
PROC(SORTELEMENT,SORTELEMENT)BOOL sort cmp default := (SORTELEMENT a, b)BOOL: a < b;
PROC sort cmp rev = (SORTELEMENT a, b)BOOL: NOT sort cmp default(a,b);
# Alternative gap calculations: #
# ⌊n/2**k⌋; ⌊n/2⌋; Θ(n**2) [when n=2**p]; Donald Shell 1959 #
PROC sort gap shell = (INT k, n)INT: n OVER 2;
# 2 ⌊n/2**(k+1)⌋+1; 2 ⌊n/4⌋+1, ..., 3, 1; Θ(n**(3/2)); Frank & Lazarus, 1960 #
# 2**k-1; 1, 3, 7, 15, 31, 63, ...; Θ(n**(3/2)); Hibbard, 1963 #
# 2**k+1, prefixed with 1; 1, 3, 5, 9, 17, 33, 65, ...; Θ(n**(3/2)); Papernov & Stasevich, 1965 #
# successive numbers of the form 2**p 3**q; 1, 2, 3, 4, 6, 8, 9, 12, ...; Θ(n log**2 n); Pratt 1971 #
# (3**k-1)/2, not greater than ⌈n/3⌉; 1, 4, 13, 40, 121, ...; Θ(n**(3/2)); Knuth 1973 #
# ∏a[q], where r=⌊√(2k+√(2k))⌋ and a[q]=min(n∈𝒩:n≥(5/2)**(q+1) and ∀ p:0≤ p<q → gcd(a[p],n)=1);
limit where 0≤q<r and q≠(r**2+r)/2-k
1, 3, 7, 21, 48, 112, ...; O(n e**√(8ln(5/2)ln n)); Incerpi & Sedgewick, 1985 #
# 4**k+3×2**(k-1)+1, prefixed with 1; 1, 8, 23, 77, 281, ...; Θ(n**(4/3)); Sedgewick, 1986 #
# 9(4**(k-1)-2**(k-1))+1, 4**(k+1)-6×2**k+1; 1, 5, 19, 41, 109, ...; Θ(n**(4/3)); Sedgewick, 1986 #
# h[k]=max(⌊5h[k-1]/11⌋, 1), h[0]=n; ⌊5N/11⌋, ⌊5/11 ⌊5N/11⌋⌋, ..., 1; Θ(?); Gonnet & Baeza-Yates, 1991 #
PROC sort gap gonnet and baeza yates = (INT k, n)INT: IF n=2 THEN 1 ELSE n*5 OVER 11 FI;
# ⌈(9**k-4**k)/(5×4**(k-1))⌉; 1, 4, 9, 20, 46, 103, ...; Θ(?); Tokuda, 1992 #
# unknown; 1, 4, 10, 23, 57, 132, 301, 701; Θ(?); Ciura, 2001 #
# set default gap calculation #
PROC (INT #k#, INT #n#)INT sort gap := sort gap gonnet and baeza yates;
PROC shell sort in place = (REF []SORTELEMENT array, UNION(VOID, SORTELEMENTCMP) opt cmp)REF[]SORTELEMENT:(
SORTELEMENTCMP cmp := (opt cmp|(SORTELEMENTCMP cmp): cmp | sort cmp default);
INT n := ( UPB array + LWB array + 1 ) OVER 2; # initial gap #
FOR k WHILE n NE 0 DO
FOR index FROM LWB array TO UPB array DO
INT i := index;
SORTELEMENT element = array[i];
WHILE ( i - LWB array >= n | cmp(element, array[i-n]) | FALSE ) DO
array[i] := array[i-n];
i -:= n
OD;
array[i] := element
OD;
n := sort gap(k,n)
OD;
array
);
PROC shell sort = ([]SORTELEMENT seq)[]SORTELEMENT:
shell sort in place(LOC[LWB seq: UPB seq]SORTELEMENT:=seq, EMPTY);
PROC shell sort rev = ([]SORTELEMENT seq)[]SORTELEMENT:
shell sort in place(LOC[LWB seq: UPB seq]SORTELEMENT:=seq, sort cmp rev);
SKIP |
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.
| #FALSE | FALSE | {
variables:
s: sign (1 or -1)
u: current number
f: current number fraction length
v: current number is valid
t: number of numbers read
x: biggest fraction
y: smallest number (without fraction)
z: biggest number (without fraction)
}
{function a: test if top is 0-9, without popping the value, codes 48-57 are in range}
[$$47>\57>~&]a:
{function b: test if top is ',' or ' ', without popping the value}
[$$',=\' =|]b:
{function c: read a number from the input, given that the first character of the input is already on the stack}
[
1s:0u:0f:0v: {reset values}
$'-=[1_s:%^]? {if (it is negative) set the sign value to -1 move to next}
[a;!][48-u;10*+u:1_v:^]# {while (isnumber) do number = number * 10 + decimal and set valid number and move to next}
$'.=[ {if (it is a decimal) move forward and read fraction}
%^
[a;!][48-u;10*+u:f;1+f:1_v:^]# {while (isnumber) do number = number * 10 + decimal and increase fraction length and set valid number and move to next}
]?
$$'-=\'.=|[0v:]? {if next charachter is a '-' or a '.', set invalid}
]c:
{function d: normalize number/fraction from stack to max fraction and push that number}
[
[$x;=~][1+\10*\]# {while (fraction != max) fraction + 1, value * 10}
% {pop fraction}
]d:
0t:
0x:
1_v: { nothing read, so we are still valid }
^[b;!][%^]# {read away any initial separators}
[$1_=~v;&][ {while input != -1 and valid input, leaving input on the stack}
c;! {read a number}
t;1+t:u;s;*f;@ {increase count, push number * sign and fraction length onto the stack and bring input back up}
f;x;>[f;x:]? {set fraction to biggest of current and previous biggest}
[b;!][%^]# {while (isseparator) move forward}
]#
v;~["error at charachter ",]? {if invalid number, tell them when}
v;[ {if last number also valid, do the math}
% {pop the -1}
t;2*1-q: {var q: points to next value}
0p: {var p: whether min/max have been set}
[q;1+t;>][ {while q + 1 > t}
q;ø {current number}
q;ø {current fraction}
d;! {normalize}
p;[$y;\>[$y:]? $z;>[$z:]?]? {compare min/max}
p;~[1_p:$y:$z:]? {if (first)) set min/max}
q;1-q: {move pointer}
]#
t;q: {point q to first value}
[q;0>][ {while q > 0}
q;1-øy;-7*z;y;-/ {(number - minvalue) * 7 / (maxvalue - minvalue), should result in 0..7}
9601+, {print character}
q;1-q: {move pointer}
]#
]? |
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.
| #Go | Go | package main
import (
"bufio"
"errors"
"fmt"
"math"
"os"
"regexp"
"strconv"
"strings"
)
func main() {
fmt.Println("Numbers please separated by space/commas:")
sc := bufio.NewScanner(os.Stdin)
sc.Scan()
s, n, min, max, err := spark(sc.Text())
if err != nil {
fmt.Println(err)
return
}
if n == 1 {
fmt.Println("1 value =", min)
} else {
fmt.Println(n, "values. Min:", min, "Max:", max)
}
fmt.Println(s)
}
var sep = regexp.MustCompile(`[\s,]+`)
func spark(s0 string) (sp string, n int, min, max float64, err error) {
ss := sep.Split(s0, -1)
n = len(ss)
vs := make([]float64, n)
var v float64
min = math.Inf(1)
max = math.Inf(-1)
for i, s := range ss {
switch v, err = strconv.ParseFloat(s, 64); {
case err != nil:
case math.IsNaN(v):
err = errors.New("NaN not supported.")
case math.IsInf(v, 0):
err = errors.New("Inf not supported.")
default:
if v < min {
min = v
}
if v > max {
max = v
}
vs[i] = v
continue
}
return
}
if min == max {
sp = strings.Repeat("▄", n)
} else {
rs := make([]rune, n)
f := 8 / (max - min)
for j, v := range vs {
i := rune(f * (v - min))
if i > 7 {
i = 7
}
rs[j] = '▁' + i
}
sp = string(rs)
}
return
} |
http://rosettacode.org/wiki/Sorting_algorithms/Strand_sort | Sorting algorithms/Strand sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
This page uses content from Wikipedia. The original article was at Strand sort. The list of authors can be seen in the page history. As with Rosetta Code, the text of Wikipedia is available under the GNU FDL. (See links for details on variance)
Task
Implement the Strand sort.
This is a way of sorting numbers by extracting shorter sequences of already sorted numbers from an unsorted list.
| #Kotlin | Kotlin | // version 1.1.2
fun <T : Comparable<T>> strandSort(l: List<T>): List<T> {
fun merge(left: MutableList<T>, right: MutableList<T>): MutableList<T> {
val res = mutableListOf<T>()
while (!left.isEmpty() && !right.isEmpty()) {
if (left[0] <= right[0]) {
res.add(left[0])
left.removeAt(0)
}
else {
res.add(right[0])
right.removeAt(0)
}
}
res.addAll(left)
res.addAll(right)
return res
}
var list = l.toMutableList()
var result = mutableListOf<T>()
while (!list.isEmpty()) {
val sorted = mutableListOf(list[0])
list.removeAt(0)
val leftover = mutableListOf<T>()
for (item in list) {
if (sorted.last() <= item)
sorted.add(item)
else
leftover.add(item)
}
result = merge(sorted, result)
list = leftover
}
return result
}
fun main(args: Array<String>) {
val l = listOf(-2, 0, -2, 5, 5, 3, -1, -3, 5, 5, 0, 2, -4, 4, 2)
println(strandSort(l))
} |
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)
| #JavaScript | JavaScript | function Person(name) {
var candidateIndex = 0;
this.name = name;
this.fiance = null;
this.candidates = [];
this.rank = function(p) {
for (i = 0; i < this.candidates.length; i++)
if (this.candidates[i] === p) return i;
return this.candidates.length + 1;
}
this.prefers = function(p) {
return this.rank(p) < this.rank(this.fiance);
}
this.nextCandidate = function() {
if (candidateIndex >= this.candidates.length) return null;
return this.candidates[candidateIndex++];
}
this.engageTo = function(p) {
if (p.fiance) p.fiance.fiance = null;
p.fiance = this;
if (this.fiance) this.fiance.fiance = null;
this.fiance = p;
}
this.swapWith = function(p) {
console.log("%s & %s swap partners", this.name, p.name);
var thisFiance = this.fiance;
var pFiance = p.fiance;
this.engageTo(pFiance);
p.engageTo(thisFiance);
}
}
function isStable(guys, gals) {
for (var i = 0; i < guys.length; i++)
for (var j = 0; j < gals.length; j++)
if (guys[i].prefers(gals[j]) && gals[j].prefers(guys[i]))
return false;
return true;
}
function engageEveryone(guys) {
var done;
do {
done = true;
for (var i = 0; i < guys.length; i++) {
var guy = guys[i];
if (!guy.fiance) {
done = false;
var gal = guy.nextCandidate();
if (!gal.fiance || gal.prefers(guy))
guy.engageTo(gal);
}
}
} while (!done);
}
function doMarriage() {
var abe = new Person("Abe");
var bob = new Person("Bob");
var col = new Person("Col");
var dan = new Person("Dan");
var ed = new Person("Ed");
var fred = new Person("Fred");
var gav = new Person("Gav");
var hal = new Person("Hal");
var ian = new Person("Ian");
var jon = new Person("Jon");
var abi = new Person("Abi");
var bea = new Person("Bea");
var cath = new Person("Cath");
var dee = new Person("Dee");
var eve = new Person("Eve");
var fay = new Person("Fay");
var gay = new Person("Gay");
var hope = new Person("Hope");
var ivy = new Person("Ivy");
var jan = new Person("Jan");
abe.candidates = [abi, eve, cath, ivy, jan, dee, fay, bea, hope, gay];
bob.candidates = [cath, hope, abi, dee, eve, fay, bea, jan, ivy, gay];
col.candidates = [hope, eve, abi, dee, bea, fay, ivy, gay, cath, jan];
dan.candidates = [ivy, fay, dee, gay, hope, eve, jan, bea, cath, abi];
ed.candidates = [jan, dee, bea, cath, fay, eve, abi, ivy, hope, gay];
fred.candidates = [bea, abi, dee, gay, eve, ivy, cath, jan, hope, fay];
gav.candidates = [gay, eve, ivy, bea, cath, abi, dee, hope, jan, fay];
hal.candidates = [abi, eve, hope, fay, ivy, cath, jan, bea, gay, dee];
ian.candidates = [hope, cath, dee, gay, bea, abi, fay, ivy, jan, eve];
jon.candidates = [abi, fay, jan, gay, eve, bea, dee, cath, ivy, hope];
abi.candidates = [bob, fred, jon, gav, ian, abe, dan, ed, col, hal];
bea.candidates = [bob, abe, col, fred, gav, dan, ian, ed, jon, hal];
cath.candidates = [fred, bob, ed, gav, hal, col, ian, abe, dan, jon];
dee.candidates = [fred, jon, col, abe, ian, hal, gav, dan, bob, ed];
eve.candidates = [jon, hal, fred, dan, abe, gav, col, ed, ian, bob];
fay.candidates = [bob, abe, ed, ian, jon, dan, fred, gav, col, hal];
gay.candidates = [jon, gav, hal, fred, bob, abe, col, ed, dan, ian];
hope.candidates = [gav, jon, bob, abe, ian, dan, hal, ed, col, fred];
ivy.candidates = [ian, col, hal, gav, fred, bob, abe, ed, jon, dan];
jan.candidates = [ed, hal, gav, abe, bob, jon, col, ian, fred, dan];
var guys = [abe, bob, col, dan, ed, fred, gav, hal, ian, jon];
var gals = [abi, bea, cath, dee, eve, fay, gay, hope, ivy, jan];
engageEveryone(guys);
for (var i = 0; i < guys.length; i++) {
console.log("%s is engaged to %s", guys[i].name, guys[i].fiance.name);
}
console.log("Stable = %s", isStable(guys, gals) ? "Yes" : "No");
jon.swapWith(fred);
console.log("Stable = %s", isStable(guys, gals) ? "Yes" : "No");
}
doMarriage();
|
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #UNIX_Shell | UNIX Shell | # First 30 positive integers which are squares but not cubes
# also, the first 3 positive integers which are both squares and cubes
######
# main #
######
integer n sq cr cnt=0
for (( n=1; cnt<30; n++ )); do
(( sq = n * n ))
(( cr = cbrt(sq) ))
if (( (cr * cr * cr) != sq )); then
(( cnt++ ))
print ${sq}
else
print "${sq} is square and cube"
fi
done |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
' flag / mask explanation:
' bit 0 (1) = increment square
' bit 1 (2) = increment cube
' bit 2 (4) = has output
' Checks flag against mask, then advances mask.
Function ChkFlg(flag As Integer, ByRef mask As Integer) As Boolean
ChkFlg = (flag And mask) = mask : mask <<= 1
End Function
Sub SwoC(limit As Integer)
Dim count, square, delta, cube, d1, d2, flag, mask As Integer, s as string = ""
count = 1 : square = 1 : delta = 1 : cube = 1 : d1 = 1 : d2 = 0
While count <= limit
flag = {5, 7, 2}(1 + square.CompareTo(cube))
If flag = 7 Then s = String. Format(" {0} (also cube)", square)
If flag = 5 Then s = String.Format("{0,-2} {1}", count, square) : count += 1
mask = 1 : If ChkFlg(flag, mask) Then delta += 2 : square += delta
If ChkFlg(flag, mask) Then d2 += 6 : d1 += d2 : cube += d1
If ChkFlg(flag, mask) Then Console.WriteLine(s)
End While
End Sub
Sub Main()
SwoC(30)
End Sub
End Module |
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
| #Sed | Sed | echo 'gHHH5YY++///\' | sed 's/\(.\)\1*/&, /g;s/, $//' |
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
| #Sidef | Sidef | func group(str) {
gather {
while (var match = (str =~ /((.)\g{-1}*)/g)) {
take(match[0])
}
}
}
say group(ARGV[0] \\ 'gHHH5YY++///\\').join(', ') |
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
| #Factor | Factor | V{ 1 2 3 } {
[ 6 swap push ]
[ "hi" swap push ]
[ "Vector is now: " write . ]
[ "Let's pop it: " write pop . ]
[ "Vector is now: " write . ]
[ "Top is: " write last . ] } cleave
Vector is now: V{ 1 2 3 6 "hi" }
Let's pop it: "hi"
Vector is now: V{ 1 2 3 6 }
Top is: 6 |
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)
| #DCL | DCL | $ p1 = f$integer( p1 )
$ max = p1 * p1
$
$ i = 0
$ r = 1
$ rd = 0
$ c = 1
$ cd = 1
$ loop:
$ a'r'_'c' = i
$ nr = r + rd
$ nc = c + cd
$ if nr .eq. 0 .or. nc .eq. 0 .or. nr .gt. p1 .or. nc .gt. p1 .or. f$type( a'nr'_'nc' ) .nes. ""
$ then
$ gosub change_directions
$ endif
$ r = r + rd
$ c = c + cd
$ i = i + 1
$ if i .lt. max then $ goto loop
$ length = f$length( f$string( max - 1 ))
$ r = 1
$ loop2:
$ c = 1
$ output = ""
$ loop3:
$ output = output + f$fao( "!#UL ", length, a'r'_'c' )
$ c = c + 1
$ if c .le. p1 then $ goto loop3
$ write sys$output output
$ r = r + 1
$ if r .le. p1 then $ goto loop2
$ exit
$
$ change_directions:
$ if rd .eq. 0 .and cd .eq. 1
$ then
$ rd = 1
$ cd = 0
$ else
$ if rd .eq. 1 .and. cd .eq. 0
$ then
$ rd = 0
$ cd = -1
$ else
$ if rd .eq. 0 .and. cd .eq. -1
$ then
$ rd = -1
$ cd = 0
$ else
$ rd = 0
$ cd = 1
$ endif
$ endif
$ endif
$ return |
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.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols binary
class RCSpecialVariables
method RCSpecialVariables()
x = super.toString
y = this.toString
say '<super>'x'</super>'
say '<this>'y'</this>'
say '<class>'RCSpecialVariables.class'</class>'
say '<digits>'digits'</digits>'
say '<form>'form'</form>'
say '<[1, 2, 3].length>'
say [1, 2, 3].length
say '</[1, 2, 3].length>'
say '<null>'
say null
say '</null>'
say '<source>'source'</source>'
say '<sourceline>'sourceline'</sourceline>'
say '<trace>'trace'</trace>'
say '<version>'version'</version>'
say 'Type an answer:'
say '<ask>'ask'</ask>'
return
method main(args = String[]) public static
RCSpecialVariables()
return
|
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.
| #Nim | Nim | result = value
return |
http://rosettacode.org/wiki/Special_characters | Special characters | Special characters are symbols (single characters or sequences of characters) that have a "special" built-in meaning in the language and typically cannot be used in identifiers.
Escape sequences are methods that the language uses to remove the special meaning from the symbol, enabling it to be used as a normal character, or sequence of characters when this can be done.
Task
List the special characters and show escape sequences in the language.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Gambas | Gambas | -- comment here until end of line
{- comment here -} |
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
| #Go | Go | -- comment here until end of line
{- comment here -} |
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
| #BBC_BASIC | BBC BASIC | DIM test%(9)
test%() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
PROCstoogesort(test%(), 0, DIM(test%(),1))
FOR i% = 0 TO 9
PRINT test%(i%) ;
NEXT
PRINT
END
DEF PROCstoogesort(l%(), i%, j%)
LOCAL t%
IF l%(j%) < l%(i%) SWAP l%(i%), l%(j%)
IF j% - i% > 1 THEN
t% = (j% - i% + 1)/3
PROCstoogesort(l%(), i%, j%-t%)
PROCstoogesort(l%(), i%+t%, j%)
PROCstoogesort(l%(), i%, j%-t%)
ENDIF
ENDPROC |
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
| #BCPL | BCPL | get "libhdr"
let stoogesort(L, i, j) be
$( if L!j < L!i then
$( let x = L!i
L!i := L!j
L!j := x
$)
if j-i>1 then
$( let t = (j - i + 1)/3
stoogesort(L, i, j-t)
stoogesort(L, i+t, j)
stoogesort(L, i, j-t)
$)
$)
let write(s, A, len) be
$( writes(s)
for i=0 to len-1 do writed(A!i, 4)
wrch('*N')
$)
let start() be
$( let array = table 4,65,2,-31,0,99,2,83,782,1
let length = 10
write("Before: ", array, length)
stoogesort(array, 0, length-1)
write("After: ", array, length)
$) |
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.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
class Program
{
static void ThreadStart(object item)
{
Thread.Sleep(1000 * (int)item);
Console.WriteLine(item);
}
static void SleepSort(IEnumerable<int> items)
{
foreach (var item in items)
{
new Thread(ThreadStart).Start(item);
}
}
static void Main(string[] arguments)
{
SleepSort(arguments.Select(int.Parse));
}
} |
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].
| #11l | 11l | F selection_sort(&lst)
L(e) lst
V mn = min(L.index .< lst.len, key' x -> @lst[x])
(lst[L.index], lst[mn]) = (lst[mn], e)
V arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
selection_sort(&arr)
print(arr) |
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.
| #Ada | Ada | with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings.Unbounded; use Ada.Strings.Unbounded;
with Ada.Characters.Handling; use Ada.Characters.Handling;
procedure Soundex is
type UStrings is array(Natural range <>) of Unbounded_String;
function "+"(S:String) return Unbounded_String renames To_Unbounded_String;
function toSoundex (instr : String) return String is
str : String := To_Upper(instr);
output : String := "0000";
spos : Integer := str'First+1; opos : Positive := 2;
map : array(0..255) of Character := (others => ' ');
last : Integer := str'First;
begin
map(65..90) := " 123 12- 22455 12623 1-2 2";
for i in str'Range loop str(i) := map(Character'Pos(str(i))); end loop;
output(1) := str(str'First);
while (opos <= 4 and spos <= str'Last) loop
if str(spos) /= '-' and str(spos) /= ' ' then
if (str(spos-1) = '-' and last = spos-2) and then
(str(spos) = str(spos-2)) then null;
elsif (str(spos) = output(opos-1) and last = spos-1) then last := spos;
else output(opos) := str(spos); opos := opos + 1; last := spos;
end if;
end if;
spos := spos + 1;
end loop;
output(1) := To_Upper(instr(instr'First));
return output;
end toSoundex;
cases : constant UStrings := (+"Soundex", +"Example", +"Sownteks",
+"Ekzampul", +"Euler", +"Gauss", +"Hilbert", +"Knuth", +"Lloyd",
+"Lukasiewicz", +"Ellery", +"Ghosh", +"Heilbronn", +"Kant",
+"Ladd", +"Lissajous", +"Wheaton", +"Burroughs", +"Burrows",
+"O'Hara", +"Washington", +"Lee", +"Gutierrez", +"Pfister",
+"Jackson", +"Tymczak", +"VanDeusen", +"Ashcraft");
begin
for i in cases'Range loop
Put_Line(To_String(cases(i))&" = "&toSoundex(To_String(cases(i))));
end loop;
end Soundex; |
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.
| #AppleScript | AppleScript | -- In-place Shell sort.
-- Algorithm: Donald Shell, 1959.
on ShellSort(theList, l, r) -- Sort items l thru r of theList.
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}
-- The list as a script property to allow faster references to its items.
script o
property lst : theList
end script
set stepSize to (r - l + 1) div 2
repeat while (stepSize > 0)
repeat with i from (l + stepSize) to r
set currentValue to o's lst's item i
repeat with j from (i - stepSize) to l by -stepSize
set thisValue to o's lst's item j
if (thisValue > currentValue) then
set o's lst's item (j + stepSize) to thisValue
else
set j to j + stepSize
exit repeat
end if
end repeat
if (j < i) then set o's lst's item j to currentValue
end repeat
set stepSize to (stepSize / 2.2) as integer
end repeat
return -- nothing.
end ShellSort
property sort : ShellSort
-- Demo:
local aList
set aList to {56, 44, 72, 4, 93, 26, 61, 72, 52, 9, 87, 26, 73, 75, 94, 91, 30, 18, 63, 16}
sort(aList, 1, -1) -- Sort items 1 thru -1 of aList.
return aList |
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.
| #Groovy | Groovy | def sparkline(List<Number> list) {
def (min, max) = [list.min(), list.max()]
def div = (max - min) / 7
list.collect { (char)(0x2581 + (it-min) * div) }.join()
}
def sparkline(String text) { sparkline(text.split(/[ ,]+/).collect { it as Double }) } |
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.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | StrandSort[ input_ ] := Module[ {results = {}, A = input},
While[Length@A > 0,
sublist = {A[[1]]}; A = A[[2;;All]];
For[i = 1, i < Length@A, i++,
If[ A[[i]] > Last@sublist, AppendTo[sublist, A[[i]]]; A = Delete[A, i];]
];
results = #[[Ordering@#]]&@Join[sublist, results];];
results ]
StrandSort[{2, 3, 7, 5, 1, 4, 7}] |
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)
| #Julia | Julia |
# This is not optimized, but tries to follow the pseudocode given the Wikipedia entry below.
# Reference: https://en.wikipedia.org/wiki/Stable_marriage_problem#Algorithm
const males = ["abe", "bob", "col", "dan", "ed", "fred", "gav", "hal", "ian", "jon"]
const females = ["abi", "bea", "cath", "dee", "eve", "fay", "gay", "hope", "ivy", "jan"]
const malepreferences = Dict(
"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"]
)
const femalepreferences = Dict(
"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"]
)
function pshuf(d)
ret = Dict()
for (k,v) in d
ret[k] = shuffle(v)
end
ret
end
# helper functions for the verb: p1 "prefers" p2 over p3
pindexin(a, p) = ([i for i in 1:length(a) if a[i] == p])[1]
prefers(d, p1, p2, p3) = (pindexin(d[p1], p2) < pindexin(d[p1], p3))
function isstable(mmatchup, fmatchup, mpref, fpref)
for (mmatch, fmatch) in mmatchup
for f in mpref[mmatch]
if(f != fmatch && prefers(mpref, mmatch, f, fmatch)
&& prefers(fpref, f, mmatch, fmatchup[f]))
println("$mmatch prefers $f and $f prefers $mmatch over their current partners.")
return false
end
end
end
true
end
function galeshapley(men, women, malepref, femalepref)
# Initialize all m ∈ M and w ∈ W to free
mfree = Dict([(p, true) for p in men])
wfree = Dict([(p, true) for p in women])
mpairs = Dict()
wpairs = Dict()
while true # while ∃ free man m who still has a woman w to propose to
bachelors = [p for p in keys(mfree) if mfree[p]]
if(length(bachelors) == 0)
return mpairs, wpairs
end
for m in bachelors
for w in malepref[m] # w = first woman on m’s list to whom m has not yet proposed
if(wfree[w]) # if w is free (else some pair (m', w) already exists)
#println("Free match: $m, $w")
mpairs[m] = w # (m, w) become engaged
wpairs[w] = m # double entry bookeeping
mfree[m] = false
wfree[w] = false
break
elseif(prefers(femalepref, w, m, wpairs[w])) # if w prefers m to m'
#println("Unmatch $(wpairs[w]), match: $m, $w")
mfree[wpairs[w]] = true # m' becomes free
mpairs[m] = w # (m, w) become engaged
wpairs[w] = m
mfree[m] = false
break
end # else (m', w) remain engaged, so continue
end
end
end
end
function tableprint(txt, ans, stab)
println(txt)
println(" Man Woman")
println(" ----- -----")
show(STDOUT, "text/plain", ans)
if(stab)
println("\n ----STABLE----\n\n")
else
println("\n ---UNSTABLE---\n\n")
end
end
println("Use the Gale Shapley algorithm to find a stable set of engagements.")
answer = galeshapley(males, females, malepreferences, femalepreferences)
stabl = isstable(answer[1], answer[2], malepreferences, femalepreferences)
tableprint("Original Data Table", answer[1], stabl)
println("To check this is not a one-off solution, run the function on a randomized sample.")
newmpref = pshuf(malepreferences)
newfpref = pshuf(femalepreferences)
answer = galeshapley(males, females, newmpref, newfpref)
stabl = isstable(answer[1], answer[2], newmpref, newfpref)
tableprint("Shuffled Preferences", answer[1], stabl)
# trade abe with bob
println("Perturb this set of engagements to form an unstable set of engagements then check this new set for stability.")
answer = galeshapley(males, females, malepreferences, femalepreferences)
fia1 = (answer[1])["abe"]
fia2 = (answer[1])["bob"]
answer[1]["abe"] = fia2
answer[1]["bob"] = fia1
answer[2][fia1] = "bob"
answer[2][fia2] = "abe"
stabl = isstable(answer[1], answer[2], malepreferences, femalepreferences)
tableprint("Original Data With Bob and Abe Switched", answer[1], stabl)
|
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #VTL-2 | VTL-2 | 10 N=0
20 S=1
30 C=1
40 #=60
50 C=C+1
60 #=C*C*C<(S*S)*50
70 #=C*C*C=(S*S)*110
80 N=N+1
90 ?=S*S
100 $=32
110 S=S+1
120 #=N<30*60 |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #Wren | Wren | import "/math" for Math
import "/fmt" for Fmt
var i = 1
var sqnc = [] // squares not cubes
var sqcb = [] // squares and cubes
while (sqnc.count < 30 || sqcb.count < 3) {
var sq = i * i
var cb = Math.cbrt(sq).round
if (cb*cb*cb != sq) {
sqnc.add(sq)
} else {
sqcb.add(sq)
}
i = i + 1
}
System.print("The first 30 positive integers which are squares but not cubes are:")
System.print(sqnc.take(30).toList)
System.print("\nThe first 3 positive integers which are both squares and cubes are:")
System.print(sqcb.take(3).toList) |
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
| #SNOBOL4 | SNOBOL4 |
* Program: split_on_change_of_character.sbl
* To run: sbl split_on_change_of_character.sbl
* Description: Split a (character) string into comma (plus a blank)
* delimited strings based on a change of character (left to right).
*
* 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, ++, ///, \
* Comment: Tested using the Spitbol for Linux version of SNOBOL4
lf = substr(&alphabet,11,1) ;* New line or line feed
* Function split_cc will split a string on a change of character.
define('split_cc(s)tchar,target,post')
:(split_cc_end)
split_cc
tchar = substr(s,1,1) :f(freturn)
split_cc_pat = span(*tchar) . target (rpos(0) | len(1) . tchar rem) . post
split_cc2
s ? split_cc_pat = post :f(split_cc3)
split_cc = (ident(split_cc) target, split_cc ', ' target) :s(split_cc2)
split_cc3
:(return)
split_cc_end
test_string = "gHHH5YY++///\"
output = test_string lf
split_string = split_cc(test_string)
output = split_string
END |
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
| #Standard_ML | Standard ML | (*
* Head-Tail implementation of grouping
*)
fun group' ac nil = [ac]
| group' nil (y::ys) = group' [y] ys
| group' (x::ac) (y::ys) = if x=y then group' (y::x::ac) ys else (x::ac) :: group' [y] ys
fun group xs = group' nil xs
fun groupString str = String.concatWith ", " (map implode (group (explode str))) |
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
| #Forth | Forth | : stack ( size -- )
create here cell+ , cells allot ;
: push ( n st -- ) tuck @ ! cell swap +! ;
: pop ( st -- n ) -cell over +! @ @ ;
: empty? ( st -- ? ) dup @ - cell+ 0= ;
10 stack st
1 st push
2 st push
3 st push
st empty? . \ 0 (false)
st pop . st pop . st pop . \ 3 2 1
st empty? . \ -1 (true) |
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)
| #E | E | /** Missing scalar multiplication, but we don't need it. */
def makeVector2(x, y) {
return def vector {
to x() { return x }
to y() { return y }
to add(other) { return makeVector2(x + other.x(), y + other.y()) }
to clockwise() { return makeVector2(-y, x) }
}
}
/** Bugs: (1) The printing is specialized. (2) No bounds check on the column. */
def makeFlex2DArray(rows, cols) {
def storage := ([null] * (rows * cols)).diverge()
return def flex2DArray {
to __printOn(out) {
for y in 0..!rows {
for x in 0..!cols {
out.print(<import:java.lang.makeString>.format("%3d", [flex2DArray[y, x]]))
}
out.println()
}
}
to get(r, c) { return storage[r * cols + c] }
to put(r, c, v) { storage[r * cols + c] := v }
}
} |
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.
| #OASYS | OASYS | val argv : string array
(** The command line arguments given to the process.
The first element is the command name used to invoke the program.
The following elements are the command-line arguments
given to the program. *)
val executable_name : string
(** The name of the file containing the executable currently running. *)
val interactive : bool ref
(** This reference is initially set to [false] in standalone
programs and to [true] if the code is being executed under
the interactive toplevel system [ocaml]. *)
val os_type : string
(** Operating system currently executing the Caml program. One of
- ["Unix"] (for all Unix versions, including Linux and Mac OS X),
- ["Win32"] (for MS-Windows, OCaml compiled with MSVC++ or Mingw),
- ["Cygwin"] (for MS-Windows, OCaml compiled with Cygwin). *)
val word_size : int
(** Size of one word on the machine currently executing the Caml
program, in bits: 32 or 64. *)
val max_string_length : int
(** Maximum length of a string. *)
val max_array_length : int
(** Maximum length of a normal array. The maximum length of a float
array is [max_array_length/2] on 32-bit machines and
[max_array_length] on 64-bit machines. *)
val ocaml_version : string
(** [ocaml_version] is the version of Objective Caml.
It is a string of the form ["major.minor[.patchlevel][+additional-info]"],
where [major], [minor], and [patchlevel] are integers, and
[additional-info] is an arbitrary string. The [[.patchlevel]] and
[[+additional-info]] parts may be absent. *) |
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.
| #OASYS_Assembler | OASYS Assembler | val argv : string array
(** The command line arguments given to the process.
The first element is the command name used to invoke the program.
The following elements are the command-line arguments
given to the program. *)
val executable_name : string
(** The name of the file containing the executable currently running. *)
val interactive : bool ref
(** This reference is initially set to [false] in standalone
programs and to [true] if the code is being executed under
the interactive toplevel system [ocaml]. *)
val os_type : string
(** Operating system currently executing the Caml program. One of
- ["Unix"] (for all Unix versions, including Linux and Mac OS X),
- ["Win32"] (for MS-Windows, OCaml compiled with MSVC++ or Mingw),
- ["Cygwin"] (for MS-Windows, OCaml compiled with Cygwin). *)
val word_size : int
(** Size of one word on the machine currently executing the Caml
program, in bits: 32 or 64. *)
val max_string_length : int
(** Maximum length of a string. *)
val max_array_length : int
(** Maximum length of a normal array. The maximum length of a float
array is [max_array_length/2] on 32-bit machines and
[max_array_length] on 64-bit machines. *)
val ocaml_version : string
(** [ocaml_version] is the version of Objective Caml.
It is a string of the form ["major.minor[.patchlevel][+additional-info]"],
where [major], [minor], and [patchlevel] are integers, and
[additional-info] is an arbitrary string. The [[.patchlevel]] and
[[+additional-info]] parts may be absent. *) |
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
| #11l | 11l | F is_sorted(arr)
L(i) 1..arr.len-1
I arr[i-1] > arr[i]
R 0B
R 1B
F permutation_sort(&arr)
L !is_sorted(arr)
arr.next_permutation()
V arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
permutation_sort(&arr)
print(arr) |
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
| #GUISS | GUISS | -- comment here until end of line
{- comment here -} |
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
| #Haskell | Haskell | -- comment here until end of line
{- comment here -} |
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 | C | #include <stdio.h>
#define SWAP(r,s) do{ t=r; r=s; s=t; } while(0)
void StoogeSort(int a[], int i, int j)
{
int t;
if (a[j] < a[i]) SWAP(a[i], a[j]);
if (j - i > 1)
{
t = (j - i + 1) / 3;
StoogeSort(a, i, j - t);
StoogeSort(a, i + t, j);
StoogeSort(a, i, j - t);
}
}
int main(int argc, char *argv[])
{
int nums[] = {1, 4, 5, 3, -6, 3, 7, 10, -2, -5, 7, 5, 9, -3, 7};
int i, n;
n = sizeof(nums)/sizeof(int);
StoogeSort(nums, 0, n-1);
for(i = 0; i <= n-1; i++)
printf("%5d", nums[i]);
return 0;
} |
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.
| #C.2B.2B | C++ |
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
int main(int argc, char* argv[]) {
std::vector<std::thread> threads;
for (int i = 1; i < argc; ++i) {
threads.emplace_back([i, &argv]() {
int arg = std::stoi(argv[i]);
std::this_thread::sleep_for(std::chrono::seconds(arg));
std::cout << argv[i] << std::endl;
});
}
for (auto& thread : threads) {
thread.join();
}
}
|
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.
| #Clojure | Clojure | (ns sleepsort.core
(require [clojure.core.async :as async :refer [chan go <! <!! >! timeout]]))
(defn sleep-sort [l]
(let [c (chan (count l))]
(doseq [i l]
(go (<! (timeout (* 1000 i)))
(>! c i)))
(<!! (async/into [] (async/take (count l) c))))) |
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].
| #360_Assembly | 360 Assembly | * Selection sort 26/06/2016
SELECSRT CSECT
USING SELECSRT,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13) "
LR R13,R15 "
LA RJ,1 j=1
DO WHILE=(C,RJ,LE,N) do j=1 to n
LR RK,RJ k=j
LR R1,RJ j
SLA R1,2 .
LA R3,A-4(R1) @a(j)
L RT,0(R3) temp=a(j)
LA RI,1(RJ) i=j+1
DO WHILE=(C,RI,LE,N) do i=j+1 to n
LR R1,RI i
SLA R1,2 .
L R2,A-4(R1) a(i)
IF CR,RT,GT,R2 THEN if temp>a(i) then
LR RT,R2 temp=a(i)
LR RK,RI k=i
ENDIF , end if
LA RI,1(RI) i=i+1
ENDDO , end do
L R0,0(R3) a(j)
LR R1,RK k
SLA R1,2 .
ST R0,A-4(R1) a(k)=a(j)
ST RT,0(R3) a(j)=temp;
LA RJ,1(RJ) j=j+1
ENDDO , end do
LA R3,PG pgi=0
LA RI,1 i=1
DO WHILE=(C,RI,LE,N) do i=1 to n
LR R1,RI i
SLA R1,2 .
L R2,A-4(R1) a(i)
XDECO R2,XDEC edit a(i)
MVC 0(4,R3),XDEC+8 output a(i)
LA R3,4(R3) pgi=pgi+4
LA RI,1(RI) i=i+1
ENDDO , end do
XPRNT PG,L'PG print buffer
L R13,4(0,R13) epilog
LM R14,R12,12(R13) "
XR R15,R15 "
BR R14 exit
A DC F'4',F'65',F'2',F'-31',F'0',F'99',F'2',F'83',F'782',F'1'
DC F'45',F'82',F'69',F'82',F'104',F'58',F'88',F'112',F'89',F'74'
N DC A((N-A)/L'A) number of items of a
PG DC CL80' ' buffer
XDEC DS CL12 temp for xdeco
YREGS
RI EQU 6 i
RJ EQU 7 j
RK EQU 8 k
RT EQU 9 temp
END SELECSRT |
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.
| #ALGOL_68 | ALGOL 68 | PROC soundex = (STRING s) STRING:
BEGIN
PROC encode = (CHAR c) CHAR:
BEGIN
# We assume the alphabet is contiguous. #
"-123-12*-22455-12623-1*2-2"[ABS to lower(c) - ABS "a" + 1]
END;
INT soundex code length = 4;
STRING result := soundex code length * "0";
IF s /= "" THEN
CHAR previous;
INT j;
result[j := 1] := s[1];
previous := encode(s[1]);
FOR i FROM 2 TO UPB s WHILE j < soundex code length
DO
IF is alpha(s[i]) THEN
CHAR code = encode(s[i]);
IF is digit(code) AND code /= previous THEN
result[j +:= 1] := code;
previous := code
ELIF code = "-" THEN
# Only vowels (y counts here) hide the last-added character #
previous := code
FI
FI
OD
FI;
result
END;
# Test code to persuade one that it does work. #
MODE TEST = STRUCT (STRING input, STRING expected output);
[] TEST soundex test = (
("Soundex", "S532"), ("Example", "E251"),
("Sownteks", "S532"), ("Ekzampul", "E251"),
("Euler", "E460"), ("Gauss", "G200"),
("Hilbert", "H416"), ("Knuth", "K530"),
("Lloyd", "L300"), ("Lukasiewicz", "L222"),
("Ellery", "E460"), ("Ghosh", "G200"),
("Heilbronn", "H416"), ("Kant", "K530"),
("Ladd", "L300"), ("Lissajous", "L222"),
("Wheaton", "W350"), ("Burroughs", "B620"),
("Burrows", "B620"), ("O'Hara", "O600"),
("Washington", "W252"), ("Lee", "L000"),
("Gutierrez", "G362"), ("Pfister", "P236"),
("Jackson", "J250"), ("Tymczak", "T522"),
("VanDeusen", "V532"), ("Ashcraft", "A261")
);
#
Apologies for the magic number in the padding of the input
and the wired-in heading.
#
print(("Test name Code Got", newline, "----------------------", newline));
FOR i FROM LWB soundex test TO UPB soundex test
DO
STRING output = soundex(input OF soundex test[i]);
printf(($g, n (12 - UPB input OF soundex test[i]) x$, input OF soundex test[i]));
printf(($g, 1x, g, 1x$, expected output OF soundex test[i], output));
printf(($b("ok", "not ok"), 1l$, output = expected output OF soundex test[i]))
OD |
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.
| #ARM_Assembly | ARM Assembly |
/* ARM assembly Raspberry PI */
/* program shellSort.s */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSortOk: .asciz "Table sorted.\n"
szMessSortNok: .asciz "Table not sorted !!!!!.\n"
sMessResult: .ascii "Value : "
sMessValeur: .fill 11, 1, ' ' @ size => 11
szCarriageReturn: .asciz "\n"
.align 4
iGraine: .int 123456
.equ NBELEMENTS, 10
#TableNumber: .int 1,3,6,2,5,9,10,8,4,7
TableNumber: .int 10,9,8,7,6,5,4,3,2,1
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
1:
ldr r0,iAdrTableNumber @ address number table
mov r1,#0 @ not use in routine
mov r2,#NBELEMENTS @ number of élements
bl shellSort
ldr r0,iAdrTableNumber @ address number table
bl displayTable
ldr r0,iAdrTableNumber @ address number table
mov r1,#NBELEMENTS @ number of élements
bl isSorted @ control sort
cmp r0,#1 @ sorted ?
beq 2f
ldr r0,iAdrszMessSortNok @ no !! error sort
bl affichageMess
b 100f
2: @ yes
ldr r0,iAdrszMessSortOk
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrTableNumber: .int TableNumber
iAdrszMessSortOk: .int szMessSortOk
iAdrszMessSortNok: .int szMessSortNok
/******************************************************************/
/* control sorted table */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the number of elements > 0 */
/* r0 return 0 if not sorted 1 if sorted */
isSorted:
push {r2-r4,lr} @ save registers
mov r2,#0
ldr r4,[r0,r2,lsl #2]
1:
add r2,#1
cmp r2,r1
movge r0,#1
bge 100f
ldr r3,[r0,r2, lsl #2]
cmp r3,r4
movlt r0,#0
blt 100f
mov r4,r3
b 1b
100:
pop {r2-r4,lr}
bx lr @ return
/***************************************************/
/* shell Sort */
/***************************************************/
/* r0 contains the address of table */
/* r1 contains the first element but not use !! */
/* this routine use first element at index zero !!! */
/* r2 contains the number of element */
shellSort:
push {r0-r7,lr} @save registers
sub r2,#1 @ index last item
mov r1,r2 @ init gap = last item
1: @ start loop 1
lsrs r1,#1 @ gap = gap / 2
beq 100f @ if gap = 0 -> end
mov r3,r1 @ init loop indice 1
2: @ start loop 2
ldr r4,[r0,r3,lsl #2] @ load first value
mov r5,r3 @ init loop indice 2
3: @ start loop 3
cmp r5,r1 @ indice < gap
blt 4f @ yes -> end loop 2
sub r6,r5,r1 @ index = indice - gap
ldr r7,[r0,r6,lsl #2] @ load second value
cmp r4,r7 @ compare values
strlt r7,[r0,r5,lsl #2] @ store if <
sublt r5,r1 @ indice = indice - gap
blt 3b @ and loop
4: @ end loop 3
str r4,[r0,r5,lsl #2] @ store value 1 at indice 2
add r3,#1 @ increment indice 1
cmp r3,r2 @ end ?
ble 2b @ no -> loop 2
b 1b @ yes loop for new gap
100: @ end function
pop {r0-r7,lr} @ restaur registers
bx lr @ return
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* r0 contains the address of table */
displayTable:
push {r0-r3,lr} @ save registers
mov r2,r0 @ table address
mov r3,#0
1: @ loop display table
ldr r0,[r2,r3,lsl #2]
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function
ldr r0,iAdrsMessResult
bl affichageMess @ display message
add r3,#1
cmp r3,#NBELEMENTS - 1
ble 1b
ldr r0,iAdrszCarriageReturn
bl affichageMess
100:
pop {r0-r3,lr}
bx lr
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal unsigned */
/******************************************************************/
/* r0 contains value and r1 address area */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ else previous position
bne 1b @ and loop
@ and move digit from left of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4]
add r2,#1
add r4,#1
cmp r2,#LGZONECAL
ble 2b
@ and move spaces in end on area
mov r0,r4 @ result length
mov r1,#' ' @ space
3:
strb r1,[r3,r4] @ store space in area
add r4,#1 @ next position
cmp r4,#LGZONECAL
ble 3b @ loop if r4 <= area size
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
//mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3
//movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
|
http://rosettacode.org/wiki/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.
| #Haskell | Haskell | import Data.List.Split (splitOneOf)
import Data.Char (chr)
toSparkLine :: [Double] -> String
toSparkLine xs = map cl xs
where
top = maximum xs
bot = minimum xs
range = top - bot
cl x = chr $ 0x2581 + floor (min 7 ((x - bot) / range * 8))
makeSparkLine :: String -> (String, Stats)
makeSparkLine xs = (toSparkLine parsed, stats parsed)
where
parsed = map read $ filter (not . null) $ splitOneOf " ," xs
data Stats = Stats
{ minValue, maxValue, rangeOfValues :: Double
, numberOfValues :: Int
}
instance Show Stats where
show (Stats mn mx r n) =
"min: " ++
show mn ++
"; max: " ++
show mx ++ "; range: " ++ show r ++ "; no. of values: " ++ show n
stats :: [Double] -> Stats
stats xs =
Stats
{ minValue = mn
, maxValue = mx
, rangeOfValues = mx - mn
, numberOfValues = length xs
}
where
mn = minimum xs
mx = maximum xs
drawSparkLineWithStats :: String -> IO ()
drawSparkLineWithStats xs = putStrLn sp >> print st
where
(sp, st) = makeSparkLine xs
main :: IO ()
main =
mapM_
drawSparkLineWithStats
[ "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"
, "3 2 1 0 -1 -2 -3 -4 -3 -2 -1 0 1 2 3"
, "-1000 100 1000 500 200 -400 -700 621 -189 3"
] |
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.
| #MAXScript | MAXScript | fn strandSort arr =
(
arr = deepcopy arr
local sub = #()
local results = #()
while arr.count > 0 do
(
sub = #()
append sub (amax arr)
deleteitem arr (for i in 1 to arr.count where arr[i] == amax arr collect i)[1]
local i = 1
while i <= arr.count do
(
if arr[i] > sub[sub.count] do
(
append sub arr[i]
deleteitem arr i
)
i += 1
)
results = join sub results
)
return results
) |
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.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref savelog symbols binary
import java.util.List
placesList = [String -
"UK London", "US New York", "US Boston", "US Washington" -
, "UK Washington", "US Birmingham", "UK Birmingham", "UK Boston" -
]
lists = [ -
placesList -
, strandSort(String[] Arrays.copyOf(placesList, placesList.length)) -
]
loop ln = 0 to lists.length - 1
cl = lists[ln]
loop ct = 0 to cl.length - 1
say cl[ct]
end ct
say
end ln
return
method strandSort(A = String[]) public constant binary returns String[]
rl = String[A.length]
al = List strandSort(Arrays.asList(A))
al.toArray(rl)
return rl
method strandSort(Alst = List) public constant binary returns ArrayList
A = ArrayList(Alst)
result = ArrayList()
loop label A_ while A.size > 0
sublist = ArrayList()
sublist.add(A.get(0))
A.remove(0)
loop i_ = 0 while i_ < A.size - 1
if (Comparable A.get(i_)).compareTo(Comparable sublist.get(sublist.size - 1)) > 0 then do
sublist.add(A.get(i_))
A.remove(i_)
end
end i_
result = merge(result, sublist)
end A_
return result
method merge(left = List, right = List) public constant binary returns ArrayList
result = ArrayList()
loop label mx while left.size > 0 & right.size > 0
if (Comparable left.get(0)).compareTo(Comparable right.get(0)) <= 0 then do
result.add(left.get(0))
left.remove(0)
end
else do
result.add(right.get(0))
right.remove(0)
end
end mx
if left.size > 0 then do
result.addAll(left)
end
if right.size > 0 then do
result.addAll(right)
end
return result
|
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)
| #Kotlin | Kotlin |
data class Person(val name: String) {
val preferences = mutableListOf<Person>()
var matchedTo: Person? = null
fun trySwap(p: Person) {
if (prefers(p)) {
matchedTo?.matchedTo = null
matchedTo = p
p.matchedTo = this
}
}
fun prefers(p: Person) = when (matchedTo) {
null -> true
else -> preferences.indexOf(p) < preferences.indexOf(matchedTo!!)
}
fun showMatch() = "$name <=> ${matchedTo?.name}"
}
fun match(males: Collection<Person>) {
while (males.find { it.matchedTo == null }?.also { match(it) } != null) {
}
}
fun match(male: Person) {
while (male.matchedTo == null) {
male.preferences.removeAt(0).trySwap(male)
}
}
fun isStableMatch(males: Collection<Person>, females: Collection<Person>): Boolean {
return males.all { isStableMatch(it, females) }
}
fun isStableMatch(male: Person, females: Collection<Person>): Boolean {
val likesBetter = females.filter { !male.preferences.contains(it) }
val stable = !likesBetter.any { it.prefers(male) }
if (!stable) {
println("#### Unstable pair: ${male.showMatch()}")
}
return stable
}
fun main(args: Array<String>) {
val inMales = mapOf(
"abe" to mutableListOf("abi", "eve", "cath", "ivy", "jan", "dee", "fay", "bea", "hope", "gay"),
"bob" to mutableListOf("cath", "hope", "abi", "dee", "eve", "fay", "bea", "jan", "ivy", "gay"),
"col" to mutableListOf("hope", "eve", "abi", "dee", "bea", "fay", "ivy", "gay", "cath", "jan"),
"dan" to mutableListOf("ivy", "fay", "dee", "gay", "hope", "eve", "jan", "bea", "cath", "abi"),
"ed" to mutableListOf("jan", "dee", "bea", "cath", "fay", "eve", "abi", "ivy", "hope", "gay"),
"fred" to mutableListOf("bea", "abi", "dee", "gay", "eve", "ivy", "cath", "jan", "hope", "fay"),
"gav" to mutableListOf("gay", "eve", "ivy", "bea", "cath", "abi", "dee", "hope", "jan", "fay"),
"hal" to mutableListOf("abi", "eve", "hope", "fay", "ivy", "cath", "jan", "bea", "gay", "dee"),
"ian" to mutableListOf("hope", "cath", "dee", "gay", "bea", "abi", "fay", "ivy", "jan", "eve"),
"jon" to mutableListOf("abi", "fay", "jan", "gay", "eve", "bea", "dee", "cath", "ivy", "hope"))
val inFemales = mapOf(
"abi" to listOf("bob", "fred", "jon", "gav", "ian", "abe", "dan", "ed", "col", "hal"),
"bea" to listOf("bob", "abe", "col", "fred", "gav", "dan", "ian", "ed", "jon", "hal"),
"cath" to listOf("fred", "bob", "ed", "gav", "hal", "col", "ian", "abe", "dan", "jon"),
"dee" to listOf("fred", "jon", "col", "abe", "ian", "hal", "gav", "dan", "bob", "ed"),
"eve" to listOf("jon", "hal", "fred", "dan", "abe", "gav", "col", "ed", "ian", "bob"),
"fay" to listOf("bob", "abe", "ed", "ian", "jon", "dan", "fred", "gav", "col", "hal"),
"gay" to listOf("jon", "gav", "hal", "fred", "bob", "abe", "col", "ed", "dan", "ian"),
"hope" to listOf("gav", "jon", "bob", "abe", "ian", "dan", "hal", "ed", "col", "fred"),
"ivy" to listOf("ian", "col", "hal", "gav", "fred", "bob", "abe", "ed", "jon", "dan"),
"jan" to listOf("ed", "hal", "gav", "abe", "bob", "jon", "col", "ian", "fred", "dan"))
fun buildPrefs(person: Person, stringPrefs: List<String>, population: List<Person>) {
person.preferences.addAll(
stringPrefs.map { name -> population.single { it.name == name } }
)
}
val males = inMales.keys.map { Person(it) }
val females = inFemales.keys.map { Person(it) }
males.forEach { buildPrefs(it, inMales[it.name]!!, females) }
females.forEach { buildPrefs(it, inFemales[it.name]!!, males) }
match(males)
males.forEach { println(it.showMatch()) }
println("#### match is stable: ${isStableMatch(males, females)}")
fun swapMatch(male1: Person, male2: Person) {
val female1 = male1.matchedTo!!
val female2 = male2.matchedTo!!
male1.matchedTo = female2
male2.matchedTo = female1
female1.matchedTo = male2
female2.matchedTo = male1
}
swapMatch(males.single { it.name == "fred" }, males.single { it.name == "jon" })
males.forEach { println(it.showMatch()) }
println("#### match is stable: ${isStableMatch(males, females)}")
}
|
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #XPL0 | XPL0 | int C, N, N2, T;
[C:= 0; N:= 1;
loop [N2:= N*N;
IntOut(0, N2);
T:= fix(Pow(float(N2), 1./3.));
if T*T*T # N2 then
[ChOut(0, ^ );
C:= C+1;
if C >= 30 then quit;
]
else Text(0, "* ");
N:= N+1;
];
Text(0, "^m^j* are both squares and cubes.^m^j");
] |
http://rosettacode.org/wiki/Square_but_not_cube | Square but not cube | Task
Show the first 30 positive integers which are squares but not cubes of such integers.
Optionally, show also the first 3 positive integers which are both squares and cubes, and mark them as such.
| #zkl | zkl | println("First 30 positive integers that are a square but not a cube:");
squareButNotCube:=(1).walker(*).tweak(fcn(n){
sq,cr := n*n, sq.toFloat().pow(1.0/3).round(); // cube root(64)<4
if(sq==cr*cr*cr) Void.Skip else sq
});
squareButNotCube.walk(30).concat(",").println("\n");
println("First 15 positive integers that are both a square and a cube:");
println((1).walker(*).tweak((1).pow.unbind().fp1(6)).walk(15)); |
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
| #Swift | Swift | public extension String {
func splitOnChanges() -> [String] {
guard !isEmpty else {
return []
}
var res = [String]()
var workingChar = first!
var workingStr = "\(workingChar)"
for char in dropFirst() {
if char != workingChar {
res.append(workingStr)
workingStr = "\(char)"
workingChar = char
} else {
workingStr += String(char)
}
}
res.append(workingStr)
return res
}
}
print("gHHH5YY++///\\".splitOnChanges().joined(separator: ", ")) |
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
| #Tailspin | Tailspin |
composer splitEquals
<reps> <nextReps>*
rule reps: <'(.)\1*'>
rule nextReps: <reps> -> \(', ' ! $ ! \)
end splitEquals
'gHHH5YY++///\' -> splitEquals -> !OUT::write
|
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
| #Fortran | Fortran | module mod_stack
implicit none
type node
! data entry in each node
real*8, private :: data
! pointer to the next node of the linked list
type(node), pointer, private :: next
end type node
private node
type stack
! pointer to first element of stack.
type(node), pointer, private :: first
! size of stack
integer, private :: len=0
contains
procedure :: pop
procedure :: push
procedure :: peek
procedure :: getSize
procedure :: clearStack
procedure :: isEmpty
end type stack
contains
function pop(this) result(x)
class(stack) :: this
real*8 :: x
type(node), pointer :: tmp
if ( this%len == 0 ) then
print*, "popping from empty stack"
!stop
end if
tmp => this%first
x = this%first%data
this%first => this%first%next
deallocate(tmp)
this%len = this%len -1
end function pop
subroutine push(this, x)
real*8 :: x
class(stack), target :: this
type(node), pointer :: new, tmp
allocate(new)
new%data = x
if (.not. associated(this%first)) then
this%first => new
else
tmp => this%first
this%first => new
this%first%next => tmp
end if
this%len = this%len + 1
end subroutine push
function peek(this) result(x)
class(stack) :: this
real*8 :: x
x = this%first%data
end function peek
function getSize(this) result(n)
class(stack) :: this
integer :: n
n = this%len
end function getSize
function isEmpty(this) result(empty)
class(stack) :: this
logical :: empty
if ( this%len > 0 ) then
empty = .FALSE.
else
empty = .TRUE.
end if
end function isEmpty
subroutine clearStack(this)
class(stack) :: this
type(node), pointer :: tmp
integer :: i
if ( this%len == 0 ) then
return
end if
do i = 1, this%len
tmp => this%first
if ( .not. associated(tmp)) exit
this%first => this%first%next
deallocate(tmp)
end do
this%len = 0
end subroutine clearStack
end module mod_stack
program main
use mod_stack
type(stack) :: my_stack
integer :: i
real*8 :: dat
do i = 1, 5, 1
dat = 1.0 * i
call my_stack%push(dat)
end do
do while ( .not. my_stack%isEmpty() )
print*, my_stack%pop()
end do
call my_stack%clearStack()
end program main |
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)
| #Elixir | Elixir | defmodule RC do
def spiral_matrix(n) do
wide = length(to_char_list(n*n-1))
fmt = String.duplicate("~#{wide}w ", n) <> "~n"
runs = Enum.flat_map(n..1, &[&1,&1]) |> tl
delta = Stream.cycle([{0,1},{1,0},{0,-1},{-1,0}])
running(Enum.zip(runs,delta),0,-1,[])
|> Enum.with_index |> Enum.sort |> Enum.chunk(n)
|> Enum.each(fn row -> :io.format fmt, (for {_,i} <- row, do: i) end)
end
defp running([{run,{dx,dy}}|rest], x, y, track) do
new_track = Enum.reduce(1..run, track, fn i,acc -> [{x+i*dx, y+i*dy} | acc] end)
running(rest, x+run*dx, y+run*dy, new_track)
end
defp running([],_,_,track), do: track |> Enum.reverse
end
RC.spiral_matrix(5) |
http://rosettacode.org/wiki/Special_variables | Special variables | Special variables have a predefined meaning within a computer programming language.
Task
List the special variables used within the language.
| #OCaml | OCaml | val argv : string array
(** The command line arguments given to the process.
The first element is the command name used to invoke the program.
The following elements are the command-line arguments
given to the program. *)
val executable_name : string
(** The name of the file containing the executable currently running. *)
val interactive : bool ref
(** This reference is initially set to [false] in standalone
programs and to [true] if the code is being executed under
the interactive toplevel system [ocaml]. *)
val os_type : string
(** Operating system currently executing the Caml program. One of
- ["Unix"] (for all Unix versions, including Linux and Mac OS X),
- ["Win32"] (for MS-Windows, OCaml compiled with MSVC++ or Mingw),
- ["Cygwin"] (for MS-Windows, OCaml compiled with Cygwin). *)
val word_size : int
(** Size of one word on the machine currently executing the Caml
program, in bits: 32 or 64. *)
val max_string_length : int
(** Maximum length of a string. *)
val max_array_length : int
(** Maximum length of a normal array. The maximum length of a float
array is [max_array_length/2] on 32-bit machines and
[max_array_length] on 64-bit machines. *)
val ocaml_version : string
(** [ocaml_version] is the version of Objective Caml.
It is a string of the form ["major.minor[.patchlevel][+additional-info]"],
where [major], [minor], and [patchlevel] are integers, and
[additional-info] is an arbitrary string. The [[.patchlevel]] and
[[+additional-info]] parts may be absent. *) |
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
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program permutationSort64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeConstantesARM64.inc"
/*******************************************/
/* Structures */
/********************************************/
/* structure permutations */
.struct 0
perm_adrtable: // table value address
.struct perm_adrtable + 8
perm_size: // elements number
.struct perm_size + 8
perm_adrheap: // Init to zéro at the first call
.struct perm_adrheap + 8
perm_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSortOk: .asciz "Table sorted.\n"
szMessSortNok: .asciz "Table not sorted !!!!!.\n"
sMessCounter: .asciz "sorted in @ permutations \n"
sMessResult: .asciz "Value : @ \n"
szCarriageReturn: .asciz "\n"
.align 4
#TableNumber: .quad 1,3,6,2,5,9,10,8,4,7,11
TableNumber: .quad 10,9,8,7,6,-5,4,3,2,1
.equ NBELEMENTS, (. - TableNumber) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
stPermutation: .skip perm_end
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrstPermutation // address structure permutation
ldr x1,qAdrTableNumber // address number table
str x1,[x0,perm_adrtable]
mov x1,NBELEMENTS // elements number
str x1,[x0,perm_size]
mov x1,0 // first call
str x1,[x0,perm_adrheap]
mov x20,0 // counter
1:
ldr x0,qAdrstPermutation // address structure permutation
bl newPermutation // call for each permutation
cmp x0,0 // end ?
blt 99f // yes -> error
//bl displayTable // for display after each permutation
add x20,x20,1 // increment counter
ldr x0,qAdrTableNumber // address number table
mov x1,NBELEMENTS // number of élements
bl isSorted // control sort
cmp x0,1 // sorted ?
bne 1b // no -> loop
ldr x0,qAdrTableNumber // address number table
bl displayTable
ldr x0,qAdrszMessSortOk // address OK message
bl affichageMess
mov x0,x20 // display counter
ldr x1,qAdrsZoneConv
bl conversion10S // décimal conversion
ldr x0,qAdrsMessCounter
ldr x1,qAdrsZoneConv // insert conversion
bl strInsertAtCharInc
bl affichageMess // display message
b 100f
99:
ldr x0,qAdrTableNumber // address number table
bl displayTable
ldr x0,qAdrszMessSortNok // address not OK message
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
qAdrstPermutation: .quad stPermutation
qAdrszMessSortOk: .quad szMessSortOk
qAdrszMessSortNok: .quad szMessSortNok
qAdrsMessCounter: .quad sMessCounter
/******************************************************************/
/* control sorted table */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the number of elements > 0 */
/* x0 return 0 if not sorted 1 if sorted */
isSorted:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
mov x2,0
ldr x4,[x0,x2,lsl 3]
1:
add x2,x2,1
cmp x2,x1
bge 99f
ldr x3,[x0,x2, lsl 3]
cmp x3,x4
blt 98f
mov x4,x3
b 1b
98:
mov x0,0 // not sorted
b 100f
99:
mov x0,1 // sorted
100:
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/***************************************************/
/* return permutation one by one */
/* sur une idée de vincent Moresmau */
/* use algorytm heap iteratif see wikipedia */
/***************************************************/
/* x0 contains the address of structure permutations */
/* x0 return address of value table or zéro if end */
newPermutation:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
ldr x2,[x0,perm_adrheap]
cmp x2,0
bne 2f
// first call -> init area on heap
mov x7,x0
ldr x1,[x7,perm_size]
lsl x3,x1,3 // 8 bytes by count table
add x3,x3,8 // 8 bytes for current index
mov x0,0 // allocation place heap
mov x8,BRK // call system 'brk'
svc 0
mov x2,x0 // save address heap
add x0,x0,x3 // reservation place
mov x8,BRK // call system 'brk'
svc #0
cmp x0,-1 // allocation error
beq 100f
add x8,x2,8 // address begin area counters
mov x3,0
1: // loop init
str xzr,[x8,x3,lsl 3] // init to zéro area heap
add x3,x3,1
cmp x3,x1
blt 1b
str xzr,[x2] // store zero to index
str x2,[x7,perm_adrheap] // store heap address on structure permutation
ldr x0,[x7,perm_adrtable] // return first permutation
b 100f
2: // other calls x2 contains heap address
mov x7,x0 // structure address
ldr x1,[x7,perm_size] // elements number
ldr x0,[x7,perm_adrtable]
add x8,x2,8 // begin address area count
ldr x3,[x2] // load current index
3:
ldr x4,[x8,x3,lsl 3] // load count [i]
cmp x4,x3 // compare with i
bge 6f
tst x3,#1 // even ?
bne 4f
ldr x5,[x0] // yes load value A[0]
ldr x6,[x0,x3,lsl 3] // and swap with value A[i]
str x6,[x0]
str x5,[x0,x3,lsl 3]
b 5f
4:
ldr x5,[x0,x4,lsl 3] // no load value A[count[i]]
ldr x6,[x0,x3,lsl 3] // and swap with value A[i]
str x6,[x0,x4,lsl 3]
str x5,[x0,x3,lsl 3]
5:
add x4,x4,1
str x4,[x8,x3,lsl 3] // store new count [i]
str xzr,[x2] // store new index
b 100f // and return new permutation in x0
6:
str xzr,[x8,x3,lsl 3] // store zero in count [i]
add x3,x3,1 // increment index
cmp x3,x1 // end
blt 3b // loop
mov x0,0 // if end -> return zero
100: // end function
ldp x6,x7,[sp],16 // restaur 1 register
ldp x4,x5,[sp],16 // restaur 1 register
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* x0 contains the address of table */
displayTable:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x0 // table address
mov x3,0
1: // loop display table
ldr x0,[x2,x3,lsl 3]
ldr x1,qAdrsZoneConv
bl conversion10S // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at // character
bl affichageMess // display message
add x3,x3,1
cmp x3,NBELEMENTS - 1
ble 1b
ldr x0,qAdrszCarriageReturn
bl affichageMess
mov x0,x2
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
|
http://rosettacode.org/wiki/Sorting_algorithms/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
| #ActionScript | ActionScript | //recursively builds the permutations of permutable, appended to front, and returns the first sorted permutation it encounters
function permutations(front:Array, permutable:Array):Array {
//If permutable has length 1, there is only one possible permutation. Check whether it's sorted
if (permutable.length==1)
return isSorted(front.concat(permutable));
else
//There are multiple possible permutations. Generate them.
var i:uint=0,tmp:Array=null;
do
{
tmp=permutations(front.concat([permutable[i]]),remove(permutable,i));
i++;
}while (i< permutable.length && tmp == null);
//If tmp != null, it contains the sorted permutation. If it does not contain the sorted permutation, return null. Either way, return tmp.
return tmp;
}
//returns the array if it's sorted, or null otherwise
function isSorted(data:Array):Array {
for (var i:uint = 1; i < data.length; i++)
if (data[i]<data[i-1])
return null;
return data;
}
//returns a copy of array with the i'th element removed
function remove(array:Array, i:uint):Array {
return array.filter(function(item,index,array){return(index !=i)}) ;
}
//wrapper around the permutation function to provide a more logical interface
function permutationSort(array:Array):Array {
return permutations([],array);
} |
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
| #HicEst | HicEst | \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
| #HTML | HTML | \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/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.23 | C# | public static void Sort<T>(List<T> list) where T : IComparable {
if (list.Count > 1) {
StoogeSort(list, 0, list.Count - 1);
}
}
private static void StoogeSort<T>(List<T> L, int i, int j) where T : IComparable {
if (L[j].CompareTo(L[i])<0) {
T tmp = L[i];
L[i] = L[j];
L[j] = tmp;
}
if (j - i > 1) {
int t = (j - i + 1) / 3;
StoogeSort(L, i, j - t);
StoogeSort(L, i + t, j);
StoogeSort(L, i, j - t);
}
} |
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.
| #CoffeeScript | CoffeeScript |
after = (s, f) -> setTimeout f, s*1000
# Setting Computer Science back at least a century, maybe more,
# this algorithm sorts integers using a highly parallelized algorithm.
sleep_sort = (arr) ->
for n in arr
do (n) -> after n, -> console.log n
do ->
input = (parseInt(arg) for arg in process.argv[2...])
sleep_sort input
|
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.
| #Common_Lisp | Common Lisp | (defun sleeprint(n)
(sleep (/ n 10))
(format t "~a~%" n))
(loop for arg in (cdr sb-ext:*posix-argv*) doing
(sb-thread:make-thread (lambda() (sleeprint (parse-integer arg)))))
(loop while (not (null (cdr (sb-thread:list-all-threads))))) |
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].
| #AArch64_Assembly | AArch64 Assembly |
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program selectionSort64.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 1,3,6,2,5,9,10,8,4,7
TableNumber: .quad 10,9,8,7,6,5,4,3,2,1
.equ NBELEMENTS, (. - TableNumber) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrTableNumber // address number table
mov x1,0
mov x2,NBELEMENTS // number of élements
bl selectionSort
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
/******************************************************************/
/* selection sort */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the first element */
/* x2 contains the number of element */
selectionSort:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
mov x3,x1 // start index i
sub x7,x2,1 // compute n - 1
1: // start loop
mov x4,x3
add x5,x3,1 // init index 2
2:
ldr x1,[x0,x4,lsl 3] // load value A[mini]
ldr x6,[x0,x5,lsl 3] // load value A[j]
cmp x6,x1 // compare value
csel x4,x5,x4,lt // j -> mini
add x5,x5,1 // increment index j
cmp x5,x2 // end ?
blt 2b // no -> loop
cmp x4,x3 // mini <> j ?
beq 3f // no
ldr x1,[x0,x4,lsl 3] // yes swap A[i] A[mini]
ldr x6,[x0,x3,lsl 3]
str x1,[x0,x3,lsl 3]
str x6,[x0,x4,lsl 3]
3:
add x3,x3,1 // increment i
cmp x3,x7 // end ?
blt 1b // no -> loop
100:
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* x0 contains the address of table */
displayTable:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x0 // table address
mov x3,0
1: // loop display table
ldr x0,[x2,x3,lsl 3]
ldr x1,qAdrsZoneConv
bl conversion10 // 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
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/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.
| #ANSI_Standard_BASIC | ANSI Standard BASIC | 100 DECLARE EXTERNAL FUNCTION FNSoundex$
110
120 DATA Ashcraft, Ashcroft, Gauss, Ghosh, Hilbert, Heilbronn, Lee, Lloyd
130 DATA Moses, Pfister, Robert, Rupert, Rubin, Tymczak, Soundex, Example
140 FOR i = 1 TO 16
150 READ name$
160 PRINT """"; name$; """"; TAB(15); FNsoundex$(name$)
170 NEXT i
180 END
190
200 EXTERNAL FUNCTION FNsoundex$(name$)
210 LET name$ = UCASE$(name$)
220 LET n$ = "01230129022455012623019202"
230 LET s$ = name$(1:1)
240 LET p = VAL(n$(ORD(s$) - 64 : ORD(s$) - 64))
250 FOR i = 2 TO LEN(name$)
260 LET n = VAL(n$(ORD(name$(i:i)) - 64: ORD(name$(i:i)) - 64))
270 IF n <> 0 AND n <> 9 AND n <> p THEN LET s$ = s$ & STR$(n)
280 IF n <> 9 THEN LET p = n
290 NEXT i
300 LET s$ = s$ & "000"
310 LET FNSoundex$ = s$(1:4)
320 END FUNCTION |
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.
| #Arturo | Arturo | shellSort: function [items][
a: new items
h: size a
while [h > 0][
h: h / 2
loop h..dec size a 'i [
k: a\[i]
j: i
while [and? [j >= h] [k < a\[j-h]]][
a\[j]: a\[j-h]
j: j - h
]
a\[j]: k
]
]
return a
]
print shellSort [3 1 2 8 5 7 9 4 6] |
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.
| #J | J | spkln =: verb define
y spkln~ 4 u:16b2581+i.8 NB. ▁▂▃▄▅▆▇█
:
'MIN MAX' =. (<./ , >./) y
N =. # x
x {~ <. (N-1) * (y-MIN) % MAX-MIN
) |
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.
| #Java | Java |
public class Sparkline
{
String bars="▁▂▃▄▅▆▇█";
public static void main(String[] args)
{
Sparkline now=new Sparkline();
float[] arr={1, 2, 3, 4, 5, 6, 7, 8, 7, 6, 5, 4, 3, 2, 1};
now.display1D(arr);
System.out.println(now.getSparkline(arr));
float[] arr1={1.5f, 0.5f, 3.5f, 2.5f, 5.5f, 4.5f, 7.5f, 6.5f};
now.display1D(arr1);
System.out.println(now.getSparkline(arr1));
}
public void display1D(float[] arr)
{
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
System.out.println();
}
public String getSparkline(float[] arr)
{
float min=Integer.MAX_VALUE;
float max=Integer.MIN_VALUE;
for(int i=0;i<arr.length;i++)
{
if(arr[i]<min)
min=arr[i];
if(arr[i]>max)
max=arr[i];
}
float range=max-min;
int num=bars.length()-1;
String line="";
for(int i=0;i<arr.length;i++)
{
line+=bars.charAt((int)Math.ceil(((arr[i]-min)/range*num)));
}
return line;
}
}
|
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.
| #Nim | Nim | proc mergeList[T](a, b: var seq[T]): seq[T] =
result = @[]
while a.len > 0 and b.len > 0:
if a[0] < b[0]:
result.add a[0]
a.delete 0
else:
result.add b[0]
b.delete 0
result.add a
result.add b
proc strand[T](a: var seq[T]): seq[T] =
var i = 0
result = @[a[0]]
a.delete 0
while i < a.len:
if a[i] > result[result.high]:
result.add a[i]
a.delete i
else:
inc i
proc strandSort[T](a: seq[T]): seq[T] =
var a = a
result = a.strand
while a.len > 0:
var s = a.strand
result = mergeList(result, s)
var a = @[1, 6, 3, 2, 1, 7, 5, 3]
echo a.strandSort |
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.
| #OCaml | OCaml | let rec strand_sort (cmp : 'a -> 'a -> int) : 'a list -> 'a list = function
[] -> []
| x::xs ->
let rec extract_strand x = function
[] -> [x], []
| x1::xs when cmp x x1 <= 0 ->
let strand, rest = extract_strand x1 xs in x::strand, rest
| x1::xs ->
let strand, rest = extract_strand x xs in strand, x1::rest
in
let strand, rest = extract_strand x xs in
List.merge cmp strand (strand_sort cmp rest) |
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)
| #Lua | Lua | local Person = {}
Person.__index = Person
function Person.new(inName)
local o = {
name = inName,
prefs = nil,
fiance = nil,
_candidateIndex = 1,
}
return setmetatable(o, Person)
end
function Person:indexOf(other)
for i, p in pairs(self.prefs) do
if p == other then return i end
end
return 999
end
function Person:prefers(other)
return self:indexOf(other) < self:indexOf(self.fiance)
end
function Person:nextCandidateNotYetProposedTo()
if self._candidateIndex >= #self.prefs then return nil end
local c = self.prefs[self._candidateIndex];
self._candidateIndex = self._candidateIndex + 1
return c;
end
function Person:engageTo(other)
if other.fiance then
other.fiance.fiance = nil
end
other.fiance = self
if self.fiance then
self.fiance.fiance = nil
end
self.fiance = other;
end
local function isStable(men)
local women = men[1].prefs
local stable = true
for _, guy in pairs(men) do
for _, gal in pairs(women) do
if guy:prefers(gal) and gal:prefers(guy) then
stable = false
print(guy.name .. ' and ' .. gal.name ..
' prefer each other over their partners ' ..
guy.fiance.name .. ' and ' .. gal.fiance.name)
end
end
end
return stable
end
local abe = Person.new("Abe")
local bob = Person.new("Bob")
local col = Person.new("Col")
local dan = Person.new("Dan")
local ed = Person.new("Ed")
local fred = Person.new("Fred")
local gav = Person.new("Gav")
local hal = Person.new("Hal")
local ian = Person.new("Ian")
local jon = Person.new("Jon")
local abi = Person.new("Abi")
local bea = Person.new("Bea")
local cath = Person.new("Cath")
local dee = Person.new("Dee")
local eve = Person.new("Eve")
local fay = Person.new("Fay")
local gay = Person.new("Gay")
local hope = Person.new("Hope")
local ivy = Person.new("Ivy")
local jan = Person.new("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 }
local men = abi.prefs
local freeMenCount = #men
while freeMenCount > 0 do
for _, guy in pairs(men) do
if not guy.fiance then
local gal = guy:nextCandidateNotYetProposedTo()
if not gal.fiance then
guy:engageTo(gal)
freeMenCount = freeMenCount - 1
elseif gal:prefers(guy) then
guy:engageTo(gal)
end
end
end
end
print(' ')
for _, guy in pairs(men) do
print(guy.name .. ' is engaged to ' .. guy.fiance.name)
end
print('Stable: ', isStable(men))
print(' ')
print('Switching ' .. fred.name .. "'s & " .. jon.name .. "'s partners")
jon.fiance, fred.fiance = fred.fiance, jon.fiance
print('Stable: ', isStable(men))
|
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
| #tbas | tbas | SUB SPLITUNIQUE$(s$)
DIM c$, d$, split$, i%
c$ = LEFT$(s$, 1)
split$ = ""
FOR i% = 1 TO LEN(s$)
d$ = MID$(s$, i%, 1)
IF d$ <> c$ THEN
split$ = split$ + ", "
c$ = d$
END IF
split$ = split$ + d$
NEXT
RETURN split$
END SUB
PRINT SPLITUNIQUE$("gHHH5YY++///\")
END |
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
| #Tcl | Tcl | set string "gHHH5YY++///\\"
regsub -all {(.)\1*} $string {\0, } string
regsub {, $} $string {} string
puts $string |
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
| #Free_Pascal | Free Pascal | program Stack;
{$IFDEF FPC}{$MODE DELPHI}{$IFDEF WINDOWS}{$APPTYPE CONSOLE}{$ENDIF}{$ENDIF}
{$ASSERTIONS ON}
uses Generics.Collections;
var
lStack: TStack<Integer>;
begin
lStack := TStack<Integer>.Create;
try
lStack.Push(1);
lStack.Push(2);
lStack.Push(3);
Assert(lStack.Peek = 3); // 3 should be at the top of the stack
Write(lStack.Pop:2); // 3
Write(lStack.Pop:2); // 2
Writeln(lStack.Pop:2); // 1
Assert(lStack.Count = 0, 'Stack is not empty'); // should be empty
finally
lStack.Free;
end;
end. |
http://rosettacode.org/wiki/Spiral_matrix | Spiral matrix | Task
Produce a spiral array.
A spiral array is a square arrangement of the first N2 natural numbers, where the
numbers increase sequentially as you go around the edges of the array spiraling inwards.
For example, given 5, produce this array:
0 1 2 3 4
15 16 17 18 5
14 23 24 19 6
13 22 21 20 7
12 11 10 9 8
Related tasks
Zig-zag matrix
Identity_matrix
Ulam_spiral_(for_primes)
| #Euphoria | Euphoria | function spiral(integer dimension)
integer side, curr, curr2
sequence s
s = repeat(repeat(0,dimension),dimension)
side = dimension
curr = 0
for i = 0 to floor(dimension/2) do
for j = 1 to side-1 do
s[i+1][i+j] = curr -- top
curr2 = curr + side-1
s[i+j][i+side] = curr2 -- right
curr2 += side-1
s[i+side][i+side-j+1] = curr2 -- bottom
curr2 += side-1
s[i+side-j+1][i+1] = curr2 -- left
curr += 1
end for
curr = curr2 + 1
side -= 2
end for
if remainder(dimension,2) then
s[floor(dimension/2)+1][floor(dimension/2)+1] = curr
end if
return s
end function
? spiral(5) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.