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/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #VBA | VBA | Sub Main()
Dim temp() As String
temp = Tokenize("Hello,How,Are,You,Today", ",")
Display temp, Space(5)
End Sub
Private Function Tokenize(strS As String, sep As String) As String()
Tokenize = Split(strS, sep)
End Function
Private Sub Display(arr() As String, sep As String)
Debug.Print Join(arr, sep)
End Sub |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
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
| #VBScript_2 | VBScript |
s = "Hello,How,Are,You,Today"
WScript.StdOut.Write Join(Split(s,","),".")
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #NetRexx | NetRexx | /* NetRexx */
options replace format comments java crossref symbols binary
runSample(arg)
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
parse arg discs .
if discs = '', discs < 1 then discs = 4
say 'Minimum moves to solution:' 2 ** discs - 1
moves = move(discs)
say 'Solved in' moves 'moves.'
return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method move(discs = int 4, towerFrom = int 1, towerTo = int 2, towerVia = int 3, moves = int 0) public static
if discs == 1 then do
moves = moves + 1
say 'Move disc from peg' towerFrom 'to peg' towerTo '- Move No:' Rexx(moves).right(5)
end
else do
moves = move(discs - 1, towerFrom, towerVia, towerTo, moves)
moves = move(1, towerFrom, towerTo, towerVia, moves)
moves = move(discs - 1, towerVia, towerTo, towerFrom, moves)
end
return moves
|
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
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
| #Vedit_macro_language | Vedit macro language | Buf_Switch(Buf_Free)
Ins_Text("Hello,How,Are,You,Today")
// Split the text into text registers 10, 11, ...
BOF
#1 = 9
Repeat(ALL) {
#1++
#2 = Cur_Pos
Search(",", ADVANCE+ERRBREAK)
Reg_Copy_Block(#1, #2, Cur_Pos-1)
}
Reg_Copy_Block(#1, #2, EOB_Pos)
// Display the list
for (#3 = 10; #3 <= #1; #3++) {
Reg_Type(#3) Message(".")
}
Buf_Quit(OK) |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
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
| #Vlang | Vlang | // Tokenize a string, in V
// Tectonics: v run tokenize-a-string.v
module main
// starts here
pub fn main() {
println("Hello,How,Are,You,Today".split(',').join('.'))
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #NewLISP | NewLISP | (define (move n from to via)
(if (> n 0)
(move (- n 1) from via to
(print "move disk from pole " from " to pole " to "\n")
(move (- n 1) via to from))))
(move 4 1 2 3) |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
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
| #WinBatch | WinBatch | text = 'Hello,How,Are,You,Today'
result = ''
BoxOpen('WinBatch Tokenizing Example', '')
for ix = 1 to itemcount(text,',')
result = result : itemextract(ix, text, ',') : '.'
BoxText(result)
next
display(10, 'End of Program', 'Dialog and program will close momentarily.')
BoxShut() |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
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
| #Wortel | Wortel | @join "." @split "," "Hello,How,Are,You,Today" |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Nim | Nim | proc hanoi(disks: int; fromTower, toTower, viaTower: string) =
if disks != 0:
hanoi(disks - 1, fromTower, viaTower, toTower)
echo("Move disk ", disks, " from ", fromTower, " to ", toTower)
hanoi(disks - 1, viaTower, toTower, fromTower)
hanoi(4, "1", "2", "3") |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Wren | Wren | var s = "Hello,How,Are,You,Today"
var t = s.split(",").join(".") + "."
System.print(t) |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
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
| #XPath_2.0 | XPath 2.0 | string-join(tokenize("Hello,How,Are,You,Today", ","), ".") |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Objeck | Objeck | class Hanoi {
function : Main(args : String[]) ~ Nil {
Move(4, 1, 2, 3);
}
function: Move(n:Int, f:Int, t:Int, v:Int) ~ Nil {
if(n = 1) {
"Move disk from pole {$f} to pole {$t}"->PrintLine();
}
else {
Move(n - 1, f, v, t);
Move(1, f, t, v);
Move(n - 1, v, t, f);
};
}
} |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #XPL0 | XPL0 | string 0;
include c:\cxpl\codes;
int I, J, K, Char;
char String, Array(5,6); \5 words and 5 maximum chars + terminating 0
[String:= "Hello,How,Are,You,Today";
I:= 0; K:= 0;
repeat J:= 0;
loop [Char:= String(I);
I:= I+1;
if Char=^, or Char=0 then quit;
Array(K,J):= Char;
J:= J+1;
];
Array(K,J):= 0; \terminate word
K:= K+1; \next word in array
until K>=5;
for K:= 4 downto 0 do [Text(0, addr Array(K,0)); ChOut(0, ^.)];
CrLf(0);
] |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Yabasic | Yabasic | dim s$(1)
n = token("Hello. How are you today?", s$(), ".? ")
for i = 1 to n
print s$(i);
if i < n print ".";
next
print |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Objective-C | Objective-C | #import <Foundation/NSObject.h>
@interface TowersOfHanoi: NSObject {
int pegFrom;
int pegTo;
int pegVia;
int numDisks;
}
-(void) setPegFrom: (int) from andSetPegTo: (int) to andSetPegVia: (int) via andSetNumDisks: (int) disks;
-(void) movePegFrom: (int) from andMovePegTo: (int) to andMovePegVia: (int) via andWithNumDisks: (int) disks;
@end |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #zkl | zkl | "Hello,How,Are,You,Today".split(",").concat(".").println();
Hello.How.Are.You.Today |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
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
| #Zoea | Zoea |
program: tokenize_a_string
input: "Hello,How,Are,You,Today"
output: "Hello.How.Are.You.Today"
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #OCaml | OCaml | let rec hanoi n a b c =
if n <> 0 then begin
hanoi (pred n) a c b;
Printf.printf "Move disk from pole %d to pole %d\n" a b;
hanoi (pred n) c b a
end
let () =
hanoi 4 1 2 3 |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
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
| #Zoea_Visual | Zoea Visual | str='Hello,How,Are,You,Today'
tokens=(${(s:,:)str})
print ${(j:.:)tokens} |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
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
| #Zsh | Zsh | str='Hello,How,Are,You,Today'
tokens=(${(s:,:)str})
print ${(j:.:)tokens} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Octave | Octave | function hanoimove(ndisks, from, to, via)
if ( ndisks == 1 )
printf("Move disk from pole %d to pole %d\n", from, to);
else
hanoimove(ndisks-1, from, via, to);
hanoimove(1, from, to, via);
hanoimove(ndisks-1, via, to, from);
endif
endfunction
hanoimove(4, 1, 2, 3); |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Oforth | Oforth | : move(n, from, to, via)
n 0 > ifTrue: [
move(n 1-, from, via, to)
System.Out "Move disk from " << from << " to " << to << cr
move(n 1-, via, to, from)
] ;
5 $left $middle $right) move |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Oz | Oz | declare
proc {TowersOfHanoi N From To Via}
if N > 0 then
{TowersOfHanoi N-1 From Via To}
{System.showInfo "Move from "#From#" to "#To}
{TowersOfHanoi N-1 Via To From}
end
end
in
{TowersOfHanoi 4 left middle right} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #PARI.2FGP | PARI/GP | \\ Towers of Hanoi
\\ 8/19/2016 aev
\\ Where: n - number of disks, sp - start pole, ep - end pole.
HanoiTowers(n,sp,ep)={
if(n!=0,
HanoiTowers(n-1,sp,6-sp-ep);
print("Move disk ", n, " from pole ", sp," to pole ", ep);
HanoiTowers(n-1,6-sp-ep,ep);
);
}
\\ Testing n=3:
HanoiTowers(3,1,3); |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Pascal | Pascal | program Hanoi;
type
TPole = (tpLeft, tpCenter, tpRight);
const
strPole:array[TPole] of string[6]=('left','center','right');
procedure MoveStack (const Ndisks : integer; const Origin,Destination,Auxiliary:TPole);
begin
if Ndisks >0 then begin
MoveStack(Ndisks - 1, Origin,Auxiliary, Destination );
Writeln('Move disk ',Ndisks ,' from ',strPole[Origin],' to ',strPole[Destination]);
MoveStack(Ndisks - 1, Auxiliary, Destination, origin);
end;
end;
begin
MoveStack(4,tpLeft,tpCenter,tpRight);
end. |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Perl | Perl | sub hanoi {
my ($n, $from, $to, $via) = (@_, 1, 2, 3);
if ($n == 1) {
print "Move disk from pole $from to pole $to.\n";
} else {
hanoi($n - 1, $from, $via, $to);
hanoi(1, $from, $to, $via);
hanoi($n - 1, $via, $to, $from);
};
}; |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Phix | Phix | constant poles = {"left","middle","right"}
enum left, middle, right
sequence disks
integer moves
procedure showpegs(integer src, integer dest)
string desc = sprintf("%s to %s:",{poles[src],poles[dest]})
disks[dest] &= disks[src][$]
disks[src] = disks[src][1..$-1]
for i=1 to length(disks) do
printf(1,"%-16s | %s\n",{desc,join(sq_add(disks[i],'0'),' ')})
desc = ""
end for
printf(1,"\n")
moves += 1
end procedure
procedure hanoir(integer n, src=left, dest=right, via=middle)
if n>0 then
hanoir(n-1, src, via, dest)
showpegs(src,dest)
hanoir(n-1, via, dest, src)
end if
end procedure
procedure hanoi(integer n)
disks = {reverse(tagset(n)),{},{}}
moves = 0
hanoir(n)
printf(1,"completed in %d moves\n",{moves})
end procedure
hanoi(3) -- (output of 4,5,6 also shown)
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #PHL | PHL | module hanoi;
extern printf;
@Void move(@Integer n, @Integer from, @Integer to, @Integer via) [
if (n > 0) {
move(n - 1, from, via, to);
printf("Move disk from pole %d to pole %d\n", from, to);
move(n - 1, via, to, from);
}
]
@Integer main [
move(4, 1,2,3);
return 0;
] |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #PHP | PHP | function move($n,$from,$to,$via) {
if ($n === 1) {
print("Move disk from pole $from to pole $to");
} else {
move($n-1,$from,$via,$to);
move(1,$from,$to,$via);
move($n-1,$via,$to,$from);
}
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Picat | Picat | main =>
hanoi(3, left, center, right).
hanoi(0, _From, _To, _Via) => true.
hanoi(N, From, To, Via) =>
hanoi(N - 1, From, Via, To),
printf("Move disk %w from pole %w to pole %w\n", N, From, To),
hanoi(N - 1, Via, To, From).
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #PicoLisp | PicoLisp | (de move (N A B C) # Use: (move 3 'left 'center 'right)
(unless (=0 N)
(move (dec N) A C B)
(println 'Move 'disk 'from A 'to B)
(move (dec N) C B A) ) ) |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #PL.2FI | PL/I | tower: proc options (main);
call Move (4,1,2,3);
Move: procedure (ndiscs, from, to, via) recursive;
declare (ndiscs, from, to, via) fixed binary;
if ndiscs = 1 then
put skip edit ('Move disc from pole ', trim(from), ' to pole ',
trim(to) ) (a);
else
do;
call Move (ndiscs-1, from, via, to);
call Move (1, from, to, via);
call Move (ndiscs-1, via, to, from);
end;
end Move;
end tower; |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #PL.2FM | PL/M | 100H: /* ITERATIVE TOWERS OF HANOI; TRANSLATED FROM TINY BASIC (VIA ALGOL W) */
/* CP/M BDOS SYSTEM CALL */
BDOS: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END;
/* I/O ROUTINES */
PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS( 2, C ); END;
PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS( 9, S ); END;
DECLARE ( D, N, X, S, T ) ADDRESS;
/* FIXED NUMBER OF DISCS: 4 */
N = 1;
DO D = 1 TO 4;
N = N + N;
END;
DO X = 1 TO N - 1;
/* AS IN ALGOL W, WE CAN USE PL/M'S BIT ABD MOD OPERATORS */
S = ( X AND ( X - 1 ) ) MOD 3;
T = ( ( X OR ( X - 1 ) ) + 1 ) MOD 3;
CALL PR$STRING( .'MOVE DISC ON PEG $' );
CALL PR$CHAR( '1' + S );
CALL PR$STRING( .' TO PEG $' );
CALL PR$CHAR( '1' + T );
CALL PR$STRING( .( 0DH, 0AH, '$' ) );
END;
EOF |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Plain_TeX | Plain TeX | \newcount\hanoidepth
\def\hanoi#1{%
\hanoidepth = #1
\move abc
}%
\def\move#1#2#3{%
\advance \hanoidepth by -1
\ifnum \hanoidepth > 0
\move #1#3#2
\fi
Move the upper disk from pole #1 to pole #3.\par
\ifnum \hanoidepth > 0
\move#2#1#3
\fi
\advance \hanoidepth by 1
}
\hanoi{5}
\end |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Pop11 | Pop11 | define hanoi(n, src, dst, via);
if n > 0 then
hanoi(n - 1, src, via, dst);
'Move disk ' >< n >< ' from ' >< src >< ' to ' >< dst >< '.' =>
hanoi(n - 1, via, dst, src);
endif;
enddefine;
hanoi(4, "left", "middle", "right"); |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #PostScript | PostScript | %!PS-Adobe-3.0
%%BoundingBox: 0 0 300 300
/plate {
exch 100 mul 50 add exch th mul 10 add moveto
dup s mul neg 2 div 0 rmoveto
dup s mul 0 rlineto
0 th rlineto
s neg mul 0 rlineto
closepath gsave .5 setgray fill grestore 0 setgray stroke
} def
/drawtower {
0 1 2 { /x exch def /y 0 def
tower x get {
dup 0 gt { x y plate /y y 1 add def } {pop} ifelse
} forall
} for showpage
} def
/apop { [ exch aload pop /last exch def ] last } def
/apush{ [ 3 1 roll aload pop counttomark -1 roll ] } def
/hanoi {
0 dict begin /from /mid /to /h 5 -1 2 { -1 roll def } for
h 1 eq {
tower from get apop tower to get apush
tower to 3 -1 roll put
tower from 3 -1 roll put
drawtower
} {
/h h 1 sub def
from to mid h hanoi
from mid to 1 hanoi
mid from to h hanoi
} ifelse
end
} def
/n 12 def
/s 90 n div def
/th 180 n div def
/tower [ [n 1 add -1 2 { } for ] [] [] ] def
drawtower 0 1 2 n hanoi
%%EOF |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #PowerShell | PowerShell |
function hanoi($n, $a, $b, $c) {
if($n -eq 1) {
"$a -> $c"
} else{
hanoi ($n - 1) $a $c $b
hanoi 1 $a $b $c
hanoi ($n - 1) $b $a $c
}
}
hanoi 3 "A" "B" "C"
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Prolog | Prolog | hanoi(N) :- move(N,left,center,right).
move(0,_,_,_) :- !.
move(N,A,B,C) :-
M is N-1,
move(M,A,C,B),
inform(A,B),
move(M,C,B,A).
inform(X,Y) :- write([move,a,disk,from,the,X,pole,to,Y,pole]), nl. |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #PureBasic | PureBasic | Procedure Hanoi(n, A.s, C.s, B.s)
If n
Hanoi(n-1, A, B, C)
PrintN("Move the plate from "+A+" to "+C)
Hanoi(n-1, B, C, A)
EndIf
EndProcedure |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Python | Python | def hanoi(ndisks, startPeg=1, endPeg=3):
if ndisks:
hanoi(ndisks-1, startPeg, 6-startPeg-endPeg)
print "Move disk %d from peg %d to peg %d" % (ndisks, startPeg, endPeg)
hanoi(ndisks-1, 6-startPeg-endPeg, endPeg)
hanoi(ndisks=4) |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Quackery | Quackery | [ stack ] is rings ( --> [ )
[ rings share
depth share -
8 * times sp
emit sp emit sp
say 'move' cr ] is echomove ( c c --> )
[ dup rings put
depth put
char a char b char c
[ swap decurse
rot 2dup echomove
decurse
swap rot ]
3 times drop
depth release
rings release ] is hanoi ( n --> n )
say 'How to solve a three ring Towers of Hanoi puzzle:' cr cr
3 hanoi cr |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Quite_BASIC | Quite BASIC | 'This is implemented on the Quite BASIC website
'http://www.quitebasic.com/prj/puzzle/towers-of-hanoi/
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #R | R | hanoimove <- function(ndisks, from, to, via) {
if (ndisks == 1) {
cat("move disk from", from, "to", to, "\n")
} else {
hanoimove(ndisks - 1, from, via, to)
hanoimove(1, from, to, via)
hanoimove(ndisks - 1, via, to, from)
}
}
hanoimove(4, 1, 2, 3) |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Racket | Racket |
#lang racket
(define (hanoi n a b c)
(when (> n 0)
(hanoi (- n 1) a c b)
(printf "Move ~a to ~a\n" a b)
(hanoi (- n 1) c b a)))
(hanoi 4 'left 'middle 'right)
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Raku | Raku | subset Peg of Int where 1|2|3;
multi hanoi (0, Peg $a, Peg $b, Peg $c) { }
multi hanoi (Int $n, Peg $a = 1, Peg $b = 2, Peg $c = 3) {
hanoi $n - 1, $a, $c, $b;
say "Move $a to $b.";
hanoi $n - 1, $c, $b, $a;
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Rascal | Rascal | public void hanoi(ndisks, startPeg, endPeg){
if(ndisks>0){
hanoi(ndisks-1, startPeg, 6 - startPeg - endPeg);
println("Move disk <ndisks> from peg <startPeg> to peg <endPeg>");
hanoi(ndisks-1, 6 - startPeg - endPeg, endPeg);
}
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Raven | Raven | define hanoi use ndisks, startpeg, endpeg
ndisks 0 > if
6 startpeg - endpeg - startpeg ndisks 1 - hanoi
endpeg startpeg ndisks "Move disk %d from peg %d to peg %d\n" print
endpeg 6 startpeg - endpeg - ndisks 1 - hanoi
define dohanoi use ndisks
# startpeg=1, endpeg=3
3 1 ndisks hanoi
# 4 disks
4 dohanoi
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #REBOL | REBOL | rebol [
Title: "Towers of Hanoi"
URL: http://rosettacode.org/wiki/Towers_of_Hanoi
]
hanoi: func [
{Begin moving the golden disks from one pole to the next.
Note: when last disk moved, the world will end.}
disks [integer!] "Number of discs on starting pole."
/poles "Name poles."
from to via
][
if disks = 0 [return]
if not poles [from: 'left to: 'middle via: 'right]
hanoi/poles disks - 1 from via to
print [from "->" to]
hanoi/poles disks - 1 via to from
]
hanoi 4 |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Retro | Retro | ~~~
{ 'Num 'From 'To 'Via } [ var ] a:for-each
:set !Via !To !From !Num ;
:display @To @From 'Move_a_ring_from_%n_to_%n\n s:format s:put ;
:hanoi (num,from,to,via-)
set @Num n:-zero?
[ @Num @From @To @Via
@Num n:dec @From @Via @To hanoi set display
@Num n:dec @Via @To @From hanoi ] if ;
#3 #1 #3 #2 hanoi nl
~~~ |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #REXX | REXX | /*REXX program displays the moves to solve the Tower of Hanoi (with N disks). */
parse arg N . /*get optional number of disks from CL.*/
if N=='' | N=="," then N=3 /*Not specified? Then use the default.*/
#= 0 /*#: the number of disk moves (so far)*/
z= 2**N - 1 /*Z: " " " minimum # of moves.*/
call mov 1, 3, N /*move the top disk, then recurse ··· */
say /* [↓] Display the minimum # of moves.*/
say 'The minimum number of moves to solve a ' N"─disk Tower of Hanoi is " z
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
mov: procedure expose # z; parse arg @1,@2,@3; L= length(z)
if @3==1 then do; #= # + 1 /*bump the (disk) move counter by one. */
say 'step' right(#, L)": move disk on tower" @1 '───►' @2
end
else do; call mov @1, 6 -@1 -@2, @3 -1
call mov @1, @2, 1
call mov 6 - @1 - @2, @2, @3 -1
end
return /* [↑] this subroutine uses recursion.*/ |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Ring | Ring |
move(4, 1, 2, 3)
func move n, src, dst, via
if n > 0 move(n - 1, src, via, dst)
see "" + src + " to " + dst + nl
move(n - 1, via, dst, src) ok
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Ruby | Ruby | def move(num_disks, start=0, target=1, using=2)
if num_disks == 1
@towers[target] << @towers[start].pop
puts "Move disk from #{start} to #{target} : #{@towers}"
else
move(num_disks-1, start, using, target)
move(1, start, target, using)
move(num_disks-1, using, target, start)
end
end
n = 5
@towers = [[*1..n].reverse, [], []]
move(n) |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Run_BASIC | Run BASIC | a = move(4, "1", "2", "3")
function move(n, a$, b$, c$)
if n > 0 then
a = move(n-1, a$, c$, b$)
print "Move disk from " ; a$ ; " to " ; c$
a = move(n-1, b$, a$, c$)
end if
end function |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Rust | Rust | fn move_(n: i32, from: i32, to: i32, via: i32) {
if n > 0 {
move_(n - 1, from, via, to);
println!("Move disk from pole {} to pole {}", from, to);
move_(n - 1, via, to, from);
}
}
fn main() {
move_(4, 1,2,3);
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #SASL | SASL | hanoi 8 ‘abc"
WHERE
hanoi 0 (a,b,c,) = ()
hanoi n ( a,b,c) = hanoi (n-1) (a,c,b) ,
‘move a disc from " , a , ‘ to " , b , NL ,
hanoi (n-1) (c,b,a)
? |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Sather | Sather | class MAIN is
move(ndisks, from, to, via:INT) is
if ndisks = 1 then
#OUT + "Move disk from pole " + from + " to pole " + to + "\n";
else
move(ndisks-1, from, via, to);
move(1, from, to, via);
move(ndisks-1, via, to, from);
end;
end;
main is
move(4, 1, 2, 3);
end;
end; |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Scala | Scala | def move(n: Int, from: Int, to: Int, via: Int) : Unit = {
if (n == 1) {
Console.println("Move disk from pole " + from + " to pole " + to)
} else {
move(n - 1, from, via, to)
move(1, from, to, via)
move(n - 1, via, to, from)
}
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Scheme | Scheme | (define (towers-of-hanoi n from to spare)
(define (print-move from to)
(display "Move[")
(display from)
(display ", ")
(display to)
(display "]")
(newline))
(cond ((= n 0) "done")
(else
(towers-of-hanoi (- n 1) from spare to)
(print-move from to)
(towers-of-hanoi (- n 1) spare to from))))
(towers-of-hanoi 3 "A" "B" "C") |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Seed7 | Seed7 | const proc: hanoi (in integer: disk, in string: source, in string: dest, in string: via) is func
begin
if disk > 0 then
hanoi(pred(disk), source, via, dest);
writeln("Move disk " <& disk <& " from " <& source <& " to " <& dest);
hanoi(pred(disk), via, dest, source);
end if;
end func; |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Sidef | Sidef | func hanoi(n, from=1, to=2, via=3) {
if (n == 1) {
say "Move disk from pole #{from} to pole #{to}.";
} else {
hanoi(n-1, from, via, to);
hanoi( 1, from, to, via);
hanoi(n-1, via, to, from);
}
}
hanoi(4); |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #SNOBOL4 | SNOBOL4 | * # Note: count is global
define('hanoi(n,src,trg,tmp)') :(hanoi_end)
hanoi hanoi = eq(n,0) 1 :s(return)
hanoi(n - 1, src, tmp, trg)
count = count + 1
output = count ': Move disc from ' src ' to ' trg
hanoi(n - 1, tmp, trg, src) :(return)
hanoi_end
* # Test with 4 discs
hanoi(4,'A','C','B')
end |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Standard_ML | Standard ML | fun hanoi(0, a, b, c) = [] |
hanoi(n, a, b, c) = hanoi(n-1, a, c, b) @ [(a,b)] @ hanoi(n-1, c, b, a);
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Stata | Stata | function hanoi(n, a, b, c) {
if (n>0) {
hanoi(n-1, a, c, b)
printf("Move from %f to %f\n", a, b)
hanoi(n-1, c, b, a)
}
}
hanoi(3, 1, 2, 3)
Move from 1 to 2
Move from 1 to 3
Move from 2 to 3
Move from 1 to 2
Move from 3 to 1
Move from 3 to 2
Move from 1 to 2 |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Swift | Swift | func hanoi(n:Int, a:String, b:String, c:String) {
if (n > 0) {
hanoi(n - 1, a, c, b)
println("Move disk from \(a) to \(c)")
hanoi(n - 1, b, a, c)
}
}
hanoi(4, "A", "B", "C") |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Tcl | Tcl | interp alias {} hanoi {} do_hanoi 0
proc do_hanoi {count n {from A} {to C} {via B}} {
if {$n == 1} {
interp alias {} hanoi {} do_hanoi [incr count]
puts "$count: move from $from to $to"
} else {
incr n -1
hanoi $n $from $via $to
hanoi 1 $from $to $via
hanoi $n $via $to $from
}
}
hanoi 4 |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #TI-83_BASIC | TI-83 BASIC | PROGRAM:TOHSOLVE
0→A
1→B
0→C
0→D
0→M
1→R
While A<1 or A>7
Input "No. of rings=?",A
End
randM(A+1,3)→[C]
[[1,2][1,3][2,3]]→[E]
Fill(0,[C])
For(I,1,A,1)
I?[C](I,1)
End
ClrHome
While [C](1,3)≠1 and [C](1,2)≠1
For(J,1,3)
For(I,1,A)
If [C](I,J)≠0:Then
Output(I+1,3J,[C](I,J))
End
End
End
While C=0
Output(1,3B," ")
1→I
[E](R,2)→J
While [C](I,J)=0 and I≤A
I+1→I
End
[C](I,J)→D
1→I
[E](R,1)→J
While [C](I,J)=0 and I≤A
I+1→I
End
If (D<[C](I,J) and D≠0) or [C](I,J)=0:Then
[E](R,2)→B
Else
[E](R,1)→B
End
1→I
While [C](I,B)=0 and I≤A
I+1→I
End
If I≤A:Then
[C](I,B)→C
0→[C](I,B)
Output(I+1,3B," ")
End
Output(1,3B,"V")
End
While C≠0
Output(1,3B," ")
If B=[E](R,2):Then
[E](R,1)→B
Else
[E](R,2)→B
End
1→I
While [C](I,B)=0 and I≤A
I+1→I
End
If [C](I,B)=0 or [C](I,B)>C:Then
C→[C](I-1,B)
0→C
M+1→M
End
End
Output(1,3B,"V")
R+1→R
If R=4:Then:1→R:End
End
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Tiny_BASIC | Tiny BASIC | 5 PRINT "How many disks?"
INPUT D
IF D < 1 THEN GOTO 5
IF D > 10 THEN GOTO 5
LET N = 1
10 IF D = 0 THEN GOTO 20
LET D = D - 1
LET N = 2*N
GOTO 10
20 LET X = 0
30 LET X = X + 1
IF X = N THEN END
GOSUB 40
LET S = S - 3*(S/3)
GOSUB 50
LET T = T + 1
LET T = T - 3*(T/3)
PRINT "Move disc on peg ",S+1," to peg ",T+1
GOTO 30
40 LET B = X - 1
LET A = X
LET S = 0
LET Z = 2048
45 LET C = 0
IF B >= Z THEN LET C = 1
IF A >= Z THEN LET C = C + 1
IF C = 2 THEN LET S = S + Z
IF A >= Z THEN LET A = A - Z
IF B >= Z THEN LET B = B - Z
LET Z = Z / 2
IF Z = 0 THEN RETURN
GOTO 45
50 LET B = X - 1
LET A = X
LET T = 0
LET Z = 2048
55 LET C = 0
IF B >= Z THEN LET C = 1
IF A >= Z THEN LET C = C + 1
IF C > 0 THEN LET T = T + Z
IF A >= Z THEN LET A = A - Z
IF B >= Z THEN LET B = B - Z
LET Z = Z / 2
IF Z = 0 THEN RETURN
GOTO 55 |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Toka | Toka | value| sa sb sc n |
[ to sc to sb to sa to n ] is vars!
[ ( num from to via -- )
vars!
n 0 <>
[
n sa sb sc
n 1- sa sc sb recurse
vars!
." Move a ring from " sa . ." to " sb . cr
n 1- sc sb sa recurse
] ifTrue
] is hanoi |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #True_BASIC | True BASIC |
DECLARE SUB hanoi
SUB hanoi(n, desde , hasta, via)
IF n > 0 THEN
CALL hanoi(n - 1, desde, via, hasta)
PRINT "Mover disco"; n; "desde posición"; desde; "hasta posición"; hasta
CALL hanoi(n - 1, via, hasta, desde)
END IF
END SUB
PRINT "Tres discos"
PRINT
CALL hanoi(3, 1, 2, 3)
PRINT
PRINT "Cuatro discos"
PRINT
CALL hanoi(4, 1, 2, 3)
PRINT
PRINT "Pulsa un tecla para salir"
END
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #TSE_SAL | TSE SAL | // library: program: run: towersofhanoi: recursive: sub <description></description> <version>1.0.0.0.0</version> <version control></version control> (filenamemacro=runprrsu.s) [kn, ri, tu, 07-02-2012 19:54:23]
PROC PROCProgramRunTowersofhanoiRecursiveSub( INTEGER totalDiskI, STRING fromS, STRING toS, STRING viaS, INTEGER bufferI )
IF ( totalDiskI == 0 )
RETURN()
ENDIF
PROCProgramRunTowersofhanoiRecursiveSub( totalDiskI - 1, fromS, viaS, toS, bufferI )
AddLine( Format( "Move disk", " ", totalDiskI, " ", "from peg", " ", "'", fromS, "'", " ", "to peg", " ", "'", toS, "'" ), bufferI )
PROCProgramRunTowersofhanoiRecursiveSub( totalDiskI - 1, viaS, toS, fromS, bufferI )
END
// library: program: run: towersofhanoi: recursive <description></description> <version>1.0.0.0.6</version> <version control></version control> (filenamemacro=runprtre.s) [kn, ri, tu, 07-02-2012 19:40:45]
PROC PROCProgramRunTowersofhanoiRecursive( INTEGER totalDiskI, STRING fromS, STRING toS, STRING viaS )
INTEGER bufferI = 0
PushPosition()
bufferI = CreateTempBuffer()
PopPosition()
PROCProgramRunTowersofhanoiRecursiveSub( totalDiskI, fromS, toS, viaS, bufferI )
GotoBufferId( bufferI )
END
PROC Main()
STRING s1[255] = "4"
IF ( NOT ( Ask( "program: run: towersofhanoi: recursive: totalDiskI = ", s1, _EDIT_HISTORY_ ) ) AND ( Length( s1 ) > 0 ) ) RETURN() ENDIF
PROCProgramRunTowersofhanoiRecursive( Val( s1 ), "source", "target", "via" )
END |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #uBasic.2F4tH | uBasic/4tH | Proc _Move(4, 1,2,3) ' 4 disks, 3 poles
End
_Move Param(4)
If (a@ > 0) Then
Proc _Move (a@ - 1, b@, d@, c@)
Print "Move disk from pole ";b@;" to pole ";c@
Proc _Move (a@ - 1, d@, c@, b@)
EndIf
Return |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #UNIX_Shell | UNIX Shell | #!/bin/bash
move()
{
local n="$1"
local from="$2"
local to="$3"
local via="$4"
if [[ "$n" == "1" ]]
then
echo "Move disk from pole $from to pole $to"
else
move $(($n - 1)) $from $via $to
move 1 $from $to $via
move $(($n - 1)) $via $to $from
fi
}
move $1 $2 $3 $4 |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Ursala | Ursala | #import nat
move = ~&al^& ^rlPlrrPCT/~&arhthPX ^|W/~& ^|G/predecessor ^/~&htxPC ~&zyxPC
#show+
main = ^|T(~&,' -> '--)* move/4 <'start','end','middle'> |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #VBScript | VBScript | Sub Move(n,fromPeg,toPeg,viaPeg)
If n > 0 Then
Move n-1, fromPeg, viaPeg, toPeg
WScript.StdOut.Write "Move disk from " & fromPeg & " to " & toPeg
WScript.StdOut.WriteBlankLines(1)
Move n-1, viaPeg, toPeg, fromPeg
End If
End Sub
Move 4,1,2,3
WScript.StdOut.Write("Towers of Hanoi puzzle completed!") |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Vedit_macro_language | Vedit macro language | #1=1; #2=2; #3=3; #4=4 // move 4 disks from 1 to 2
Call("MOVE_DISKS")
Return
// Move disks
// #1 = from, #2 = to, #3 = via, #4 = number of disks
//
:MOVE_DISKS:
if (#4 > 0) {
Num_Push(1,4)
#9=#2; #2=#3; #3=#9; #4-- // #1 to #3 via #2
Call("MOVE_DISKS")
Num_Pop(1,4)
Ins_Text("Move a disk from ") // move one disk
Num_Ins(#1, LEFT+NOCR)
Ins_Text(" to ")
Num_Ins(#2, LEFT)
Num_Push(1,4)
#9=#1; #1=#3; #3 = #9; #4-- // #3 to #2 via #1
Call("MOVE_DISKS")
Num_Pop(1,4)
}
Return |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Vim_Script | Vim Script | function TowersOfHanoi(n, from, to, via)
if (a:n > 1)
call TowersOfHanoi(a:n-1, a:from, a:via, a:to)
endif
echom("Move a disc from " . a:from . " to " . a:to)
if (a:n > 1)
call TowersOfHanoi(a:n-1, a:via, a:to, a:from)
endif
endfunction
call TowersOfHanoi(4, 1, 3, 2) |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Visual_Basic_.NET | Visual Basic .NET | Module TowersOfHanoi
Sub MoveTowerDisks(ByVal disks As Integer, ByVal fromTower As Integer, ByVal toTower As Integer, ByVal viaTower As Integer)
If disks > 0 Then
MoveTowerDisks(disks - 1, fromTower, viaTower, toTower)
System.Console.WriteLine("Move disk {0} from {1} to {2}", disks, fromTower, toTower)
MoveTowerDisks(disks - 1, viaTower, toTower, fromTower)
End If
End Sub
Sub Main()
MoveTowerDisks(4, 1, 2, 3)
End Sub
End Module |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #VTL-2 | VTL-2 | 1000 N=4
1010 F=1
1020 T=2
1030 V=3
1040 S=0
1050 #=2000
1060 #=9999
2000 R=!
2010 #=N<1*2210
2020 #=4000
2030 N=N-1
2040 A=T
2050 T=V
2060 V=A
2070 #=2000
2080 #=5000
2090 ?="Move disk from peg: ";
2100 ?=F
2110 ?=" to peg: ";
2120 ?=T
2130 ?=""
2140 #=4000
2150 N=N-1
2160 A=F
2170 F=V
2180 V=A
2190 #=2000
2200 #=5000
2210 #=R
4000 S=S+1
4010 :S)=R
4020 S=S+1
4030 :S)=N
4040 S=S+1
4050 :S)=F
4060 S=S+1
4070 :S)=V
4080 S=S+1
4090 :S)=T
4100 #=!
5000 T=:S)
5010 S=S-1
5020 V=:S)
5030 S=S-1
5040 F=:S)
5050 S=S-1
5060 N=:S)
5070 S=S-1
5080 R=:S)
5090 S=S-1
5100 #=! |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Wren | Wren | class Hanoi {
construct new(disks) {
_moves = 0
System.print("Towers of Hanoi with %(disks) disks:\n")
move(disks, "L", "C", "R")
System.print("\nCompleted in %(_moves) moves\n")
}
move(n, from, to, via) {
if (n > 0) {
move(n - 1, from, via, to)
_moves = _moves + 1
System.print("Move disk %(n) from %(from) to %(to)")
move(n - 1, via, to, from)
}
}
}
Hanoi.new(3)
Hanoi.new(4) |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #XPL0 | XPL0 | code Text=12;
proc MoveTower(Discs, From, To, Using);
int Discs, From, To, Using;
[if Discs > 0 then
[MoveTower(Discs-1, From, Using, To);
Text(0, "Move from "); Text(0, From);
Text(0, " peg to "); Text(0, To); Text(0, " peg.^M^J");
MoveTower(Discs-1, Using, To, From);
];
];
MoveTower(3, "left", "right", "center") |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #XQuery | XQuery | declare function local:hanoi($disk as xs:integer, $from as xs:integer,
$to as xs:integer, $via as xs:integer) as element()*
{
if($disk > 0)
then (
local:hanoi($disk - 1, $from, $via, $to),
<move disk='{$disk}'><from>{$from}</from><to>{$to}</to></move>,
local:hanoi($disk - 1, $via, $to, $from)
)
else ()
};
<hanoi>
{
local:hanoi(4, 1, 2, 3)
}
</hanoi> |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #XSLT | XSLT | <xsl:template name="hanoi">
<xsl:param name="n"/>
<xsl:param name="from">left</xsl:param>
<xsl:param name="to">middle</xsl:param>
<xsl:param name="via">right</xsl:param>
<xsl:if test="$n > 0">
<xsl:call-template name="hanoi">
<xsl:with-param name="n" select="$n - 1"/>
<xsl:with-param name="from" select="$from"/>
<xsl:with-param name="to" select="$via"/>
<xsl:with-param name="via" select="$to"/>
</xsl:call-template>
<fo:block>
<xsl:text>Move disk from </xsl:text>
<xsl:value-of select="$from"/>
<xsl:text> to </xsl:text>
<xsl:value-of select="$to"/>
</fo:block>
<xsl:call-template name="hanoi">
<xsl:with-param name="n" select="$n - 1"/>
<xsl:with-param name="from" select="$via"/>
<xsl:with-param name="to" select="$to"/>
<xsl:with-param name="via" select="$from"/>
</xsl:call-template>
</xsl:if>
</xsl:template> |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Yabasic | Yabasic | sub hanoi(ndisks, startPeg, endPeg)
if ndisks then
hanoi(ndisks-1, startPeg, 6-startPeg-endPeg)
//print "Move disk ", ndisks, " from ", startPeg, " to ", endPeg
hanoi(ndisks-1, 6-startPeg-endPeg, endPeg)
end if
end sub
print "Be patient, please.\n\n"
print "Hanoi 1 ellapsed ... ";
t1 = peek("millisrunning")
hanoi(22, 1, 3)
t2 = peek("millisrunning")
print t2-t1, " ms"
sub hanoi2(n, from, to_, via)
if n = 1 then
//print "Move from ", from, " to ", to_
else
hanoi2(n - 1, from, via , to_ )
hanoi2(1 , from, to_ , via )
hanoi2(n - 1, via , to_ , from)
end if
end sub
print "Hanoi 2 ellapsed ... ";
hanoi2(22, 1, 3, 2)
print peek("millisrunning") - t2, " ms" |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Zig | Zig | const std = @import("std");
pub fn print(from: u32, to: u32) void {
std.log.info("Moving disk from rod {} to rod {}", .{ from, to });
}
pub fn move(n: u32, from: u32, via: u32, to: u32) void {
if (n > 1) {
move(n - 1, from, to, via);
print(from, to);
move(n - 1, via, from, to);
} else {
print(from, to);
}
}
pub fn main() !void {
move(4, 1, 2, 3);
}
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #zkl | zkl | fcn move(n, from,to,via){
if (n>0){
move(n-1, from,via,to);
println("Move disk from pole %d to pole %d".fmt(from, to));
move(n-1, via,to,from);
}
}
move(3, 1,2,3); |
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #11l | 11l | F sieve_of_Sundaram(nth, print_all = 1B)
‘
The sieve of Sundaram is a simple deterministic algorithm for finding all the
prime numbers up to a specified integer. This function is modified from the
Wikipedia entry wiki/Sieve_of_Sundaram, to give primes to their nth rather
than the Wikipedia function that gives primes less than n.
’
assert(nth > 0, ‘nth must be a positive integer’)
V k = Int((2.4 * nth * log(nth)) I/ 2)
V integers_list = [1B] * k
L(i) 1 .< k
V j = Int64(i)
L i + j + 2 * i * j < k
integers_list[Int(i + j + 2 * i * j)] = 0B
j++
V pcount = 0
L(i) 1 .. k
I integers_list[i]
pcount++
I print_all
print(f:‘{2 * i + 1:4}’, end' ‘ ’)
I pcount % 10 == 0
print()
I pcount == nth
print("\nSundaram primes start with 3. The "nth‘th Sundaram prime is ’(2 * i + 1)".\n")
L.break
sieve_of_Sundaram(100, 1B)
sieve_of_Sundaram(1000000, 0B) |
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #ALGOL_68 | ALGOL 68 | BEGIN # sieve of Sundaram #
INT n = 8 000 000;
INT none = 0, mark1 = 1, mark2 = 2;
[ 1 : n ]INT mark;
FOR i FROM LWB mark TO UPB mark DO mark[ i ] := none OD;
FOR i FROM 4 BY 3 TO UPB mark DO mark[ i ] := mark1 OD;
INT count := 0; # Count of primes. #
[ 1 : 100 ]INT list100; # First 100 primes. #
INT last := 0; # Millionth prime. #
INT step := 5; # Current step for marking. #
FOR i TO n WHILE last = 0 DO
IF mark[ i ] = none THEN # Add/count a new odd prime. #
count +:= 1;
IF count <= 100 THEN
list100[ count ] := 2 * i + 1
ELIF count = 1 000 000 THEN
last := 2 * i + 1
FI
ELIF mark[ i ] = mark1 THEN # Mark new numbers using current step. #
IF i > 4 THEN
FOR k FROM i + step BY step TO n DO
IF mark[ k ] = none THEN mark[ k ] := mark2 FI
OD;
step +:= 2
FI
# ELSE must be mark2 - Ignore this number. #
FI
OD;
print( ( "First 100 Sundaram primes:", newline ) );
FOR i FROM LWB list100 TO UPB list100 DO
print( ( whole( list100[ i ], -3 ) ) );
IF i MOD 10 = 0 THEN print( ( newline ) ) ELSE print( ( " " ) ) FI
OD;
print( ( newline ) );
IF last = 0 THEN
print( ( "Not enough values in sieve. Found only ", whole( count, 0 ), newline ) )
ELSE
print( ( "The millionth Sundaram prime is ", whole( last, 0 ), newline ) )
FI
END |
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #AppleScript | AppleScript | on sieveOfSundaram(indexRange)
if (indexRange's class is list) then
set n1 to beginning of indexRange
set n2 to end of indexRange
else
set n1 to indexRange
set n2 to indexRange
end if
script o
property lst : {}
end script
set {unmarked, marked} to {true, false}
-- Build a list of 'true's corresponding to the unmarked start numbers implied by the
-- 1-based indices. The Python and Julia solutions note that the nth prime is approximately
-- n * 1.2 * log(n), but the number from which it'll be derived is only about half that.
-- 15 is added too here to ensure headroom with lower prime counts.
set limit to (do shell script "echo '" & n2 & " * 0.6 * l(" & n2 & ") + 15'| bc -l") as integer
set len to 1500
repeat len times
set end of o's lst to unmarked
end repeat
repeat while (len < limit)
set o's lst to o's lst & o's lst
set len to len + len
end repeat
-- Since it's a given that every third slot from 4 on will be "marked" (changed to false), there'll be
-- no need to check these and thus no point in actually marking them! Skip the step = 3 marking sweep
-- and the first slot of every three for marking in the subsequent sweeps.
repeat with step from 5 to ((limit * 2) ^ 0.5 as integer) by 2
-- Like the Phix solution, mark only from half the square of the step size, but adjusted
-- to sync the repeat to the second slot in each group of three for marking.
repeat with j from (step * step div 2 - (step * 2 mod 3) * step + step) to (limit - step) by (step * 3)
set item j of o's lst to marked
set item (j + step) of o's lst to marked
end repeat
end repeat
-- Calculate the primes from the indices of the unmarked slots
-- and store them in the list from the beginning.
set i to 1
set item i of o's lst to i * 2 + 1
repeat with n from 2 to limit by 3
if (item n of o's lst) then
set i to i + 1
set item i of o's lst to n * 2 + 1
if (i = n2) then exit repeat
end if
if (item (n + 1) of o's lst) then
set i to i + 1
set item i of o's lst to n * 2 + 3 -- ((n + 1) * 2) + 1)
if (i = n2) then exit repeat
end if
end repeat
-- set beginning of o's lst to 2 -- Uncomment if required.
return items n1 thru n2 of o's lst
end sieveOfSundaram
-- Task code:
on join(lst, delim)
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to delim
set txt to lst as text
set AppleScript's text item delimiters to astid
return txt
end join
on task()
--set r1 to sieveOfSundaram({1, 100})
--set r2 to sieveOfSundaram(1000000)
set r to sieveOfSundaram({1, 1000000})
set r1 to items 1 thru 100 of r
set r2 to item 1000000 of r
set output to {"1st to 100th Sundaram primes:"}
repeat with i from 1 to 100 by 10
set end of output to join(items i thru (i + 9) of r1, " ")
end repeat
set end of output to "1,000,000th: "
set end of output to r2
return join(output, linefeed)
end task
task() |
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #C | C |
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void) {
int nprimes = 1000000;
int nmax = ceil(nprimes*(log(nprimes)+log(log(nprimes))-0.9385));
// should be larger than the last prime wanted; See
// https://www.maa.org/sites/default/files/jaroma03200545640.pdf
int i, j, m, k; int *a;
k = (nmax-2)/2;
a = (int *)calloc(k + 1, sizeof(int));
for(i = 0; i <= k; i++)a[i] = 2*i+1;
for (i = 1; (i+1)*i*2 <= k; i++)
for (j = i; j <= (k-i)/(2*i+1); j++) {
m = i + j + 2*i*j;
if(a[m]) a[m] = 0;
}
for (i = 1, j = 0; i <= k; i++)
if (a[i]) {
if(j%10 == 0 && j <= 100)printf("\n");
j++;
if(j <= 100)printf("%3d ", a[i]);
else if(j == nprimes){
printf("\n%d th prime is %d\n",j,a[i]);
break;
}
}
}
|
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #C.23 | C# | using System;
using System.Collections.Generic;
using System.Linq;
using static System.Console;
class Program
{
static string fmt(int[] a)
{
var sb = new System.Text.StringBuilder();
for (int i = 0; i < a.Length; i++)
sb.Append(string.Format("{0,5}{1}",
a[i], i % 10 == 9 ? "\n" : " "));
return sb.ToString();
}
static void Main(string[] args)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
var pr = PG.Sundaram(15_500_000).Take(1_000_000).ToArray();
sw.Stop();
Write("The first 100 odd prime numbers:\n{0}\n",
fmt(pr.Take(100).ToArray()));
Write("The millionth odd prime number: {0}", pr.Last());
Write("\n{0} ms", sw.Elapsed.TotalMilliseconds);
}
}
class PG
{
public static IEnumerable<int> Sundaram(int n)
{
// yield return 2;
int i = 1, k = (n + 1) >> 1, t = 1, v = 1, d = 1, s = 1;
var comps = new bool[k + 1];
for (; t < k; t = ((++i + (s += d += 2)) << 1) - d - 2)
while ((t += d + 2) < k)
comps[t] = true;
for (; v < k; v++)
if (!comps[v])
yield return (v << 1) + 1;
}
} |
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #F.23 | F# |
// The sieve of Sundaram. Nigel Galloway: August 7th., 2021
let sPrimes()=
let sSieve=System.Collections.Generic.Dictionary<int,(unit -> int) list>()
let rec fN g=match g with h::t->(let n=h() in if sSieve.ContainsKey n then sSieve.[n]<-h::sSieve.[n] else sSieve.Add(n,[h])); fN t|_->()
let fI n=if sSieve.ContainsKey n then fN sSieve.[n]; sSieve.Remove n|>ignore; None else Some(2*n+1)
let fG n g=let mutable n=n in (fun()->n<-n+g; n)
let fE n g=if not(sSieve.ContainsKey n) then sSieve.Add(n,[fG n g]) else sSieve.[n]<-(fG n g)::sSieve.[g]
let fL =let mutable n,g=4,3 in (fun()->n<-n+3; g<-g+2; fE (n+g) g; n)
sSieve.Add(4,[fL]); Seq.initInfinite((+)1)|>Seq.choose fI
sPrimes()|>Seq.take 100|>Seq.iter(printf "%d "); printfn ""
printfn "The millionth Sundaram prime is %d" (Seq.item 999999 (sPrimes()))
|
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #Fortran | Fortran |
PROGRAM SUNDARAM
IMPLICIT NONE
!
! Local variables
!
INTEGER(8) :: curr_index
INTEGER(8) :: i
INTEGER(8) :: j
INTEGER :: lim
INTEGER(8) :: mid
INTEGER :: primcount
LOGICAL*1 , ALLOCATABLE , DIMENSION(:) :: primes !Array of booleans representing integers
lim = 10000000 ! Not the number of primes but the storage where the prime marker is held for the millionth prime
ALLOCATE(primes(lim))
primes(1:lim) = .TRUE.
!Set all to .True., we will later block out the known non-primes
mid = lim/2
!Generate primes
DO j = 1 , mid
DO i = 1 , j
curr_index = i + j + (2*i*j)
IF( curr_index>lim )EXIT ! Too big already, leave the loop.
primes(curr_index) = .FALSE. !This candidate will not produce a prime
END DO
END DO
!
i = 0
j = 0
WRITE(6 , *)'The first 100 primes:'
DO WHILE ( i < 100 )
j = j + 1
IF( primes(j) )THEN
WRITE(6 , 34 , ADVANCE = 'no')j*2 + 1 !Take the candidate, multiply by 2, add 1, and you have a prime
34 FORMAT(I0 , 1x)
i = i + 1 ! Counter used for printing
IF( MOD(i,10)==0 )WRITE(6 , *)' '
END IF
END DO
! Now print the millionth prime
primcount = 0
DO i = 1 , lim
IF( primes(i) )THEN
primcount = primcount + 1
IF( primcount==1000000 )THEN
WRITE(6 , 35)'1 millionth Prime Found: ' , (i*2) + 1
35 FORMAT(/ , a , i0)
EXIT
END IF
END IF
END DO
DEALLOCATE(primes)
STOP
END PROGRAM SUNDARAM
|
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #Go | Go | package main
import (
"fmt"
"math"
"rcu"
"time"
)
func sos(n int) []int {
if n < 3 {
return []int{}
}
var primes []int
k := (n-3)/2 + 1
marked := make([]bool, k) // all false by default
limit := (int(math.Sqrt(float64(n)))-3)/2 + 1
for i := 0; i < limit; i++ {
p := 2*i + 3
s := (p*p - 3) / 2
for j := s; j < k; j += p {
marked[j] = true
}
}
for i := 0; i < k; i++ {
if !marked[i] {
primes = append(primes, 2*i+3)
}
}
return primes
}
// odds only
func soe(n int) []int {
if n < 3 {
return []int{}
}
var primes []int
k := (n-3)/2 + 1
marked := make([]bool, k) // all false by default
limit := (int(math.Sqrt(float64(n)))-3)/2 + 1
for i := 0; i < limit; i++ {
if !marked[i] {
p := 2*i + 3
s := (p*p - 3) / 2
for j := s; j < k; j += p {
marked[j] = true
}
}
}
for i := 0; i < k; i++ {
if !marked[i] {
primes = append(primes, 2*i+3)
}
}
return primes
}
func main() {
const limit = int(16e6) // say
start := time.Now()
primes := sos(limit)
elapsed := int(time.Since(start).Milliseconds())
climit := rcu.Commatize(limit)
celapsed := rcu.Commatize(elapsed)
million := rcu.Commatize(1e6)
millionth := rcu.Commatize(primes[1e6-1])
fmt.Printf("Using the Sieve of Sundaram generated primes up to %s in %s ms.\n\n", climit, celapsed)
fmt.Println("First 100 odd primes generated by the Sieve of Sundaram:")
for i, p := range primes[0:100] {
fmt.Printf("%3d ", p)
if (i+1)%10 == 0 {
fmt.Println()
}
}
fmt.Printf("\nThe %s Sundaram prime is %s\n", million, millionth)
start = time.Now()
primes = soe(limit)
elapsed = int(time.Since(start).Milliseconds())
celapsed = rcu.Commatize(elapsed)
millionth = rcu.Commatize(primes[1e6-1])
fmt.Printf("\nUsing the Sieve of Eratosthenes would have generated them in %s ms.\n", celapsed)
fmt.Printf("\nAs a check, the %s Sundaram prime would again have been %s\n", million, millionth)
} |
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #Haskell | Haskell | import Data.List (intercalate, transpose)
import Data.List.Split (chunksOf)
import qualified Data.Set as S
import Text.Printf (printf)
--------------------- SUNDARAM PRIMES --------------------
sundaram :: Integral a => a -> [a]
sundaram n =
[ succ (2 * x)
| x <- [1 .. m],
x `S.notMember` excluded
]
where
m = div (pred n) 2
excluded =
S.fromList
[ 2 * i * j + i + j
| let fm = fromIntegral m,
i <- [1 .. floor (sqrt (fm / 2))],
let fi = fromIntegral i,
j <- [i .. floor ((fm - fi) / succ (2 * fi))]
]
nSundaramPrimes ::
(Integral a1, RealFrac a2, Floating a2) => a2 -> [a1]
nSundaramPrimes n =
sundaram $ floor $ (2.4 * n * log n) / 2
--------------------------- TEST -------------------------
main :: IO ()
main = do
putStrLn "First 100 Sundaram primes (starting at 3):\n"
(putStrLn . table " " . chunksOf 10) $
show <$> nSundaramPrimes 100
table :: String -> [[String]] -> String
table gap rows =
let ws = maximum . fmap length <$> transpose rows
pw = printf . flip intercalate ["%", "s"] . show
in unlines $ intercalate gap . zipWith pw ws <$> rows |
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #JavaScript | JavaScript | (() => {
"use strict";
// ----------------- SUNDARAM PRIMES -----------------
// sundaramsUpTo :: Int -> [Int]
const sundaramsUpTo = n => {
const
m = Math.floor(n - 1) / 2,
excluded = new Set(
enumFromTo(1)(
Math.floor(Math.sqrt(m / 2))
)
.flatMap(
i => enumFromTo(i)(
Math.floor((m - i) / (1 + (2 * i)))
)
.flatMap(
j => [(2 * i * j) + i + j]
)
)
);
return enumFromTo(1)(m).flatMap(
x => excluded.has(x) ? (
[]
) : [1 + (2 * x)]
);
};
// nSundaramsPrimes :: Int -> [Int]
const nSundaramPrimes = n =>
sundaramsUpTo(
// Probable limit
Math.floor((2.4 * n * Math.log(n)) / 2)
)
.slice(0, n);
// ---------------------- TEST -----------------------
const main = () => [
"First 100 Sundaram primes",
"(starting at 3):\n",
table(10)(" ")(
nSundaramPrimes(100)
.map(n => `${n}`)
)
].join("\n");
// --------------------- GENERIC ---------------------
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = m =>
n => Array.from({
length: 1 + n - m
}, (_, i) => m + i);
// --------------------- DISPLAY ---------------------
// chunksOf :: Int -> [a] -> [[a]]
const chunksOf = n => {
// xs split into sublists of length n.
// The last sublist will be short if n
// does not evenly divide the length of xs.
const go = xs => {
const chunk = xs.slice(0, n);
return 0 < chunk.length ? (
[chunk].concat(
go(xs.slice(n))
)
) : [];
};
return go;
};
// justifyRight :: Int -> Char -> String -> String
const justifyRight = n =>
// The string s, preceded by enough padding (with
// the character c) to reach the string length n.
c => s => Boolean(s) ? (
s.padStart(n, c)
) : "";
// table :: Int -> String -> [String] -> String
const table = nCols =>
// A tabulation of a list of values into a given
// number of columns, using a specified gap
// between those columns.
gap => xs => {
const w = xs[xs.length - 1].length;
return chunksOf(nCols)(xs)
.map(
row => row.map(
justifyRight(w)(" ")
).join(gap)
)
.join("\n");
};
return main();
})(); |
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #jq | jq | # `sieve_of_Sundaram` as defined here generates the stream of
# consecutive primes from 3 on but less than or equal to the specified
# limit specified by `.`.
# input: an integer, n
# output: stream of consecutive primes from 3 but less than or equal to n
def sieve_of_Sundaram:
def idiv($b): (. - (. % $b))/$b ;
debug |
round as $n
| if $n < 2 then empty
else
((($n-3) | idiv(2)) + 1) as $k
| [range(0; $k + 1) | 1 ] # integers_list
| reduce range (0; (($n|sqrt) - 3) / 2 + 1) as $i (.;
(2*$i + 3) as $p
| ((($p*$p - 3) | idiv(2))) as $s
| reduce range($s; $k; $p) as $j (.;
if .[$j] then .[$j] = false else . end ) )
| range(0; $k) as $i
| if .[$i] then ($i+1)*2+1 else empty end
end ;
# Emit an array of $n Sundaram primes.
# The first Sundaram prime is 3 so we ensure Sundaram_prime(1) is [3].
# An adaptive definition to ensure generality without being excessively conservative.
def Sundaram_primes($n):
def sieve:
. as $in
| [limit($n; sieve_of_Sundaram)]
| if length == $n then .
else ($n + $in) as $m
| ("... nth_Sundaram_prime(\($n)): \($in) => \($m))" | debug) as $debug
| $m | sieve
end;
if $n < 1 then empty
elif $n <= 100 then ($n | 1.2 * . * log) | sieve
else $n | (1.15 * . * log) | sieve # OK
end; |
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #Julia | Julia |
"""
The sieve of Sundaram is a simple deterministic algorithm for finding all the
prime numbers up to a specified integer. This function is modified from the
Python example Wikipedia entry wiki/Sieve_of_Sundaram, to give primes to the
nth prime rather than the Wikipedia function that gives primes less than n.
"""
function sieve_of_Sundaram(nth, print_all=true)
@assert nth > 0
k = Int(round(1.2 * nth * log(nth))) # nth prime is at about n * log(n)
integers_list = trues(k)
for i in 1:k
j = i
while i + j + 2 * i * j < k
integers_list[i + j + 2 * i * j + 1] = false
j += 1
end
end
pcount = 0
for i in 1:k + 1
if integers_list[i + 1]
pcount += 1
if print_all
print(lpad(2 * i + 1, 4), pcount % 10 == 0 ? "\n" : "")
end
if pcount == nth
println("\nSundaram primes start with 3. The $(nth)th Sundaram prime is $(2 * i + 1).")
break
end
end
end
end
sieve_of_Sundaram(100)
@time sieve_of_Sundaram(1000000, false)
println("\nChecking:")
using Primes; @show count(primesmask(15485867))
@time count(primesmask(15485867))
|
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | ClearAll[SieveOfSundaram]
SieveOfSundaram[n_Integer] := Module[{i, prefac, k, ints},
k = Floor[(n - 2)/2];
ints = ConstantArray[True, k + 1];
Do[
prefac = 2 i + 1;
If[i + i prefac <= k,
ints[[i + i prefac ;; ;; prefac]] = False
];
,
{i, 1, k + 1}
];
2 Flatten[Position[ints, True]] + 1
]
SieveOfSundaram[600][[;; 100]]
SieveOfSundaram[16000000][[10^6]] |
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #Nim | Nim | import strutils
const N = 8_000_000
type Mark {.pure.} = enum None, Mark1, Mark2
var mark: array[1..N, Mark]
for n in countup(4, N, 3): mark[n] = Mark1
var count = 0 # Count of primes.
var list100: seq[int] # First 100 primes.
var last = 0 # Millionth prime.
var step = 5 # Current step for marking.
for n in 1..N:
case mark[n]
of None:
# Add/count a new odd prime.
inc count
if count <= 100:
list100.add 2 * n + 1
elif count == 1_000_000:
last = 2 * n + 1
break
of Mark1:
# Mark new numbers using current step.
if n > 4:
for k in countup(n + step, N, step):
if mark[k] == None: mark[k] = Mark2
inc step, 2
of Mark2:
# Ignore this number.
discard
echo "First 100 Sundaram primes:"
for i, n in list100:
stdout.write ($n).align(3), if (i + 1) mod 10 == 0: '\n' else: ' '
echo()
if last == 0:
quit "Not enough values in sieve. Found only $#.".format(count), QuitFailure
echo "The millionth Sundaram prime is ", ($last).insertSep() |
http://rosettacode.org/wiki/The_sieve_of_Sundaram | The sieve of Sundaram | The sieve of Eratosthenes: you've been there; done that; have the T-shirt. The sieve of Eratosthenes was ancient history when Euclid was a schoolboy. You are ready for something less than 3000 years old. You are ready for The sieve of Sundaram.
Starting with the ordered set of +ve integers, mark every third starting at 4 (4;7;10...).
Step through the set and if the value is not marked output 2*n+1. So from 1 to 4 output 3 5 7.
4 is marked so skip for 5 and 6 output 11 and 13.
7 is marked, so no output but now also mark every fifth starting at 12 (12;17;22...)
as per to 10 and now mark every seventh starting at 17 (17;24;31....)
as per for every further third element (13;16;19...) mark every (9th;11th;13th;...) element.
The output will be the ordered set of odd primes.
Using your function find and output the first 100 and the millionth Sundaram prime.
The faithless amongst you may compare the results with those generated by The sieve of Eratosthenes.
References
The article on Wikipedia.
| #Perl | Perl | use strict;
use warnings;
use feature 'say';
my @sieve;
my $nth = 1_000_000;
my $k = 2.4 * $nth * log($nth) / 2;
$sieve[$k] = 0;
for my $i (1 .. $k) {
my $j = $i;
while ((my $l = $i + $j + 2 * $i * $j) < $k) {
$sieve[$l] = 1;
$j++
}
}
$sieve[0] = 1;
my @S = (grep { $_ } map { ! $sieve[$_] and 1+$_*2 } 0..@sieve)[0..99];
say "First 100 Sundaram primes:\n" .
(sprintf "@{['%5d' x 100]}", @S) =~ s/(.{50})/$1\n/gr;
my ($count, $index);
for (@sieve) {
$count += !$_;
(say "One millionth: " . (1+2*$index)) and last if $count == $nth;
++$index;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.