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
| #Erlang | Erlang | -module(tok).
-export([start/0]).
start() ->
Lst = string:tokens("Hello,How,Are,You,Today",","),
io:fwrite("~s~n", [string:join(Lst,".")]),
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
| #Euphoria | Euphoria | function split(sequence s, integer c)
sequence out
integer first, delim
out = {}
first = 1
while first<=length(s) do
delim = find_from(c,s,first)
if delim = 0 then
delim = length(s)+1
end if
out = append(out,s[first..delim-1])
first = delim + 1
end while
return out
end function
sequence s
s = split("Hello,How,Are,You,Today", ',')
for i = 1 to length(s) do
puts(1, s[i] & ',')
end for |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Go | Go | package empty
func Empty() {}
func Count() {
// count to a million
for i := 0; i < 1e6; i++ {
}
} |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Groovy | Groovy | import java.lang.management.ManagementFactory
import java.lang.management.ThreadMXBean
def threadMX = ManagementFactory.threadMXBean
assert threadMX.currentThreadCpuTimeSupported
threadMX.threadCpuTimeEnabled = true
def clockCpuTime = { Closure c ->
def start = threadMX.currentThreadCpuTime
c.call()
(threadMX.currentThreadCpuTime - start)/1000000
} |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
Find the top N salaries in each department, where N is provided as a parameter.
Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:
Employee Name,Employee ID,Salary,Department
Tyler Bennett,E10297,32000,D101
John Rappl,E21437,47000,D050
George Woltman,E00127,53500,D101
Adam Smith,E63535,18000,D202
Claire Buckman,E39876,27800,D202
David McClellan,E04242,41500,D101
Rich Holcomb,E01234,49500,D202
Nathan Adams,E41298,21900,D050
Richard Potter,E43128,15900,D101
David Motsinger,E27002,19250,D202
Tim Sampair,E03033,27000,D101
Kim Arlich,E10001,57000,D190
Timothy Grove,E16398,29900,D190
| #FreeBASIC | FreeBASIC | #define N 3 'show the top three employees of each rank
'here is all the data to be read in
data "Tyler Bennett","E10297",32000,"D101"
data "John Rappl","E21437",47000,"D050"
data "George Woltman","E00127",53500,"D101"
data "Adam Smith","E63535",18000,"D202"
data "Claire Buckman","E39876",27800,"D202"
data "David McClellan","E04242",41500,"D101"
data "Rich Holcomb","E01234",49500,"D202"
data "Nathan Adams","E41298",21900,"D050"
data "Richard Potter","E43128",15900,"D101"
data "David Motsinger","E27002",19250,"D202"
data "Tim Sampair","E03033",27000,"D101"
data "Kim Arlich","E10001",57000,"D190"
data "Timothy Grove","E16398",29900,"D190"
type employee
'define a data type for employees
nm as string*32 'name
en as string*6 'employee number
sl as uinteger 'salary
dp as string*4 'department
fl as boolean 'a flag
end type
dim as employee emp(1 to 13)
dim as uinteger e, d, x, ce, cs
dim as string*4 dept(1 to 4) = {"D050", "D101", "D190", "D202"}
for e = 1 to 13
'put all the employee data into an array
read emp(e).nm
read emp(e).en
read emp(e).sl
read emp(e).dp
emp(e).fl = false
next e
for d = 1 to 4 'look at each department
print "Department ";dept(d);":"
for x = 1 to N 'top N employees
cs = 0
ce = 0
for e = 1 to 13 'look through employees
if emp(e).dp = dept(d) andalso emp(e).fl = false andalso emp(e).sl > cs then
emp(ce).fl = false 'unflag the previous champion so they can be found on the next pass
ce = e
cs = emp(e).sl
emp(e).fl = true 'flag this employee so that on the next pass we can get the next richest
endif
next e
if ce>0 then print emp(ce).nm;" ";emp(ce).en;" ";emp(ce).sl;" ";emp(ce).dp
next x
print
next d |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #ERRE | ERRE | !--------------------------------------------
! TRIS.R : gioca a tris contro l'operatore
!--------------------------------------------
PROGRAM TRIS
DIM TRIS%[9],T1%[9],PIECES$[3]
!$SEGMENT=$B800
!$INCLUDE="PC.LIB"
PROCEDURE DELAY(COUNT%)
FOR Z%=1 TO COUNT DO
END FOR
END PROCEDURE
PROCEDURE SET_BOARD
!
! Disegna lo schema del gioco
!
CLS
BLOAD("TRIS.BLD",0)
!$KEY
END PROCEDURE
PROCEDURE PUT_PIECES
!
! Pone i pezzi sulla scacchiera
!
Z%=0
FOR ROW%=6 TO 12 STEP 3 DO ! posizioni assolute sullo schermo
FOR COL%=32 TO 48 STEP 8 DO
LOCATE(ROW%+1,COL%+1)
Z%=Z%+1
PRINT(PIECES$[TRIS%[Z%]])
END FOR
END FOR
END PROCEDURE
PROCEDURE COMPUTE_MOVE(A%)
CASE A% OF
2-> C1%=C1%+1 END ->
4-> C2%=C2%+1 END ->
8-> S1%=TRUE S2%=TRUE END ->
3-> N1%=N1%+1 END ->
9-> N2%=N2%+1 END ->
27-> S1%=FALSE S2%=FALSE END ->
END CASE
END PROCEDURE
PROCEDURE PREPAREMOVE(T1%[],I%->M%)
!
! Prepara la mossa del calcolatore
!
T1%[I%]=2
C1%=0
C2%=0
N1%=0
N2%=0
FOR K%=0 TO 2 DO
COMPUTE_MOVE(T1%[3*K%+1]*T1%[3*K%+2]*T1%[3*K%+3])
COMPUTE_MOVE(T1%[K%+1]*T1%[K%+4]*T1%[K%+7])
END FOR
COMPUTE_MOVE(T1%[1]*T1%[5]*T1%[9])
COMPUTE_MOVE(T1%[3]*T1%[5]*T1%[7])
M%=-63*N2%+31*C2%-15*N1%+7*C1%
END PROCEDURE
PROCEDURE COMPUTER_MOVE
!
! Coordina le mosse del calcolatore
!
MAXSCORE%=-1000
FOR I%=1 TO 9 DO
IF TRIS%[I%]=1
THEN
PREPAREMOVE(TRIS%[],I%->MV%)
EXIT IF S2% AND NOT S1%
IF S1% AND S2%
THEN
TRIS%[I%]=2
DIARY$=DIARY$+"c"+MID$(STR$(I%),2)+"*"
PUT_PIECES
EXIT
END IF
IF MV%=0
THEN
MOVE%=I%
EXIT
END IF
IF MV%>MAXSCORE%
THEN
MOVE%=I%
MAXSCORE%=MV%
END IF
END IF
END FOR
IF NOT S2%
THEN
TRIS%[MOVE%]=2
DIARY$=DIARY$+"c"+MID$(STR$(MOVE%),2)+";"
PUT_PIECES
NMOVE%=NMOVE%-1
S1%=(NMOVE%=0)
END IF
END PROCEDURE
PROCEDURE PLAYER_MOVE
!
! Gioca l'avversario umano usando i tasti cursore per lo spostamento
!
LOCATE(19,13)
PRINT("Tocca a te .... ")
REPEAT
ROW%=7
COL%=32
LOCATE(ROW%+1,COL%+1)
PRINT("Ü")
REPEAT
GET(B$)
IF LEN(B$)=2 THEN
CASE ASC(RIGHT$(B$,1)+CHR$(0)) OF
77-> ! codice tastiera per CRSR =>
LOCATE(ROW%+1,COL%+1)
PRINT(" ")
COL%=-(COL%+8)*(COL%<=40)-32*(COL%>40)
LOCATE(ROW%+1,COL%+1)
PRINT("Ü")
END ->
75-> ! codice tastiera per CRSR <=
LOCATE(ROW%+1,COL%+1)
PRINT(" ")
COL%=-(COL%-8)*(COL%>=40)-48*(COL%<40)
LOCATE(ROW%+1,COL%+1)
PRINT("Ü")
END ->
80-> ! codice tastiera per CRSR DOWN
LOCATE(ROW%+1,COL%+1)
PRINT(" ")
ROW%=-(ROW%+3)*(ROW%<=10)-7*(ROW%>10)
LOCATE(ROW%+1,COL%+1)
PRINT("Ü")
END ->
72-> ! codice tastiera per CRSR UP
LOCATE(ROW%+1,COL%+1)
PRINT(" ")
ROW%=-(ROW%-3)*(ROW%>=10)-13*(ROW%<10)
LOCATE(ROW%+1,COL%+1)
PRINT("Ü")
END ->
END CASE
END IF
UNTIL B$=CHR$(13)
MM%=ROW%+COL%/8-10 ! da coordinate schermo a coordinate scacchiera
UNTIL TRIS%[MM%]=1
TRIS%[MM%]=3
LOCATE(ROW%+1,COL%+1)
PRINT(" ")
DIARY$=DIARY$+"p"+MID$(STR$(MM%),2)+";"
PUT_PIECES
NMOVE%=NMOVE%-1
S1%=(NMOVE%=0)
LOCATE(19,13)
PRINT(STRING$(45," "))
END PROCEDURE
BEGIN
DATA(" ","+","o")
SET_BOARD
REPEAT
S1%=FALSE S2%=FALSE ! determinano lo stato della partita
NMOVE%=9
FOR Z%=1 TO 3 DO
READ(PIECES$[Z%])
END FOR
FOR Z%=1 TO 9 DO
TRIS%[Z%]=1
END FOR
LOCATE(19,13)
PRINT("Giochi per primo ?")
REPEAT
GET(A$)
UNTIL A$="S" OR A$="s" OR A$="N" OR A$="n"
PUT_PIECES
FOR INDICE%=1 TO 9 DO
IF A$="s" OR A$="S"
THEN
PLAYER_MOVE
EXIT IF S1% OR S2%
COMPUTER_MOVE
EXIT IF S1% OR S2%
ELSE
COMPUTER_MOVE
EXIT IF S1% OR S2%
PLAYER_MOVE
EXIT IF S1% OR S2%
END IF
END FOR
LOCATE(19,13)
CASE TRUE OF
(S1% AND NOT S2%)->
PRINT("E' finita pari !!! ")
END ->
(S2% AND NOT S1%)->
PRINT("HAI VINTO !!! ")
END ->
(S1% AND S2%)->
PRINT("HO VINTO IO !!! ")
END ->
END CASE
DELAY(500)
LOCATE(19,13)
PRINT(DIARY$)
DELAY(500)
LOCATE(19,13)
PRINT("Vuoi giocare ancora ? ")
REPEAT
GET(A$)
UNTIL A$="S" OR A$="s" OR A$="N" OR A$="n"
UNTIL A$="N" OR A$="n"
END PROGRAM
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Clojure | Clojure | (defn towers-of-hanoi [n from to via]
(when (pos? n)
(towers-of-hanoi (dec n) from via to)
(printf "Move from %s to %s\n" from to)
(recur (dec n) via to from))) |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #PicoLisp | PicoLisp | (let R 0
(prinl R)
(for (X 1 (>= 32 X))
(setq R
(bin
(pack
(bin R)
(bin (x| (dec (** 2 X)) R)) ) ) )
(prinl (pack 0 (bin R)))
(inc 'X X) ) ) |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #PowerShell | PowerShell | function New-ThueMorse ( $Digits )
{
# Start with seed 0
$ThueMorse = "0"
# Decrement digits remaining
$Digits--
# While we still have digits to calculate...
While ( $Digits -gt 0 )
{
# Number of digits we'll get this loop (what we still need up to the maximum available), corrected to 0 base
$LastDigit = [math]::Min( $ThueMorse.Length, $Digits ) - 1
# Loop through each digit
ForEach ( $i in 0..$LastDigit )
{
# Append the twos complement
$ThueMorse += ( 1 - $ThueMorse.Substring( $i, 1 ) )
}
# Calculate the number of digits still remaining
$Digits = $Digits - $LastDigit - 1
}
return $ThueMorse
}
New-ThueMorse 5
New-ThueMorse 16
New-ThueMorse 73 |
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were separated by the separators, become the elements of the output list.
Empty fields should be preserved, even at the start and end.
Rules for escaping:
"Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.
When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special).
Each occurrence of the escape character that was used to escape something, should not become part of the output.
Test case
Demonstrate that your function satisfies the following test-case:
Input
Output
string:
one^|uno||three^^^^|four^^^|^cuatro|
separator character:
|
escape character:
^
one|uno
three^^
four^|cuatro
(Print the output list in any format you like, as long as it is it easy to see what the fields are.)
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
| #Raku | Raku | sub tokenize ($string, :$sep!, :$esc!) {
return $string.match(/([ <!before $sep | $esc> . | $esc . ]*)+ % $sep/)\
.[0].map(*.subst: /$esc )> ./, '', :g);
}
say "'$_'" for tokenize 'one^|uno||three^^^^|four^^^|^cuatro|', sep => '|', esc => '^'; |
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were separated by the separators, become the elements of the output list.
Empty fields should be preserved, even at the start and end.
Rules for escaping:
"Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.
When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special).
Each occurrence of the escape character that was used to escape something, should not become part of the output.
Test case
Demonstrate that your function satisfies the following test-case:
Input
Output
string:
one^|uno||three^^^^|four^^^|^cuatro|
separator character:
|
escape character:
^
one|uno
three^^
four^|cuatro
(Print the output list in any format you like, as long as it is it easy to see what the fields are.)
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
| #REXX | REXX | /*REXX program demonstrates tokenizing and displaying a string with escaping sequences. */
str = 'one^|uno||three^^^^|four^^^|^cuatro|' /*the character string to be tokenized.*/
esc = '^' /* " escape character to be used. */
sep = '|' /* " separator " " " " */
out = /* " output string (so far). */
eMode = 0 /*a flag, escape is in progress. */
do j=1 for length(str); _=substr(str, j, 1) /*parse a single character at a time. */
if eMode then do; out=out || _; eMode=0; iterate; end /*are we in escape mode? */
if _==esc then do; eMode=1; iterate; end /*is it an escape char ? */
if _==sep then do; call show; iterate; end /* " " a separator char?*/
out=out || _ /*append the character. */
end /*j*/
if out\=='' | _==sep then call show /*handle a residual str or a separator.*/
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: say '[length'right(length(out),4)"]" out; out=; return |
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.
A tool exists that extracts library dependencies.
Task
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
Assume library names are single words.
Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be flagged.
Use the following data as an example:
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01.
C.f.
Topological sort/Extracted top item.
There are two popular algorithms for topological sorting:
Kahn's 1962 topological sort [1]
depth-first search [2] [3]
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | TopologicalSort[
Graph[Flatten[# /. {l_, ld_} :>
Map[# -> l &,
DeleteCases[ld, l]]]]] /. {_TopologicalSort -> $Failed} &@
{{"des_system_lib", {"std", "synopsys", "std_cell_lib",
"des_system_lib", "dw02", "dw01", "ramlib", "ieee"}},
{"dw01", {"ieee", "dw01", "dware", "gtech"}},
{"dw02", {"ieee", "dw02", "dware"}},
{"dw03", {"std", "synopsys", "dware", "dw03", "dw02", "dw01",
"ieee", "gtech"}},
{"dw04", {"dw04", "ieee", "dw01", "dware", "gtech"}},
{"dw05", {"dw05", "ieee", "dware"}},
{"dw06", {"dw06", "ieee", "dware"}},
{"dw07", {"ieee", "dware"}},
{"dware", {"ieee", "dware"}},
{"gtech", {"ieee", "gtech"}},
{"ramlib", {"std", "ieee"}},
{"std_cell_lib", {"ieee", "std_cell_lib"}},
{"synopsys", {}}} |
http://rosettacode.org/wiki/Universal_Turing_machine | Universal Turing machine | One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936–1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.
Task
Simulate such a machine capable
of taking the definition of any other Turing machine and executing it.
Of course, you will not have an infinite tape,
but you should emulate this as much as is possible.
The three permissible actions on the tape are "left", "right" and "stay".
To test your universal Turing machine (and prove your programming language
is Turing complete!), you should execute the following two Turing machines
based on the following definitions.
Simple incrementer
States: q0, qf
Initial state: q0
Terminating states: qf
Permissible symbols: B, 1
Blank symbol: B
Rules:
(q0, 1, 1, right, q0)
(q0, B, 1, stay, qf)
The input for this machine should be a tape of 1 1 1
Three-state busy beaver
States: a, b, c, halt
Initial state: a
Terminating states: halt
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(a, 0, 1, right, b)
(a, 1, 1, left, c)
(b, 0, 1, left, a)
(b, 1, 1, right, b)
(c, 0, 1, left, b)
(c, 1, 1, stay, halt)
The input for this machine should be an empty tape.
Bonus:
5-state, 2-symbol probable Busy Beaver machine from Wikipedia
States: A, B, C, D, E, H
Initial state: A
Terminating states: H
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(A, 0, 1, right, B)
(A, 1, 1, left, C)
(B, 0, 1, right, C)
(B, 1, 1, right, B)
(C, 0, 1, right, D)
(C, 1, 0, left, E)
(D, 0, 1, left, A)
(D, 1, 1, left, D)
(E, 0, 1, stay, H)
(E, 1, 0, left, A)
The input for this machine should be an empty tape.
This machine runs for more than 47 millions steps.
| #Raku | Raku | sub run_utm(:$state! is copy, :$blank!, :@rules!, :@tape = [$blank], :$halt, :$pos is copy = 0) {
$pos += @tape if $pos < 0;
die "Bad initial position" unless $pos ~~ ^@tape;
STEP: loop {
print "$state\t";
for ^@tape {
my $v = @tape[$_];
print $_ == $pos ?? "[$v]" !! " $v ";
}
print "\n";
last if $state eq $halt;
for @rules -> @rule {
my ($s0, $v0, $v1, $dir, $s1) = @rule;
next unless $s0 eq $state and @tape[$pos] eq $v0;
@tape[$pos] = $v1;
given $dir {
when 'left' {
if $pos == 0 { unshift @tape, $blank }
else { $pos-- }
}
when 'right' {
push @tape, $blank if ++$pos >= @tape;
}
}
$state = $s1;
next STEP;
}
die 'No matching rules';
}
}
say "incr machine";
run_utm :halt<qf>,
:state<q0>,
:tape[1,1,1],
:blank<B>,
:rules[
[< q0 1 1 right q0 >],
[< q0 B 1 stay qf >]
];
say "\nbusy beaver";
run_utm :halt<halt>,
:state<a>,
:blank<0>,
:rules[
[< a 0 1 right b >],
[< a 1 1 left c >],
[< b 0 1 left a >],
[< b 1 1 right b >],
[< c 0 1 left b >],
[< c 1 1 stay halt >]
];
say "\nsorting test";
run_utm :halt<STOP>,
:state<A>,
:blank<0>,
:tape[< 2 2 2 1 2 2 1 2 1 2 1 2 1 2 >],
:rules[
[< A 1 1 right A >],
[< A 2 3 right B >],
[< A 0 0 left E >],
[< B 1 1 right B >],
[< B 2 2 right B >],
[< B 0 0 left C >],
[< C 1 2 left D >],
[< C 2 2 left C >],
[< C 3 2 left E >],
[< D 1 1 left D >],
[< D 2 2 left D >],
[< D 3 1 right A >],
[< E 1 1 left E >],
[< E 0 0 right STOP >]
];
|
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positive integer n that are relatively prime to n
counts the integers k in the range 1 ≤ k ≤ n for which the greatest common divisor gcd(n,k) is equal to 1
counts numbers ≤ n and prime to n
If the totient number (for N) is one less than N, then N is prime.
Task
Create a totient function and:
Find and display (1 per line) for the 1st 25 integers:
the integer (the index)
the totient number for that integer
indicate if that integer is prime
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000 (optional)
Show all output here.
Related task
Perfect totient numbers
Also see
Wikipedia: Euler's totient function.
MathWorld: totient function.
OEIS: Euler totient function phi(n).
| #Ruby | Ruby |
require "prime"
def 𝜑(n)
n.prime_division.inject(1) {|res, (pr, exp)| res *= (pr-1) * pr**(exp-1) }
end
1.upto 25 do |n|
tot = 𝜑(n)
puts "#{n}\t #{tot}\t #{"prime" if n-tot==1}"
end
[100, 1_000, 10_000, 100_000].each do |u|
puts "Number of primes up to #{u}: #{(1..u).count{|n| n-𝜑(n) == 1} }"
end
|
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #jq | jq |
# degrees to radians
def radians:
(-1|acos) as $pi | (. * $pi / 180);
def task:
(-1|acos) as $pi
| ($pi / 180) as $degrees
| "Using radians:",
" sin(-pi / 6) = \( (-$pi / 6) | sin )",
" cos(3 * pi / 4) = \( (3 * $pi / 4) | cos)",
" tan(pi / 3) = \( ($pi / 3) | tan)",
" asin(-1 / 2) = \((-1 / 2) | asin)",
" acos(-sqrt(2)/2) = \((-(2|sqrt)/2) | acos )",
" atan(sqrt(3)) = \( 3 | sqrt | atan )",
"Using degrees:",
" sin(-30) = \((-30 * $degrees) | sin)",
" cos(135) = \((135 * $degrees) | cos)",
" tan(60) = \(( 60 * $degrees) | tan)",
" asin(-1 / 2) = \( (-1 / 2) | asin / $degrees)",
" acos(-sqrt(2)/2) = \( (-(2|sqrt) / 2) | acos / $degrees)",
" atan(sqrt(3)) = \( (3 | sqrt) | atan / $degrees)"
;
task
|
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.
From the wikipedia entry:
ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
result := call a function to do an operation
if result overflows
alert user
else
print result
The task is to implement the algorithm:
Use the function:
f
(
x
)
=
|
x
|
0.5
+
5
x
3
{\displaystyle f(x)=|x|^{0.5}+5x^{3}}
The overflow condition is an answer of greater than 400.
The 'user alert' should not stop processing of other items of the sequence.
Print a prompt before accepting eleven, textual, numeric inputs.
You may optionally print the item as well as its associated result, but the results must be in reverse order of input.
The sequence S may be 'implied' and so not shown explicitly.
Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
| #Wren | Wren | import "io" for Stdin, Stdout
import "/fmt" for Fmt
var f = Fn.new { |x| x.abs.sqrt + 5*x*x*x }
var s = List.filled(11, 0)
System.print("Please enter 11 numbers:")
var count = 0
while (count < 11) {
Fmt.write(" Number $-2d : ", count + 1)
Stdout.flush()
var number = Num.fromString(Stdin.readLine())
if (!number) {
System.print("Not a valid number, try again.")
} else {
s[count] = number
count = count + 1
}
}
s = s[-1..0]
System.print("\nResults:")
for (item in s) {
var fi = f.call(item)
if (fi <= 400) {
Fmt.print(" f($6.3f) = $7.3f", item, fi)
} else {
Fmt.print(" f($6.3f) = overflow", item)
}
} |
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 739, 73, and 7 formed by removing digits from its right are also prime.
No zeroes are allowed in truncatable primes.
Task
The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied).
Related tasks
Find largest left truncatable prime in a given base
Sieve of Eratosthenes
See also
Truncatable Prime from MathWorld.]
| #Scala | Scala | object TruncatablePrimes {
def main(args: Array[String]): Unit = {
val max = 1000000
println(
s"""|ltPrime: ${ltPrimes.takeWhile(_ <= max).last}
|rtPrime: ${rtPrimes.takeWhile(_ <= max).last}
|""".stripMargin)
}
def ltPrimes: LazyList[Int] = 2 #:: LazyList.from(3, 2).filter(isLeftTruncPrime)
def rtPrimes: LazyList[Int] = 2 #:: LazyList.from(3, 2).filter(isRightTruncPrime)
def isPrime(num: Int): Boolean = (num > 1) && !LazyList.range(3, math.sqrt(num).toInt + 1, 2).exists(num%_ == 0)
def isLeftTruncPrime(num: Int): Boolean = !num.toString.contains('0') && Iterator.unfold(num.toString){str => if(str.nonEmpty) Some((str.toInt, str.tail)) else None}.forall(isPrime)
def isRightTruncPrime(num: Int): Boolean = !num.toString.exists(_.asDigit%2 == 0) && Iterator.unfold(num.toString){str => if(str.nonEmpty) Some((str.toInt, str.init)) else None}.forall(isPrime)
} |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #Forth | Forth | \ binary tree (dictionary)
: node ( l r data -- node ) here >r , , , r> ;
: leaf ( data -- node ) 0 0 rot node ;
: >data ( node -- ) @ ;
: >right ( node -- ) cell+ @ ;
: >left ( node -- ) cell+ cell+ @ ;
: preorder ( xt tree -- )
dup 0= if 2drop exit then
2dup >data swap execute
2dup >left recurse
>right recurse ;
: inorder ( xt tree -- )
dup 0= if 2drop exit then
2dup >left recurse
2dup >data swap execute
>right recurse ;
: postorder ( xt tree -- )
dup 0= if 2drop exit then
2dup >left recurse
2dup >right recurse
>data swap execute ;
: max-depth ( tree -- n )
dup 0= if exit then
dup >left recurse
swap >right recurse max 1+ ;
defer depthaction
: depthorder ( depth tree -- )
dup 0= if 2drop exit then
over 0=
if >data depthaction drop
else over 1- over >left recurse
swap 1- swap >right recurse
then ;
: levelorder ( xt tree -- )
swap is depthaction
dup max-depth 0 ?do
i over depthorder
loop drop ;
7 leaf 0 4 node
5 leaf 2 node
8 leaf 9 leaf 6 node
0 3 node 1 node value tree
cr ' . tree preorder \ 1 2 4 7 5 3 6 8 9
cr ' . tree inorder \ 7 4 2 5 1 8 6 9 3
cr ' . tree postorder \ 7 4 5 2 8 9 6 3 1
cr tree max-depth . \ 4
cr ' . tree levelorder \ 1 2 3 4 5 6 7 8 9 |
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
| #F.23 | F# | System.String.Join(".", "Hello,How,Are,You,Today".Split(',')) |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Halon | Halon | $t = uptime();
sleep(1);
echo uptime() - $t; |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Haskell | Haskell | import System.CPUTime (getCPUTime)
-- We assume the function we are timing is an IO monad computation
timeIt :: (Fractional c) => (a -> IO b) -> a -> IO c
timeIt action arg = do
startTime <- getCPUTime
action arg
finishTime <- getCPUTime
return $ fromIntegral (finishTime - startTime) / 1000000000000
-- Version for use with evaluating regular non-monadic functions
timeIt_ :: (Fractional c) => (a -> b) -> a -> IO c
timeIt_ f = timeIt ((`seq` return ()) . f) |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
Find the top N salaries in each department, where N is provided as a parameter.
Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:
Employee Name,Employee ID,Salary,Department
Tyler Bennett,E10297,32000,D101
John Rappl,E21437,47000,D050
George Woltman,E00127,53500,D101
Adam Smith,E63535,18000,D202
Claire Buckman,E39876,27800,D202
David McClellan,E04242,41500,D101
Rich Holcomb,E01234,49500,D202
Nathan Adams,E41298,21900,D050
Richard Potter,E43128,15900,D101
David Motsinger,E27002,19250,D202
Tim Sampair,E03033,27000,D101
Kim Arlich,E10001,57000,D190
Timothy Grove,E16398,29900,D190
| #FunL | FunL | data Employee( name, id, salary, dept )
employees = [
Employee( 'Tyler Bennett', 'E10297', 32000, 'D101' ),
Employee( 'John Rappl', 'E21437', 47000, 'D050' ),
Employee( 'George Woltman', 'E00127', 53500, 'D101' ),
Employee( 'Adam Smith', 'E63535', 18000, 'D202' ),
Employee( 'Claire Buckman', 'E39876', 27800, 'D202' ),
Employee( 'David McClellan', 'E04242', 41500, 'D101' ),
Employee( 'Rich Holcomb', 'E01234', 49500, 'D202' ),
Employee( 'Nathan Adams', 'E41298', 21900, 'D050' ),
Employee( 'Richard Potter', 'E43128', 15900, 'D101' ),
Employee( 'David Motsinger', 'E27002', 19250, 'D202' ),
Employee( 'Tim Sampair', 'E03033', 27000, 'D101' ),
Employee( 'Kim Arlich', 'E10001', 57000, 'D190' ),
Employee( 'Timothy Grove', 'E16398', 29900, 'D190' )
]
N = 2
for (dept, empl) <- employees.groupBy( e -> e.dept ).>toList().sortWith( (<) )
println( dept )
for e <- empl.sortWith( \a, b -> a.salary > b.salary ).take( N )
printf( " %-16s %6s %7d\n", e.name, e.id, e.salary )
println() |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #Euphoria | Euphoria |
include std/console.e
include std/text.e
include std/search.e
include std/sequence.e
sequence board
sequence players = {"X","O"}
function DisplayBoard()
for i = 1 to 3 do
for j = 1 to 3 do
printf(1,"%s",board[i][j])
if j < 3 then
printf(1,"%s","|")
end if
end for
if i < 3 then
puts(1,"\n-----\n")
else
puts(1,"\n\n")
end if
end for
return 1
end function
function CheckWinner()
sequence temp = board
for a = 1 to 2 do
for i = 1 to 3 do
if equal({"X","X","X"},temp[i]) then
puts(1,"X wins\n\n")
return 1
elsif equal({"O","O","O"},temp[i]) then
puts(1,"O wins\n\n")
return 1
end if
end for
temp = columnize(board)
end for
if equal({"X","X","X"},{board[1][1],board[2][2],board[3][3]}) or
equal({"X","X","X"},{board[1][3],board[2][2],board[3][1]}) then
puts(1,"X wins\n")
return 1
elsif equal({"O","O","O"},{board[1][1],board[2][2],board[3][3]}) or
equal({"O","O","O"},{board[1][3],board[2][2],board[3][1]}) then
puts(1,"O wins\n")
return 1
end if
if moves = 9 then
puts(1,"Draw\n\n")
return 1
end if
return 0
end function
integer turn, row, column, moves
sequence replay
while 1 do
board = repeat(repeat(" ",3),3)
DisplayBoard()
turn = rand(2)
moves = 0
while 1 do
while 1 do
printf(1,"%s's turn\n",players[turn])
row = prompt_number("Enter row: ",{})
column = prompt_number("Enter column: ",{})
if match(board[row][column]," ") then
board[row][column] = players[turn]
moves += 1
exit
else
puts(1,"Space already taken - pick again\n")
end if
end while
DisplayBoard()
if CheckWinner() then
exit
end if
if turn = 1 then
turn = 2
else
turn = 1
end if
end while
replay = lower(prompt_string("Play again (y/n)?\n\n"))
if match(replay,"n") then
exit
end if
end while
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #CLU | CLU | move = proc (n, from, via, to: int)
po: stream := stream$primary_output()
if n > 0 then
move(n-1, from, to, via)
stream$putl(po, "Move disk from pole "
|| int$unparse(from)
|| " to pole "
|| int$unparse(to))
move(n-1, via, from, to)
end
end move
start_up = proc ()
move(4, 1, 2, 3)
end start_up |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #PureBasic | PureBasic | EnableExplicit
Procedure.i count_bits(v.i)
Define c.i
While v
c+v&1
v>>1
Wend
ProcedureReturn c
EndProcedure
If OpenConsole()
Define n.i
For n=0 To 255
Print(Str(count_bits(n)%2))
Next
PrintN(~"\n...fin") : Input()
EndIf |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #Python | Python |
m='0'
print(m)
for i in range(0,6):
m0=m
m=m.replace('0','a')
m=m.replace('1','0')
m=m.replace('a','1')
m=m0+m
print(m)
|
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were separated by the separators, become the elements of the output list.
Empty fields should be preserved, even at the start and end.
Rules for escaping:
"Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.
When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special).
Each occurrence of the escape character that was used to escape something, should not become part of the output.
Test case
Demonstrate that your function satisfies the following test-case:
Input
Output
string:
one^|uno||three^^^^|four^^^|^cuatro|
separator character:
|
escape character:
^
one|uno
three^^
four^|cuatro
(Print the output list in any format you like, as long as it is it easy to see what the fields are.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ring | Ring |
tokenize("one^|uno||three^^^^|four^^^|^cuatro|", "|", "^")
func tokenize(src, sep, esc)
field = 1
escaping = false
see "" + field + " "
for i = 1 to len(src)
char = substr(src, i, 1)
if escaping
see char
escaping = false
else
switch char
on sep
see nl
field = field + 1
see "" + field + " "
on esc
escaping = true
other
see char
off
ok
next
see nl
|
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were separated by the separators, become the elements of the output list.
Empty fields should be preserved, even at the start and end.
Rules for escaping:
"Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.
When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special).
Each occurrence of the escape character that was used to escape something, should not become part of the output.
Test case
Demonstrate that your function satisfies the following test-case:
Input
Output
string:
one^|uno||three^^^^|four^^^|^cuatro|
separator character:
|
escape character:
^
one|uno
three^^
four^|cuatro
(Print the output list in any format you like, as long as it is it easy to see what the fields are.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ruby | Ruby |
def tokenize(string, sep, esc)
sep = Regexp.escape(sep)
esc = Regexp.escape(esc)
string.scan(/\G (?:^ | #{sep}) (?: [^#{sep}#{esc}] | #{esc} .)*/x).collect do |m|
m.gsub(/#{esc}(.)/, '\1').gsub(/^#{sep}/, '')
end
end
p tokenize('one^|uno||three^^^^|four^^^|^cuatro|', '|', '^')
|
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.
A tool exists that extracts library dependencies.
Task
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
Assume library names are single words.
Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be flagged.
Use the following data as an example:
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01.
C.f.
Topological sort/Extracted top item.
There are two popular algorithms for topological sorting:
Kahn's 1962 topological sort [1]
depth-first search [2] [3]
| #Mercury | Mercury |
:- module topological_sort.
:- interface.
:- import_module io.
:- pred main(io::di,io::uo) is det.
:- implementation.
:- import_module string, solutions, list, set, require.
:- pred min_element(set(T),pred(T,T),T).
:- mode min_element(in,pred(in,in) is semidet,out) is nondet.
min_element(_,_,_):-fail.
min_element(S,P,X):-
member(X,S),
filter((pred(Y::in) is semidet :- P(Y,X)),S,LowerThanX),
is_empty(LowerThanX).
:- pred topological_sort(set(T),pred(T,T),list(T),list(T)).
:- mode topological_sort(in,(pred((ground >> ground), (ground >> ground)) is semidet),in,out) is nondet.
:- pred topological_sort(set(T),pred(T,T),list(T)).
:- mode topological_sort(in,(pred((ground >> ground), (ground >> ground)) is semidet),out) is nondet.
topological_sort(S,P,Ac,L) :-
(
is_empty(S) -> L is Ac
; solutions(
pred(X::out) is nondet:-
min_element(S,P,X)
, Solutions
),
(
is_empty(Solutions) -> error("No solution detected.\n")
; delete_list(Solutions,S,Sprime),
append(Solutions,Ac,AcPrime),
topological_sort(Sprime,P,AcPrime,L)
)
).
topological_sort(S,P,L) :- topological_sort(S,P,[],L).
:- pred distribute(list(T)::in,{T,list(T)}::out) is det.
distribute([],_):-error("Error in distribute").
distribute([H|T],Z) :- Z = {H,T}.
:- pred db_compare({string,list(string)}::in,{string,list(string)}::in) is semidet.
db_compare({X1,L1},{X2,_}) :- not(X1=X2),list.member(X2,L1).
main(!IO) :-
Input = [
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee",
"dw01 ieee dw01 dware gtech",
"dw02 ieee dw02 dware",
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech",
"dw04 dw04 ieee dw01 dware gtech",
"dw05 dw05 ieee dware",
"dw06 dw06 ieee dware",
"dw07 ieee dware",
"dware ieee dware",
"gtech ieee gtech",
"ramlib std ieee",
"std_cell_lib ieee std_cell_lib",
"synopsys"],
Words=list.map(string.words,Input),
list.map(distribute,Words,Db),
solutions(pred(X::out) is nondet :- topological_sort(set.from_list(Db),db_compare,X),SortedWordLists),
list.map(
pred({X,Y}::in,Z::out) is det:- X=Z,
list.det_head(SortedWordLists),
CompileOrder),
print(CompileOrder,!IO).
|
http://rosettacode.org/wiki/Universal_Turing_machine | Universal Turing machine | One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936–1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.
Task
Simulate such a machine capable
of taking the definition of any other Turing machine and executing it.
Of course, you will not have an infinite tape,
but you should emulate this as much as is possible.
The three permissible actions on the tape are "left", "right" and "stay".
To test your universal Turing machine (and prove your programming language
is Turing complete!), you should execute the following two Turing machines
based on the following definitions.
Simple incrementer
States: q0, qf
Initial state: q0
Terminating states: qf
Permissible symbols: B, 1
Blank symbol: B
Rules:
(q0, 1, 1, right, q0)
(q0, B, 1, stay, qf)
The input for this machine should be a tape of 1 1 1
Three-state busy beaver
States: a, b, c, halt
Initial state: a
Terminating states: halt
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(a, 0, 1, right, b)
(a, 1, 1, left, c)
(b, 0, 1, left, a)
(b, 1, 1, right, b)
(c, 0, 1, left, b)
(c, 1, 1, stay, halt)
The input for this machine should be an empty tape.
Bonus:
5-state, 2-symbol probable Busy Beaver machine from Wikipedia
States: A, B, C, D, E, H
Initial state: A
Terminating states: H
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(A, 0, 1, right, B)
(A, 1, 1, left, C)
(B, 0, 1, right, C)
(B, 1, 1, right, B)
(C, 0, 1, right, D)
(C, 1, 0, left, E)
(D, 0, 1, left, A)
(D, 1, 1, left, D)
(E, 0, 1, stay, H)
(E, 1, 0, left, A)
The input for this machine should be an empty tape.
This machine runs for more than 47 millions steps.
| #REXX | REXX | /*REXX program executes a Turing machine based on initial state, tape, and rules. */
state = 'q0' /*the initial Turing machine state. */
term = 'qf' /*a state that is used for a halt. */
blank = 'B' /*this character is a "true" blank. */
call Turing_rule 'q0 1 1 right q0' /*define a rule for the Turing machine.*/
call Turing_rule 'q0 B 1 stay qf' /* " " " " " " " */
call Turing_init 1 1 1 /*initialize the tape to some string(s)*/
call TM /*go and invoke the Turning machine. */
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
TM: !=1; bot=1; top=1; @er= '***error***' /*start at the tape location 1. */
say /*might as well display a blank line. */
do cycle=1 until state==term /*process Turing machine instructions.*/
do k=1 for rules /* " " " rules. */
parse var rule.k rState rTape rWrite rMove rNext . /*pick pieces. */
if state\==rState | @.!\==rTape then iterate /*wrong rule ? */
@.!=rWrite /*right rule; write it ───► the tape. */
if rMove== 'left' then !=!-1 /*Are we moving left? Then subtract 1*/
if rMove=='right' then !=!+1 /* " " " right? " add 1*/
bot=min(bot, !); top=max(top, !) /*find the tape bottom and top. */
state=rNext; iterate cycle /*use this for the next state; and */
end /*k*/
say @er 'unknown state:' state; leave /*oops, we have an unknown state error.*/
end /*cycle*/
$= /*start with empty string (the tape). */
do t=bot to top; [email protected]
if _==blank then _=' ' /*do we need to translate a true blank?*/
$=$ || pad || _ /*construct char by char, maybe pad it.*/
end /*t*/ /* [↑] construct the tape's contents*/
L=length($) /*obtain length of " " " */
if L==0 then $= "[tape is blank.]" /*make an empty tape visible to user.*/
if L>1000 then $=left($, 1000) ... /*truncate tape to 1k bytes, append ···*/
say "tape's contents:" $ /*show the tape's contents (or 1st 1k).*/
say "tape's length: " L /* " " " length. */
say 'Turning machine used ' rules " rules in " cycle ' cycles.'
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
Turing_init: @.=blank; parse arg x; do j=1 for words(x); @.j=word(x,j); end /*j*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
Turing_rule: if symbol('RULES')=="LIT" then rules=0; rules=rules+1
pad=left('', length( word( arg(1),2 ) ) \==1 ) /*padding for rule*/
rule.rules=arg(1); say right('rule' rules, 20) "═══►" rule.rules
return |
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positive integer n that are relatively prime to n
counts the integers k in the range 1 ≤ k ≤ n for which the greatest common divisor gcd(n,k) is equal to 1
counts numbers ≤ n and prime to n
If the totient number (for N) is one less than N, then N is prime.
Task
Create a totient function and:
Find and display (1 per line) for the 1st 25 integers:
the integer (the index)
the totient number for that integer
indicate if that integer is prime
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000 (optional)
Show all output here.
Related task
Perfect totient numbers
Also see
Wikipedia: Euler's totient function.
MathWorld: totient function.
OEIS: Euler totient function phi(n).
| #Rust | Rust | use num::integer::gcd;
fn main() {
// Compute the totient of the first 25 natural integers
println!("N\t phi(n)\t Prime");
for n in 1..26 {
let phi_n = phi(n);
println!("{}\t {}\t {:?}", n, phi_n, phi_n == n - 1);
}
// Compute the number of prime numbers for various steps
[1, 100, 1000, 10000, 100000]
.windows(2)
.scan(0, |acc, tuple| {
*acc += (tuple[0]..=tuple[1]).filter(is_prime).count();
Some((tuple[1], *acc))
})
.for_each(|x| println!("Until {}: {} prime numbers", x.0, x.1));
}
fn is_prime(n: &usize) -> bool {
phi(*n) == *n - 1
}
fn phi(n: usize) -> usize {
(1..=n).filter(|&x| gcd(n, x) == 1).count()
} |
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #Jsish | Jsish | help Math
Math.method(...)
Commands performing math operations on numbers
Methods: abs acos asin atan atan2 ceil cos exp floor log max min pow random round sin sqrt tan |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.
From the wikipedia entry:
ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
result := call a function to do an operation
if result overflows
alert user
else
print result
The task is to implement the algorithm:
Use the function:
f
(
x
)
=
|
x
|
0.5
+
5
x
3
{\displaystyle f(x)=|x|^{0.5}+5x^{3}}
The overflow condition is an answer of greater than 400.
The 'user alert' should not stop processing of other items of the sequence.
Print a prompt before accepting eleven, textual, numeric inputs.
You may optionally print the item as well as its associated result, but the results must be in reverse order of input.
The sequence S may be 'implied' and so not shown explicitly.
Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
| #XBasic | XBasic |
' Trabb Pardo-Knuth algorithm
PROGRAM "tpkalgorithm"
VERSION "0.0001"
IMPORT "xma"
DECLARE FUNCTION Entry ()
INTERNAL FUNCTION SINGLE F(SINGLE n)
FUNCTION Entry ()
' Used "magic numbers" because of strict specification of the algorithm.
SINGLE s[10]
SINGLE tmp, r
UBYTE i
PRINT "Enter 11 numbers."
FOR i = 0 TO 10
PRINT i + 1;
s[i] = SINGLE(INLINE$(" => "))
NEXT i
PRINT
' Reverse
FOR i = 0 TO 10 / 2
tmp = s[i]
s[i] = s[10 - i]
s[10 - i] = tmp
NEXT i
'Results
FOR i = 0 TO 10
PRINT "f("; LTRIM$(STR$(s[i])); ") =";
r = F(s[i])
IF r > 400 THEN
PRINT " overflow"
ELSE
PRINT r
END IF
NEXT i
END FUNCTION
FUNCTION SINGLE F(SINGLE n)
RETURN SQRT(ABS(n)) + 5 * n * n *n
END FUNCTION
END PROGRAM
|
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.
From the wikipedia entry:
ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
result := call a function to do an operation
if result overflows
alert user
else
print result
The task is to implement the algorithm:
Use the function:
f
(
x
)
=
|
x
|
0.5
+
5
x
3
{\displaystyle f(x)=|x|^{0.5}+5x^{3}}
The overflow condition is an answer of greater than 400.
The 'user alert' should not stop processing of other items of the sequence.
Print a prompt before accepting eleven, textual, numeric inputs.
You may optionally print the item as well as its associated result, but the results must be in reverse order of input.
The sequence S may be 'implied' and so not shown explicitly.
Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
| #XPL0 | XPL0 | include c:\cxpl\codes;
func real F(X);
real X;
return sqrt(abs(X)) + 5.0*X*X*X;
real Result, S(11); int I;
[Text(0, "Please enter 11 numbers: ");
for I:= 0 to 11-1 do S(I):= RlIn(0);
for I:= 11-1 downto 0 do
[RlOut(0, S(I));
Result:= F(S(I));
if Result > 400.0 then
Text(0, " overflows")
else RlOut(0, Result);
CrLf(0)];
] |
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 739, 73, and 7 formed by removing digits from its right are also prime.
No zeroes are allowed in truncatable primes.
Task
The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied).
Related tasks
Find largest left truncatable prime in a given base
Sieve of Eratosthenes
See also
Truncatable Prime from MathWorld.]
| #Sidef | Sidef | func t_prime(n, left=true) {
var p = %w(2 3 5 7);
var f = (
left ? { '1'..'9' ~X+ p }
: { p ~X+ '1'..'9' }
)
n.times {
p = f().grep{ .to_i.is_prime }
}
p.map{.to_i}.max
}
say t_prime(5, left: true)
say t_prime(5, left: false) |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #Fortran | Fortran |
IF (STYLE.EQ."PRE") CALL OUT(HAS)
IF (LINKL(HAS).GT.0) CALL TARZAN(LINKL(HAS),STYLE)
IF (STYLE.EQ."IN") CALL OUT(HAS)
IF (LINKR(HAS).GT.0) CALL TARZAN(LINKR(HAS),STYLE)
IF (STYLE.EQ."POST") CALL OUT(HAS) |
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
| #Factor | Factor | "Hello,How,Are,You,Today" "," split "." join print |
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
| #Falcon | Falcon |
/* created by Aykayayciti Earl Lamont Montgomery
April 9th, 2018 */
a = []
a = strSplit("Hello,How,Are,You,Today", ",")
index = 0
start = 0
b = ""
for index in [ start : len(a)-1 : 1 ]
b = b + a[i] + "."
end
> b
|
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #HicEst | HicEst | t_start = TIME() ! returns seconds since midnight
SYSTEM(WAIT = 1234) ! wait 1234 milliseconds
t_end = TIME()
WRITE(StatusBar) t_end - t_start, " seconds" |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Icon_and_Unicon | Icon and Unicon | procedure timef(f) #: time a function f
local gcol,alloc,used,size,runtime,header,x,i
title := ["","total","static","string","block"] # headings
collect() # start with collected memory (before baseline)
every put(gcol := [], -&collections) # baseline collections count
every put(alloc := [], -&allocated) # . total allocated space by region
every put(used := [], -&storage) # . currently used space by region - no total
every put(size := [], -®ions) # . current size of regions - no total
write("Performance and Timing measurement for ",image(f),":")
runtime := &time # base time
f()
write("Execution time=",&time-runtime," ms.")
every (i := 0, x := &collections) do gcol[i +:= 1] +:= x
every (i := 0, x := &allocated ) do alloc[i +:= 1] +:= x
every (i := 0, x := &storage ) do used[i +:= 1] +:= x
every (i := 0, x := ®ions ) do size[i +:= 1] +:= x
push(gcol,"garbage collections:")
push(alloc,"memory allocated:")
push(used,"N/A","currently used:")
push(size,"N/A","current size:")
write("Memory Region and Garbage Collection Summary (delta):")
every (i := 0) <:= *!(title|gcol|alloc|used|size)
every x := (title|gcol|alloc|used|size) do {
f := left
every writes(f(!x,i + 3)) do f := right
write()
}
write("Note: static region values should be zero and may not be meaningful.")
return
end |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
Find the top N salaries in each department, where N is provided as a parameter.
Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:
Employee Name,Employee ID,Salary,Department
Tyler Bennett,E10297,32000,D101
John Rappl,E21437,47000,D050
George Woltman,E00127,53500,D101
Adam Smith,E63535,18000,D202
Claire Buckman,E39876,27800,D202
David McClellan,E04242,41500,D101
Rich Holcomb,E01234,49500,D202
Nathan Adams,E41298,21900,D050
Richard Potter,E43128,15900,D101
David Motsinger,E27002,19250,D202
Tim Sampair,E03033,27000,D101
Kim Arlich,E10001,57000,D190
Timothy Grove,E16398,29900,D190
| #Go | Go | package main
import (
"fmt"
"sort"
)
// language-native data description
type Employee struct {
Name, ID string
Salary int
Dept string
}
type EmployeeList []*Employee
var data = EmployeeList{
{"Tyler Bennett", "E10297", 32000, "D101"},
{"John Rappl", "E21437", 47000, "D050"},
{"George Woltman", "E00127", 53500, "D101"},
{"Adam Smith", "E63535", 18000, "D202"},
{"Claire Buckman", "E39876", 27800, "D202"},
{"David McClellan", "E04242", 41500, "D101"},
{"Rich Holcomb", "E01234", 49500, "D202"},
{"Nathan Adams", "E41298", 21900, "D050"},
{"Richard Potter", "E43128", 15900, "D101"},
{"David Motsinger", "E27002", 19250, "D202"},
{"Tim Sampair", "E03033", 27000, "D101"},
{"Kim Arlich", "E10001", 57000, "D190"},
{"Timothy Grove", "E16398", 29900, "D190"},
// Extra data to demonstrate ties
{"Tie A", "E16399", 29900, "D190"},
{"Tie B", "E16400", 29900, "D190"},
{"No Tie", "E16401", 29899, "D190"},
}
// We only need one type of ordering/grouping for this task so we could directly
// implement sort.Interface on EmployeeList (or a byDeptSalary alias type) with
// the appropriate Less method.
//
// Instead, we'll add a bit here that makes it easier to use arbitrary orderings.
// This is like the "SortKeys" Planet sorting example in the sort package
// documentation, see https://golang.org/pkg/sort
type By func(e1, e2 *Employee) bool
type employeeSorter struct {
list EmployeeList
by func(e1, e2 *Employee) bool
}
func (by By) Sort(list EmployeeList) { sort.Sort(&employeeSorter{list, by}) }
func (s *employeeSorter) Len() int { return len(s.list) }
func (s *employeeSorter) Swap(i, j int) { s.list[i], s.list[j] = s.list[j], s.list[i] }
func (s *employeeSorter) Less(i, j int) bool { return s.by(s.list[i], s.list[j]) }
// For this specific task we could just write the data to an io.Writer
// but in general it's better to return the data in a usable form (for
// example, perhaps other code want's to do something like compare the
// averages of the top N by department).
//
// So we go through the extra effort of returning an []EmployeeList, a
// list of employee lists, one per deparment. The lists are trimmed to
// to the top 'n', which can be larger than n if there are ties for the
// nth salary (callers that don't care about ties could just trim more.)
func (el EmployeeList) TopSalariesByDept(n int) []EmployeeList {
if n <= 0 || len(el) == 0 {
return nil
}
deptSalary := func(e1, e2 *Employee) bool {
if e1.Dept != e2.Dept {
return e1.Dept < e2.Dept
}
if e1.Salary != e2.Salary {
return e1.Salary > e2.Salary
}
// Always have some unique field as the last one in a sort list
return e1.ID < e2.ID
}
// We could just sort the data in place for this task. But
// perhaps messing with the order is undesirable or there is
// other concurrent access. So we'll make a copy and sort that.
// It's just pointers so the amount to copy is relatively small.
sorted := make(EmployeeList, len(el))
copy(sorted, el)
By(deptSalary).Sort(sorted)
perDept := []EmployeeList{}
var lastDept string
var lastSalary int
for _, e := range sorted {
if e.Dept != lastDept || len(perDept) == 0 {
lastDept = e.Dept
perDept = append(perDept, EmployeeList{e})
} else {
i := len(perDept) - 1
if len(perDept[i]) >= n && e.Salary != lastSalary {
continue
}
perDept[i] = append(perDept[i], e)
lastSalary = e.Salary
}
}
return perDept
}
func main() {
const n = 3
top := data.TopSalariesByDept(n)
if len(top) == 0 {
fmt.Println("Nothing to show.")
return
}
fmt.Printf("Top %d salaries per department\n", n)
for _, list := range top {
fmt.Println(list[0].Dept)
for _, e := range list {
fmt.Printf(" %s %16s %7d\n", e.ID, e.Name, e.Salary)
}
}
} |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #F.23 | F# | type Brick =
| Empty
| Computer
| User
let brickToString = function
| Empty -> ' '
| Computer -> 'X'
| User -> 'O'
// y -> x -> Brick
type Board = Map<int, Map<int, Brick> >
let emptyBoard =
let emptyRow = Map.ofList [0,Empty; 1,Empty; 2,Empty]
Map.ofList [0,emptyRow; 1,emptyRow; 2,emptyRow]
let get (b:Board) (x,y) = b.[y].[x]
let set player (b:Board) (x,y) : Board =
let row = b.[y].Add(x, player)
b.Add(y, row)
let winningPositions =
[for x in [0..2] -> x,x] // first diagonal
::[for x in [0..2] -> 2-x,x] // second diagonal
::[for y in [0..2] do
yield! [[for x in [0..2]->(y,x)]; // columns
[for x in [0..2] -> (x,y)]]] // rows
let hasWon player board =
List.exists
(fun ps -> List.forall (fun pos -> get board pos = player) ps)
winningPositions
let freeSpace board =
[for x in 0..2 do
for y in 0..2 do
if get board (x,y) = Empty then yield x,y]
type Evaluation =
| Win
| Draw
| Lose
let rec evaluate board move =
let b2 = set Computer board move
if hasWon Computer b2 then Win
else
match freeSpace b2 with
| [] -> Draw
| userChoices ->
let b3s = List.map (set User b2) userChoices
if List.exists (hasWon User) b3s then Lose
elif List.exists (fun b3 -> bestOutcome b3 = Lose) b3s
then Lose
elif List.exists (fun b3 -> bestOutcome b3 = Draw) b3s
then Draw
else Win
and findBestChoice b =
match freeSpace b with
| [] -> ((-1,-1), Draw)
| choices ->
match List.tryFind (fun c -> evaluate b c = Win) choices with
| Some c -> (c, Win)
| None -> match List.tryFind (fun c -> evaluate b c = Draw) choices with
| Some c -> (c, Draw)
| None -> (List.head choices, Lose)
and bestOutcome b = snd (findBestChoice b)
let bestChoice b = fst (findBestChoice b)
let computerPlay b = set Computer b (bestChoice b)
let printBoard b =
printfn " | A | B | C |"
printfn "---+---+---+---+"
for y in 0..2 do
printfn " %d | %c | %c | %c |"
(3-y)
(get b (0,y) |> brickToString)
(get b (1,y) |> brickToString)
(get b (2,y) |> brickToString)
printfn "---+---+---+---+"
let rec userPlay b =
printfn "Which field do you play? (format: a1)"
let input = System.Console.ReadLine()
if input.Length <> 2
|| input.[0] < 'a' || input.[0] > 'c'
|| input.[1] < '1' || input.[1] > '3' then
printfn "illegal input"
userPlay b
else
let x = int(input.[0]) - int('a')
let y = 2 - int(input.[1]) + int('1')
if get b (x,y) <> Empty then
printfn "Field is not free."
userPlay b
else
set User b (x,y)
let rec gameLoop b player =
if freeSpace b = [] then
printfn "Game over. Draw."
elif player = Computer then
printfn "Computer plays..."
let b2 = computerPlay b
printBoard b2
if hasWon Computer b2 then
printfn "Game over. I have won."
else
gameLoop b2 User
elif player = User then
let b2 = userPlay b
printBoard b2
if hasWon User b2 then
printfn "Game over. You have won."
else
gameLoop b2 Computer
// randomly choose an element of a list
let choose =
let rnd = new System.Random()
fun (xs:_ list) -> xs.[rnd.Next(xs.Length)]
// play first brick randomly
printfn "Computer starts."
let b = set Computer emptyBoard (choose (freeSpace emptyBoard))
printBoard b
gameLoop b User |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #COBOL | COBOL | >>SOURCE FREE
IDENTIFICATION DIVISION.
PROGRAM-ID. towers-of-hanoi.
PROCEDURE DIVISION.
CALL "move-disk" USING 4, 1, 2, 3
.
END PROGRAM towers-of-hanoi.
IDENTIFICATION DIVISION.
PROGRAM-ID. move-disk RECURSIVE.
DATA DIVISION.
LINKAGE SECTION.
01 n PIC 9 USAGE COMP.
01 from-pole PIC 9 USAGE COMP.
01 to-pole PIC 9 USAGE COMP.
01 via-pole PIC 9 USAGE COMP.
PROCEDURE DIVISION USING n, from-pole, to-pole, via-pole.
IF n > 0
SUBTRACT 1 FROM n
CALL "move-disk" USING CONTENT n, from-pole, via-pole, to-pole
DISPLAY "Move disk from pole " from-pole " to pole " to-pole
CALL "move-disk" USING CONTENT n, via-pole, to-pole, from-pole
END-IF
.
END PROGRAM move-disk. |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #Quackery | Quackery | [ [] 0 rot times
[ i^ dup 1 - ^
dup 1 >> ^ hex 55555555 & if
[ 1 swap - ]
dup dip
[ digit join ] ] drop ] is thue-morse ( n --> $ )
20 thue-morse echo$ cr |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #R | R |
thue_morse <- function(steps) {
sb1 <- "0"
sb2 <- "1"
for (idx in 1:steps) {
tmp <- sb1
sb1 <- paste0(sb1, sb2)
sb2 <- paste0(sb2, tmp)
}
sb1
}
cat(thue_morse(6), "\n")
|
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #Racket | Racket | #lang racket
(define 1<->0 (match-lambda [#\0 #\1] [#\1 #\0]))
(define (thue-morse-step (s "0"))
(string-append s (list->string (map 1<->0 (string->list s)))))
(define (thue-morse n)
(let inr ((n (max (sub1 n) 0)) (rv (list "0")))
(if (zero? n) (reverse rv) (inr (sub1 n) (cons (thue-morse-step (car rv)) rv)))))
(for-each displayln (thue-morse 7)) |
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were separated by the separators, become the elements of the output list.
Empty fields should be preserved, even at the start and end.
Rules for escaping:
"Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.
When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special).
Each occurrence of the escape character that was used to escape something, should not become part of the output.
Test case
Demonstrate that your function satisfies the following test-case:
Input
Output
string:
one^|uno||three^^^^|four^^^|^cuatro|
separator character:
|
escape character:
^
one|uno
three^^
four^|cuatro
(Print the output list in any format you like, as long as it is it easy to see what the fields are.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Rust | Rust | const SEPARATOR: char = '|';
const ESCAPE: char = '^';
const STRING: &str = "one^|uno||three^^^^|four^^^|^cuatro|";
fn tokenize(string: &str) -> Vec<String> {
let mut token = String::new();
let mut tokens: Vec<String> = Vec::new();
let mut chars = string.chars();
while let Some(ch) = chars.next() {
match ch {
SEPARATOR => {
tokens.push(token);
token = String::new();
},
ESCAPE => {
if let Some(next) = chars.next() {
token.push(next);
}
},
_ => token.push(ch),
}
}
tokens.push(token);
tokens
}
fn main() {
println!("{:#?}", tokenize(STRING));
} |
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were separated by the separators, become the elements of the output list.
Empty fields should be preserved, even at the start and end.
Rules for escaping:
"Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.
When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special).
Each occurrence of the escape character that was used to escape something, should not become part of the output.
Test case
Demonstrate that your function satisfies the following test-case:
Input
Output
string:
one^|uno||three^^^^|four^^^|^cuatro|
separator character:
|
escape character:
^
one|uno
three^^
four^|cuatro
(Print the output list in any format you like, as long as it is it easy to see what the fields are.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Scala | Scala | object TokenizeStringWithEscaping0 extends App {
val (markerSpE,markerSpF) = ("\ufffe" , "\uffff")
def tokenize(str: String, sep: String, esc: String): Array[String] = {
val s0 = str.replace( esc + esc, markerSpE).replace(esc + sep, markerSpF)
val s = if (s0.last.toString == esc) s0.replace(esc, "") + esc else s0.replace(esc, "")
s.split(sep.head).map (_.replace(markerSpE, esc).replace(markerSpF, sep))
}
def str = "one^|uno||three^^^^|four^^^|^cuatro|"
tokenize(str, "|", "^").foreach(it => println(if (it.isEmpty) "<empty token>" else it))
} |
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.
A tool exists that extracts library dependencies.
Task
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
Assume library names are single words.
Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be flagged.
Use the following data as an example:
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01.
C.f.
Topological sort/Extracted top item.
There are two popular algorithms for topological sorting:
Kahn's 1962 topological sort [1]
depth-first search [2] [3]
| #Nim | Nim | import sequtils, strutils, sets, tables, sugar
type StringSet = HashSet[string]
proc topSort(data: var OrderedTable[string, StringSet]) =
## Topologically sort the data in place.
var ranks: Table[string, Natural] # Maps the keys to a rank.
# Remove self dependencies.
for key, values in data.mpairs:
values.excl key
# Add extra items (i.e items present in values but not in keys).
for values in toSeq(data.values):
for value in values:
if value notin data:
data[value] = initHashSet[string]()
# Find ranks.
var deps = data # Working copy of the table.
var rank = 0
while deps.len > 0:
# Find a key with an empty dependency set.
var keyToRemove: string
for key, values in deps.pairs:
if values.card == 0:
keyToRemove = key
break
if keyToRemove.len == 0:
# Not found: there is a cycle.
raise newException(ValueError, "Unorderable items found: " & toSeq(deps.keys).join(", "))
# Assign a rank to the key and remove it from keys and values.
ranks[keyToRemove] = rank
inc rank
deps.del keyToRemove
for k, v in deps.mpairs:
v.excl keyToRemove
# Sort the original data according to the ranks.
data.sort((x, y) => cmp(ranks[x[0]], ranks[y[0]]))
when isMainModule:
const Data = {"des_system_lib": ["std", "synopsys", "std_cell_lib",
"des_system_lib", "dw02", "dw01",
"ramlib", "ieee"].toHashSet,
"dw01": ["ieee", "dw01", "dware", "gtech"].toHashSet,
"dw02": ["ieee", "dw02", "dware"].toHashSet,
"dw03": ["std", "synopsys", "dware", "dw03",
"dw02", "dw01", "ieee", "gtech"].toHashSet,
"dw04": ["dw04", "ieee", "dw01", "dware", "gtech"].toHashSet,
"dw05": ["dw05", "ieee", "dware"].toHashSet,
"dw06": ["dw06", "ieee", "dware"].toHashSet,
"dw07": ["ieee", "dware"].toHashSet,
"dware": ["ieee", "dware"].toHashSet,
"gtech": ["ieee", "gtech"].toHashSet,
"ramlib": ["std", "ieee"].toHashSet,
"std_cell_lib": ["ieee", "std_cell_lib"].toHashSet,
"synopsys": initHashSet[string]()}.toOrderedTable
# Process the original data (without cycle).
echo "Data without cycle. Order after sorting:"
var data = Data
try:
data.topSort()
for key in data.keys: echo key
except ValueError:
echo getCurrentExceptionMsg()
# Process the modified data (with a cycle).
echo "\nData with a cycle:"
data = Data
data["dw01"].incl "dw04"
try:
data.topSort()
for key in data.keys: echo key
except ValueError:
echo getCurrentExceptionMsg() |
http://rosettacode.org/wiki/Universal_Turing_machine | Universal Turing machine | One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936–1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.
Task
Simulate such a machine capable
of taking the definition of any other Turing machine and executing it.
Of course, you will not have an infinite tape,
but you should emulate this as much as is possible.
The three permissible actions on the tape are "left", "right" and "stay".
To test your universal Turing machine (and prove your programming language
is Turing complete!), you should execute the following two Turing machines
based on the following definitions.
Simple incrementer
States: q0, qf
Initial state: q0
Terminating states: qf
Permissible symbols: B, 1
Blank symbol: B
Rules:
(q0, 1, 1, right, q0)
(q0, B, 1, stay, qf)
The input for this machine should be a tape of 1 1 1
Three-state busy beaver
States: a, b, c, halt
Initial state: a
Terminating states: halt
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(a, 0, 1, right, b)
(a, 1, 1, left, c)
(b, 0, 1, left, a)
(b, 1, 1, right, b)
(c, 0, 1, left, b)
(c, 1, 1, stay, halt)
The input for this machine should be an empty tape.
Bonus:
5-state, 2-symbol probable Busy Beaver machine from Wikipedia
States: A, B, C, D, E, H
Initial state: A
Terminating states: H
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(A, 0, 1, right, B)
(A, 1, 1, left, C)
(B, 0, 1, right, C)
(B, 1, 1, right, B)
(C, 0, 1, right, D)
(C, 1, 0, left, E)
(D, 0, 1, left, A)
(D, 1, 1, left, D)
(E, 0, 1, stay, H)
(E, 1, 0, left, A)
The input for this machine should be an empty tape.
This machine runs for more than 47 millions steps.
| #Ruby | Ruby | class Turing
class Tape
def initialize(symbols, blank, starting_tape)
@symbols = symbols
@blank = blank
@tape = starting_tape
@index = 0
end
def read
retval = @tape[@index]
unless retval
retval = @tape[@index] = @blank
end
raise "invalid symbol '#{retval}' on tape" unless @tape.member?(retval)
return retval
end
def write(symbol)
@tape[@index] = symbol
end
def right
@index += 1
end
def left
if @index == 0
@tape.unshift @blank
else
@index -= 1
end
end
def stay
# nop
end
def get_tape
return @tape
end
end
def initialize(symbols, blank,
initial_state, halt_states, running_states,
rules, starting_tape = [])
@tape = Tape.new(symbols, blank, starting_tape)
@initial_state = initial_state
@halt_states = halt_states
@running_states = running_states
@rules = rules
@halted = false
end
def run
raise "machine already halted" if @halted
state = @initial_state
while (true)
break if @halt_states.member? state
raise "unknown state '#{state}'" unless @running_states.member? state
symbol = @tape.read
outsym, action, state = @rules[state][symbol]
@tape.write outsym
@tape.send action
end
@halted = true
return @tape.get_tape
end
end |
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positive integer n that are relatively prime to n
counts the integers k in the range 1 ≤ k ≤ n for which the greatest common divisor gcd(n,k) is equal to 1
counts numbers ≤ n and prime to n
If the totient number (for N) is one less than N, then N is prime.
Task
Create a totient function and:
Find and display (1 per line) for the 1st 25 integers:
the integer (the index)
the totient number for that integer
indicate if that integer is prime
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000 (optional)
Show all output here.
Related task
Perfect totient numbers
Also see
Wikipedia: Euler's totient function.
MathWorld: totient function.
OEIS: Euler totient function phi(n).
| #S-BASIC | S-BASIC |
$lines
rem - return p mod q
function mod(p, q = integer) = integer
end = p - q * (p / q)
rem - return greatest common divisor of x and y
function gcd(x, y = integer) = integer
var r, temp = integer
if x < y then
begin
temp = x
x = y
y = temp
end
r = mod(x, y)
while r <> 0 do
begin
x = y
y = r
r = mod(x, y)
end
end = y
rem - return phi (also called totient) of n
function phi(n = integer) = integer
var i, count = integer
count = 1
for i = 2 to n
if gcd(n, i) = 1 then count = count + 1
next i
end = count
rem - exercise the function
var n, totient, count = integer
print " n Phi(n) Prime?"
for n = 1 to 25
totient = phi(n)
print using "#### #### ";n, totient;
if totient + 1 = n then
print "yes"
else
print "no"
next n
rem - and further test it by counting primes
print
count = 0
for n = 1 to 1000
if phi(n) = n - 1 then count = count + 1
if n = 100 then
print "Primes up to 100 = ";count
else if n = 1000 then
print "Primes up to 1000 = ";count
next n
end
|
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #Julia | Julia | # v0.6.0
rad = π / 4
deg = 45.0
@show rad deg
@show sin(rad) sin(deg2rad(deg))
@show cos(rad) cos(deg2rad(deg))
@show tan(rad) tan(deg2rad(deg))
@show asin(sin(rad)) asin(sin(rad)) |> rad2deg
@show acos(cos(rad)) acos(cos(rad)) |> rad2deg
@show atan(tan(rad)) atan(tan(rad)) |> rad2deg |
http://rosettacode.org/wiki/Trabb_Pardo%E2%80%93Knuth_algorithm | Trabb Pardo–Knuth algorithm | The TPK algorithm is an early example of a programming chrestomathy.
It was used in Donald Knuth and Luis Trabb Pardo's Stanford tech report The Early Development of Programming Languages.
The report traces the early history of work in developing computer languages in the 1940s and 1950s, giving several translations of the algorithm.
From the wikipedia entry:
ask for 11 numbers to be read into a sequence S
reverse sequence S
for each item in sequence S
result := call a function to do an operation
if result overflows
alert user
else
print result
The task is to implement the algorithm:
Use the function:
f
(
x
)
=
|
x
|
0.5
+
5
x
3
{\displaystyle f(x)=|x|^{0.5}+5x^{3}}
The overflow condition is an answer of greater than 400.
The 'user alert' should not stop processing of other items of the sequence.
Print a prompt before accepting eleven, textual, numeric inputs.
You may optionally print the item as well as its associated result, but the results must be in reverse order of input.
The sequence S may be 'implied' and so not shown explicitly.
Print and show the program in action from a typical run here. (If the output is graphical rather than text then either add a screendump or describe textually what is displayed).
| #zkl | zkl | fcn f(x) { x.abs().pow(0.5) + x.pow(3)*5 }
reg ns; do{
ns=ask("11 numbers seperated by spaces: ");
try{ ns=ns.split(" ").filter().apply("toFloat") } catch{}
}while(not ns.isType(List) or ns.len()!=11);
ns.reverse().apply(fcn(x){
fx:=f(x); "f(%7.3f)-->%s".fmt(x, if(fx>400)"Overflow" else fx) })
.pump(Console.println); |
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 739, 73, and 7 formed by removing digits from its right are also prime.
No zeroes are allowed in truncatable primes.
Task
The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied).
Related tasks
Find largest left truncatable prime in a given base
Sieve of Eratosthenes
See also
Truncatable Prime from MathWorld.]
| #Swift | Swift | func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
if n % 2 == 0 {
return n == 2
}
if n % 3 == 0 {
return n == 3
}
var p = 5
while p * p <= n {
if n % p == 0 {
return false
}
p += 2
if n % p == 0 {
return false
}
p += 4
}
return true
}
func isLeftTruncatable(_ p: Int) -> Bool {
var n = 10
var q = p
while p > n {
if !isPrime(p % n) || q == p % n {
return false
}
q = p % n
n *= 10
}
return true
}
func isRightTruncatable(_ p: Int) -> Bool {
var q = p / 10
while q > 0 {
if !isPrime(q) {
return false
}
q /= 10
}
return true
}
let limit = 1000000
var largestLeft = 0
var largestRight = 0
var p = limit
while p >= 2 {
if isPrime(p) && isLeftTruncatable(p) {
largestLeft = p
break
}
p -= 1
}
print("Largest left truncatable prime is \(largestLeft)")
p = limit
while p >= 2 {
if isPrime(p) && isRightTruncatable(p) {
largestRight = p
break
}
p -= 1
}
print("Largest right truncatable prime is \(largestRight)") |
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 739, 73, and 7 formed by removing digits from its right are also prime.
No zeroes are allowed in truncatable primes.
Task
The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied).
Related tasks
Find largest left truncatable prime in a given base
Sieve of Eratosthenes
See also
Truncatable Prime from MathWorld.]
| #Tcl | Tcl | package require Tcl 8.5
# Optimized version of the Sieve-of-Eratosthenes task solution
proc sieve n {
set primes [list]
if {$n < 2} {return $primes}
set nums [dict create]
for {set i 2} {$i <= $n} {incr i} {
dict set nums $i ""
}
set next 2
set limit [expr {sqrt($n)}]
while {$next <= $limit} {
for {set i $next} {$i <= $n} {incr i $next} {dict unset nums $i}
lappend primes $next
dict for {next -} $nums break
}
return [concat $primes [dict keys $nums]]
}
proc isLeftTruncatable n {
global isPrime
while {[string length $n] > 0} {
if {![info exist isPrime($n)]} {
return false
}
set n [string range $n 1 end]
}
return true
}
proc isRightTruncatable n {
global isPrime
while {[string length $n] > 0} {
if {![info exist isPrime($n)]} {
return false
}
set n [string range $n 0 end-1]
}
return true
}
# Demo code
set limit 1000000
puts "calculating primes up to $limit"
set primes [sieve $limit]
puts "search space contains [llength $primes] members"
foreach p $primes {
set isPrime($p) "yes"
}
set primes [lreverse $primes]
puts "searching for largest left-truncatable prime"
foreach p $primes {
if {[isLeftTruncatable $p]} {
puts FOUND:$p
break
}
}
puts "searching for largest right-truncatable prime"
foreach p $primes {
if {[isRightTruncatable $p]} {
puts FOUND:$p
break
}
} |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #FreeBASIC | FreeBASIC |
#define NULL 0
Dim Shared As Byte maxnodos = 100
Dim Shared As Byte raiz = 0
Dim Shared As Byte izda = 1
Dim Shared As Byte dcha = 2
Dim Shared As Byte arbol(maxnodos, 3)
Sub crear_arbol()
arbol(1, raiz) = 1
arbol(1, izda) = 2 : arbol(1, dcha) = 3
arbol(2, raiz) = 2
arbol(2, izda) = 4 : arbol(2, dcha) = 5
arbol(3, raiz) = 3
arbol(3, izda) = 6 : arbol(3, dcha) = NULL
arbol(4, raiz) = 4
arbol(4, izda) = 7 : arbol(4, dcha) = NULL
arbol(5, raiz) = 5
arbol(5, izda) = NULL : arbol(5, dcha) = NULL
arbol(6, raiz) = 6
arbol(6, izda) = 8 : arbol(6, dcha) = 9
arbol(7, raiz) = 7
arbol(7, izda) = NULL : arbol(7, dcha) = NULL
arbol(8, raiz) = 8
arbol(8, izda) = NULL : arbol(8, dcha) = NULL
arbol(9, raiz) = 9
arbol(9, izda) = NULL : arbol(9, dcha) = NULL
End Sub
Sub recorrido_preorder(nodo As Byte)
If nodo <> NULL Then
Print arbol(nodo, raiz);
recorrido_preorder(arbol(nodo, izda))
recorrido_preorder(arbol(nodo, dcha))
End If
End Sub
Sub recorrido_postorder(nodo As Byte)
If nodo <> NULL Then
recorrido_postorder(arbol(nodo, izda))
recorrido_postorder(arbol(nodo, dcha))
Print arbol(nodo, raiz);
End If
End Sub
Sub recorrido_inorden(nodo As Byte)
If nodo <> NULL Then
recorrido_inorden(arbol(nodo, izda))
Print arbol(nodo, raiz);
recorrido_inorden(arbol(nodo, dcha))
End If
End Sub
Sub recorrido_ordenXnivel(nodo As Byte)
Dim As Byte actual = 1
Dim As Byte primero_libre = actual + 1
Dim As Byte cola(maxnodos)
cola(actual) = nodo
While cola(actual) <> NULL
If arbol(cola(actual), izda) <> NULL Then
cola(primero_libre) = arbol(cola(actual), izda)
primero_libre += 1
End If
If arbol(cola(actual), dcha) <> NULL Then
cola(primero_libre) = arbol(cola(actual), dcha)
primero_libre += 1
End If
Print arbol(cola(actual), raiz);
actual += 1
Wend
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
| #Fantom | Fantom |
class Main
{
public static Void main ()
{
str := "Hello,How,Are,You,Today"
words := str.split(',')
words.each |Str word|
{
echo ("${word}. ")
}
}
}
|
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
| #Fennel | Fennel | (fn string.split [self sep]
(let [pattern (string.format "([^%s]+)" sep)
fields {}]
(self:gsub pattern (fn [c] (tset fields (+ 1 (length fields)) c)))
fields))
(let [str "Hello,How,Are,You,Today"]
(print (table.concat (str:split ",") "."))) |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Ioke | Ioke | use("benchmark")
func = method((1..50000) reduce(+))
Benchmark report(1, 1, func) |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #J | J | (6!:2 , 7!:2) '|: 50 50 50 $ i. 50^3'
0.00488008 3.14829e6
timespacex '|: 50 50 50 $ i. 50^3'
0.00388519 3.14829e6 |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
Find the top N salaries in each department, where N is provided as a parameter.
Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:
Employee Name,Employee ID,Salary,Department
Tyler Bennett,E10297,32000,D101
John Rappl,E21437,47000,D050
George Woltman,E00127,53500,D101
Adam Smith,E63535,18000,D202
Claire Buckman,E39876,27800,D202
David McClellan,E04242,41500,D101
Rich Holcomb,E01234,49500,D202
Nathan Adams,E41298,21900,D050
Richard Potter,E43128,15900,D101
David Motsinger,E27002,19250,D202
Tim Sampair,E03033,27000,D101
Kim Arlich,E10001,57000,D190
Timothy Grove,E16398,29900,D190
| #Groovy | Groovy | def displayRank(employees, number) {
employees.groupBy { it.Department }.sort().each { department, staff ->
println "Department $department"
println " Name ID Salary"
staff.sort { e1, e2 -> e2.Salary <=> e1.Salary }
staff[0..<Math.min(number, staff.size())].each { e ->
println " ${e.Name.padRight(20)}${e.ID}${sprintf('%8d', e.Salary)}"
}
println()
}
}
def employees = [
[Name: 'Tyler Bennett', ID: 'E10297', Salary: 32000, Department: 'D101'],
[Name: 'John Rappl', ID: 'E21437', Salary: 47000, Department: 'D050'],
[Name: 'George Woltman', ID: 'E00127', Salary: 53500, Department: 'D101'],
[Name: 'Adam Smith', ID: 'E63535', Salary: 18000, Department: 'D202'],
[Name: 'Claire Buckman', ID: 'E39876', Salary: 27800, Department: 'D202'],
[Name: 'David McClellan', ID: 'E04242', Salary: 41500, Department: 'D101'],
[Name: 'Rich Holcomb', ID: 'E01234', Salary: 49500, Department: 'D202'],
[Name: 'Nathan Adams', ID: 'E41298', Salary: 21900, Department: 'D050'],
[Name: 'Richard Potter', ID: 'E43128', Salary: 15900, Department: 'D101'],
[Name: 'David Motsinger', ID: 'E27002', Salary: 19250, Department: 'D202'],
[Name: 'Tim Sampair', ID: 'E03033', Salary: 27000, Department: 'D101'],
[Name: 'Kim Arlich', ID: 'E10001', Salary: 57000, Department: 'D190'],
[Name: 'Timothy Grove', ID: 'E16398', Salary: 29900, Department: 'D190']
]
displayRank(employees, 3) |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #Forth | Forth | create board 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 ,
\ board: 0=empty, 1=player X, 2=player O
: player. ( player -- ) C" XO" 1+ + @ emit ;
: spot ( n -- addr ) cells board + ;
: clean-board ( -- ) 9 0 do 0 i spot ! loop ;
: show-board
CR ." +---+---+---+ +---+---+---+" CR
3 0 do
." | "
3 0 do
i j 3 * + spot @ player. ." | "
loop
." | "
3 0 do
i j 3 * + . ." | "
loop
CR ." +---+---+---+ +---+---+---+" CR
loop ;
: spots-equal ( n1 n2 n3 -- f )
over spot @ swap spot @ = >r spot @ swap spot @ = r> and ;
: spots-win ( n1 n2 n3 -- f )
dup >r spots-equal r> spot @ 0<> and ;
: winner-check ( -- player )
0 1 2 spots-win if 0 spot @ exit then
3 4 5 spots-win if 3 spot @ exit then
6 7 8 spots-win if 6 spot @ exit then
0 3 6 spots-win if 0 spot @ exit then
1 4 7 spots-win if 1 spot @ exit then
2 5 8 spots-win if 2 spot @ exit then
0 4 8 spots-win if 0 spot @ exit then
2 4 6 spots-win if 2 spot @ exit then
0 ;
: player-move ( player -- )
begin
key dup emit [char] 0 - dup
spot @ 0= if spot ! exit else drop then
again ;
: game
clean-board show-board
9 0 do
i 2 mod 1+ dup ." Player " player. ." : "
player-move show-board
winner-check dup 0<> if player. ." wins !" unloop exit else drop then
loop
." Draw!" ;
game
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #CoffeeScript | CoffeeScript | hanoi = (ndisks, start_peg=1, end_peg=3) ->
if ndisks
staging_peg = 1 + 2 + 3 - start_peg - end_peg
hanoi(ndisks-1, start_peg, staging_peg)
console.log "Move disk #{ndisks} from peg #{start_peg} to #{end_peg}"
hanoi(ndisks-1, staging_peg, end_peg)
hanoi(4) |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #Raku | Raku | .say for (0, { '0' ~ @_.join.trans( "01" => "10", :g) } ... *)[^8]; |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #REXX | REXX | /*REXX pgm generates & displays the Thue─Morse sequence up to the Nth term (inclusive). */
parse arg N . /*obtain the optional argument from CL.*/
if N=='' | N=="," then N= 80 /*Not specified? Then use the default.*/
$= /*the Thue─Morse sequence (so far). */
do j=0 to N /*generate sequence up to the Nth item.*/
$= $ || $weight(j) // 2 /*append the item to the Thue─Morse seq*/
end /*j*/
say $
exit /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
$pop: return length( space( translate( arg(1), , 0), 0) ) /*count 1's in number.*/
$weight: return $pop( x2b( d2x( arg(1) ) ) ) /*dec──►bin, pop count*/ |
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were separated by the separators, become the elements of the output list.
Empty fields should be preserved, even at the start and end.
Rules for escaping:
"Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.
When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special).
Each occurrence of the escape character that was used to escape something, should not become part of the output.
Test case
Demonstrate that your function satisfies the following test-case:
Input
Output
string:
one^|uno||three^^^^|four^^^|^cuatro|
separator character:
|
escape character:
^
one|uno
three^^
four^|cuatro
(Print the output list in any format you like, as long as it is it easy to see what the fields are.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Sidef | Sidef | func tokenize(string, sep, esc) {
var fields = string.split(
Regex(esc.escape + '.(*SKIP)(*FAIL)|' + sep.escape, 's'), -1
)
fields.map{.gsub(Regex(esc.escape + '(.)'), {|s1| s1 }) }
}
tokenize("one^|uno||three^^^^|four^^^|^cuatro|", '|', '^').each { |str|
say str.dump
} |
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.
A tool exists that extracts library dependencies.
Task
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
Assume library names are single words.
Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be flagged.
Use the following data as an example:
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01.
C.f.
Topological sort/Extracted top item.
There are two popular algorithms for topological sorting:
Kahn's 1962 topological sort [1]
depth-first search [2] [3]
| #Object_Pascal | Object Pascal |
program topologicalsortrosetta;
{*
Topological sorter to parse e.g. dependencies.
Written for FreePascal 2.4.x/2.5.1. Probably works in Delphi, but you'd have to
change some units.
*}
{$IFDEF FPC}
// FreePascal-specific setup
{$mode objfpc}
uses {$IFDEF UNIX}
cwstring, {* widestring support for unix *} {$IFDEF UseCThreads}
cthreads, {$ENDIF UseCThreads} {$ENDIF UNIX}
Classes,
SysUtils;
{$ENDIF}
type
RNodeIndex = record
NodeName: WideString; //Name of the node
//Index: integer; //Index number used in DepGraph. For now, we can distill the index from the array index. If we want to use a TList or similar, we'd need an index property
Order: integer; //Order when sorted
end;
RDepGraph = record
Node: integer; //Refers to Index in NodeIndex
DependsOn: integer; //The Node depends on this other Node.
end;
{ TTopologicalSort }
TTopologicalSort = class(TObject)
private
Nodes: array of RNodeIndex;
DependencyGraph: array of RDepGraph;
FCanBeSorted: boolean;
function SearchNode(NodeName: WideString): integer;
function SearchIndex(NodeID: integer): WideString;
function DepFromNodeID(NodeID: integer): integer;
function DepFromDepID(DepID: integer): integer;
function DepFromNodeIDDepID(NodeID, DepID: integer): integer;
procedure DelDependency(const Index: integer);
public
constructor Create;
destructor Destroy; override;
procedure SortOrder(var Output: TStringList);
procedure AddNode(NodeName: WideString);
procedure AddDependency(NodeName, DependsOn: WideString);
procedure AddNodeDependencies(NodeAndDependencies: TStringList);
//Each string has node, and the nodes it depends on. This allows insertion of an entire dependency graph at once
//procedure DelNode(NodeName: Widestring);
procedure DelDependency(NodeName, DependsOn: WideString);
property CanBeSorted: boolean read FCanBeSorted;
end;
const
INVALID = -1;
// index not found for index search functions, no sort order defined, or record invalid/deleted
function TTopologicalSort.SearchNode(NodeName: WideString): integer;
var
Counter: integer;
begin
// Return -1 if node not found. If node found, return index in array
Result := INVALID;
for Counter := 0 to High(Nodes) do
begin
if Nodes[Counter].NodeName = NodeName then
begin
Result := Counter;
break;
end;
end;
end;
function TTopologicalSort.SearchIndex(NodeID: integer): WideString;
//Look up name for the index
begin
if (NodeID > 0) and (NodeID <= High(Nodes)) then
begin
Result := Nodes[NodeID].NodeName;
end
else
begin
Result := 'ERROR'; //something's fishy, this shouldn't happen
end;
end;
function TTopologicalSort.DepFromNodeID(NodeID: integer): integer;
// Look for Node index number in the dependency graph
// and return the first node found. If nothing found, return -1
var
Counter: integer;
begin
Result := INVALID;
for Counter := 0 to High(DependencyGraph) do
begin
if DependencyGraph[Counter].Node = NodeID then
begin
Result := Counter;
break;
end;
end;
end;
function TTopologicalSort.DepFromDepID(DepID: integer): integer;
// Look for dependency index number in the dependency graph
// and return the index for the first one found. If nothing found, return -1
var
Counter: integer;
begin
Result := INVALID;
for Counter := 0 to High(DependencyGraph) do
begin
if DependencyGraph[Counter].DependsOn = DepID then
begin
Result := Counter;
break;
end;
end;
end;
function TTopologicalSort.DepFromNodeIDDepID(NodeID, DepID: integer): integer;
// Shows index for the dependency from NodeID on DepID, or INVALID if not found
var
Counter: integer;
begin
Result := INVALID;
for Counter := 0 to High(DependencyGraph) do
begin
if DependencyGraph[Counter].Node = NodeID then
if DependencyGraph[Counter].DependsOn = DepID then
begin
Result := Counter;
break;
end;
end;
end;
procedure TTopologicalSort.DelDependency(const Index: integer);
// Removes dependency from array.
// Is fastest when the dependency is near the top of the array
// as we're copying the remaining elements.
var
Counter: integer;
OriginalLength: integer;
begin
OriginalLength := Length(DependencyGraph);
if Index = OriginalLength - 1 then
begin
SetLength(DependencyGraph, OriginalLength - 1);
end;
if Index < OriginalLength - 1 then
begin
for Counter := Index to OriginalLength - 2 do
begin
DependencyGraph[Counter] := DependencyGraph[Counter + 1];
end;
SetLength(DependencyGraph, OriginalLength - 1);
end;
if Index > OriginalLength - 1 then
begin
// This could happen when deleting on an empty array:
raise Exception.Create('Tried to delete index ' + IntToStr(Index) +
' while the maximum index was ' + IntToStr(OriginalLength - 1));
end;
end;
constructor TTopologicalSort.Create;
begin
inherited Create;
end;
destructor TTopologicalSort.Destroy;
begin
// Clear up data just to make sure:
Finalize(DependencyGraph);
Finalize(Nodes);
inherited;
end;
procedure TTopologicalSort.SortOrder(var Output: TStringList);
var
Counter: integer;
NodeCounter: integer;
OutputSortOrder: integer;
DidSomething: boolean; //used to detect cycles (circular references)
Node: integer;
begin
OutputSortOrder := 0;
DidSomething := True; // prime the loop below
FCanBeSorted := True; //hope for the best.
while (DidSomething = True) do
begin
// 1. Find all nodes (now) without dependencies, output them first and remove the dependencies:
// 1.1 Nodes that are not present in the dependency graph at all:
for Counter := 0 to High(Nodes) do
begin
if DepFromNodeID(Counter) = INVALID then
begin
if DepFromDepID(Counter) = INVALID then
begin
// Node doesn't occur in either side of the dependency graph, so it has sort order 0:
DidSomething := True;
if (Nodes[Counter].Order = INVALID) or
(Nodes[Counter].Order > OutputSortOrder) then
begin
// Enter sort order if the node doesn't have a lower valid order already.
Nodes[Counter].Order := OutputSortOrder;
end;
end; //Invalid Dep
end; //Invalid Node
end; //Count
// Done with the first batch, so we can increase the sort order:
OutputSortOrder := OutputSortOrder + 1;
// 1.2 Nodes that are only present on the right hand side of the dep graph:
DidSomething := False;
// reverse order so we can delete dependencies without passing upper array
for Counter := High(DependencyGraph) downto 0 do
begin
Node := DependencyGraph[Counter].DependsOn; //the depended node
if (DepFromNodeID(Node) = INVALID) then
begin
DidSomething := True;
//Delete dependency so we don't hit it again:
DelDependency(Counter);
if (Nodes[Node].Order = INVALID) or (Nodes[Node].Order > OutputSortOrder) then
begin
// Enter sort order if the node doesn't have a lower valid order already.
Nodes[Node].Order := OutputSortOrder;
end;
end;
OutputSortOrder := OutputSortOrder + 1; //next iteration
end;
// 2. Go back to 1 until we can't do more work, and do some bookkeeping:
OutputSortOrder := OutputSortOrder + 1;
end; //outer loop for 1 to 2
OutputSortOrder := OutputSortOrder - 1; //fix unused last loop.
// 2. If we have dependencies left, we have a cycle; exit.
if (High(DependencyGraph) > 0) then
begin
FCanBeSorted := False; //indicate we have a cycle
Output.Add('Cycle (circular dependency) detected, cannot sort further. Dependencies left:');
for Counter := 0 to High(DependencyGraph) do
begin
Output.Add(SearchIndex(DependencyGraph[Counter].Node) +
' depends on: ' + SearchIndex(DependencyGraph[Counter].DependsOn));
end;
end
else
begin
// No cycle:
// Now parse results, if we have them
for Counter := 0 to OutputSortOrder do
begin
for NodeCounter := 0 to High(Nodes) do
begin
if Nodes[NodeCounter].Order = Counter then
begin
Output.Add(Nodes[NodeCounter].NodeName);
end;
end; //output each result
end; //order iteration
end; //cycle detection
end;
procedure TTopologicalSort.AddNode(NodeName: WideString);
var
NodesNewLength: integer;
begin
// Adds node; make sure we don't add duplicate entries
if SearchNode(NodeName) = INVALID then
begin
NodesNewLength := Length(Nodes) + 1;
SetLength(Nodes, NodesNewLength);
Nodes[NodesNewLength - 1].NodeName := NodeName; //Arrays are 0 based
//Nodes[NodesNewLength -1].Index := //If we change the object to a tlist or something, we already have an index property
Nodes[NodesNewLength - 1].Order := INVALID; //default value
end;
end;
procedure TTopologicalSort.AddDependency(NodeName, DependsOn: WideString);
begin
// Make sure both nodes in the dependency exist as a node
if SearchNode(NodeName) = INVALID then
begin
Self.AddNode(NodeName);
end;
if SearchNode(DependsOn) = INVALID then
begin
Self.AddNode(DependsOn);
end;
// Add the dependency, only if we don't depend on ourselves:
if NodeName <> DependsOn then
begin
SetLength(DependencyGraph, Length(DependencyGraph) + 1);
DependencyGraph[High(DependencyGraph)].Node := SearchNode(NodeName);
DependencyGraph[High(DependencyGraph)].DependsOn := SearchNode(DependsOn);
end;
end;
procedure TTopologicalSort.AddNodeDependencies(NodeAndDependencies: TStringList);
// Takes a stringlist containing a list of strings. Each string contains node names
// separated by spaces. The first node depends on the others. It is permissible to have
// only one node name, which doesn't depend on anything.
// This procedure will add the dependencies and the nodes in one go.
var
Deplist: TStringList;
StringCounter: integer;
NodeCounter: integer;
begin
if Assigned(NodeAndDependencies) then
begin
DepList := TStringList.Create;
try
for StringCounter := 0 to NodeAndDependencies.Count - 1 do
begin
// For each string in the argument: split into names, and process:
DepList.Delimiter := ' '; //use space to separate the entries
DepList.StrictDelimiter := False; //allows us to ignore double spaces in input.
DepList.DelimitedText := NodeAndDependencies[StringCounter];
for NodeCounter := 0 to DepList.Count - 1 do
begin
if NodeCounter = 0 then
begin
// Add the first node, which might be the only one.
Self.AddNode(Deplist[0]);
end;
if NodeCounter > 0 then
begin
// Only add dependency from the second item onwards
// The AddDependency code will automatically add Deplist[0] to the Nodes, if required
Self.AddDependency(DepList[0], DepList[NodeCounter]);
end;
end;
end;
finally
DepList.Free;
end;
end;
end;
procedure TTopologicalSort.DelDependency(NodeName, DependsOn: WideString);
// Delete the record.
var
NodeID: integer;
DependsID: integer;
Dependency: integer;
begin
NodeID := Self.SearchNode(NodeName);
DependsID := Self.SearchNode(DependsOn);
if (NodeID <> INVALID) and (DependsID <> INVALID) then
begin
// Look up dependency and delete it.
Dependency := Self.DepFromNodeIDDepID(NodeID, DependsID);
if (Dependency <> INVALID) then
begin
Self.DelDependency(Dependency);
end;
end;
end;
// Main program:
var
InputList: TStringList; //Lines of dependencies
TopSort: TTopologicalSort; //Topological sort object
OutputList: TStringList; //Sorted dependencies
Counter: integer;
begin
//Actual sort
InputList := TStringList.Create;
// Add rosetta code sample input separated by at least one space in the lines
InputList.Add(
'des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee');
InputList.Add('dw01 ieee dw01 dware gtech');
InputList.Add('dw02 ieee dw02 dware');
InputList.Add('dw03 std synopsys dware dw03 dw02 dw01 ieee gtech');
InputList.Add('dw04 dw04 ieee dw01 dware gtech');
InputList.Add('dw05 dw05 ieee dware');
InputList.Add('dw06 dw06 ieee dware');
InputList.Add('dw07 ieee dware');
InputList.Add('dware ieee dware');
InputList.Add('gtech ieee gtech');
InputList.Add('ramlib std ieee');
InputList.Add('std_cell_lib ieee std_cell_lib');
InputList.Add('synopsys');
TopSort := TTopologicalSort.Create;
OutputList := TStringList.Create;
try
TopSort.AddNodeDependencies(InputList); //read in nodes
TopSort.SortOrder(OutputList); //perform the sort
for Counter := 0 to OutputList.Count - 1 do
begin
writeln(OutputList[Counter]);
end;
except
on E: Exception do
begin
Writeln(stderr, 'Error: ', DateTimeToStr(Now),
': Error sorting. Technical details: ',
E.ClassName, '/', E.Message);
end;
end; //try
OutputList.Free;
TopSort.Free;
InputList.Free;
end.
|
http://rosettacode.org/wiki/Universal_Turing_machine | Universal Turing machine | One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936–1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.
Task
Simulate such a machine capable
of taking the definition of any other Turing machine and executing it.
Of course, you will not have an infinite tape,
but you should emulate this as much as is possible.
The three permissible actions on the tape are "left", "right" and "stay".
To test your universal Turing machine (and prove your programming language
is Turing complete!), you should execute the following two Turing machines
based on the following definitions.
Simple incrementer
States: q0, qf
Initial state: q0
Terminating states: qf
Permissible symbols: B, 1
Blank symbol: B
Rules:
(q0, 1, 1, right, q0)
(q0, B, 1, stay, qf)
The input for this machine should be a tape of 1 1 1
Three-state busy beaver
States: a, b, c, halt
Initial state: a
Terminating states: halt
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(a, 0, 1, right, b)
(a, 1, 1, left, c)
(b, 0, 1, left, a)
(b, 1, 1, right, b)
(c, 0, 1, left, b)
(c, 1, 1, stay, halt)
The input for this machine should be an empty tape.
Bonus:
5-state, 2-symbol probable Busy Beaver machine from Wikipedia
States: A, B, C, D, E, H
Initial state: A
Terminating states: H
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(A, 0, 1, right, B)
(A, 1, 1, left, C)
(B, 0, 1, right, C)
(B, 1, 1, right, B)
(C, 0, 1, right, D)
(C, 1, 0, left, E)
(D, 0, 1, left, A)
(D, 1, 1, left, D)
(E, 0, 1, stay, H)
(E, 1, 0, left, A)
The input for this machine should be an empty tape.
This machine runs for more than 47 millions steps.
| #Rust | Rust | use std::collections::VecDeque;
use std::fmt::{Display, Formatter, Result};
fn main() {
println!("Simple incrementer");
let rules_si = vec!(
Rule::new("q0", '1', '1', Direction::Right, "q0"),
Rule::new("q0", 'B', '1', Direction::Stay, "qf")
);
let states_si = vec!("q0", "qf");
let terminating_states_si = vec!("qf");
let permissible_symbols_si = vec!('B', '1');
let mut tm_si = TM::new(states_si, "q0", terminating_states_si, permissible_symbols_si, 'B', rules_si, "111");
while !tm_si.is_done() {
println!("{}", tm_si);
tm_si.step();
}
println!("___________________");
println!("Three-state busy beaver");
let rules_bb3 = vec!(
Rule::new("a", '0', '1', Direction::Right, "b"),
Rule::new("a", '1', '1', Direction::Left, "c"),
Rule::new("b", '0', '1', Direction::Left, "a"),
Rule::new("b", '1', '1', Direction::Right, "b"),
Rule::new("c", '0', '1', Direction::Left, "b"),
Rule::new("c", '1', '1', Direction::Stay, "halt"),
);
let states_bb3 = vec!("a", "b", "c", "halt");
let terminating_states_bb3 = vec!("halt");
let permissible_symbols_bb3 = vec!('0', '1');
let mut tm_bb3 = TM::new(states_bb3 ,"a", terminating_states_bb3, permissible_symbols_bb3, '0', rules_bb3, "0");
while !tm_bb3.is_done() {
println!("{}", tm_bb3);
tm_bb3.step();
}
println!("{}", tm_bb3);
println!("___________________");
println!("Five-state busy beaver");
let rules_bb5 = vec!(
Rule::new("A", '0', '1', Direction::Right, "B"),
Rule::new("A", '1', '1', Direction::Left, "C"),
Rule::new("B", '0', '1', Direction::Right, "C"),
Rule::new("B", '1', '1', Direction::Right, "B"),
Rule::new("C", '0', '1', Direction::Right, "D"),
Rule::new("C", '1', '0', Direction::Left, "E"),
Rule::new("D", '0', '1', Direction::Left, "A"),
Rule::new("D", '1', '1', Direction::Left, "D"),
Rule::new("E", '0', '1', Direction::Stay, "H"),
Rule::new("E", '1', '0', Direction::Left, "A"),
);
let states_bb5 = vec!("A", "B", "C", "D", "E", "H");
let terminating_states_bb5 = vec!("H");
let permissible_symbols_bb5 = vec!('0', '1');
let mut tm_bb5 = TM::new(states_bb5 ,"A", terminating_states_bb5, permissible_symbols_bb5, '0', rules_bb5, "0");
let mut steps = 0;
while !tm_bb5.is_done() {
tm_bb5.step();
steps += 1;
}
println!("Steps: {}", steps);
println!("Band lenght: {}", tm_bb5.band.len());
}
struct TM<'a> {
state: &'a str,
terminating_states: Vec<&'a str>,
rules: Vec<Rule<'a>>,
band: VecDeque<char>,
head: usize,
blank: char,
}
struct Rule<'a> {
state: &'a str,
read: char,
write: char,
dir: Direction,
new_state: &'a str,
}
enum Direction{
Left,
Right,
Stay,
}
impl<'a> TM<'a> {
fn new(_states: Vec<&'a str>, initial_state: &'a str, terminating_states: Vec<&'a str>, _permissible_symbols: Vec<char>, blank: char, rules: Vec<Rule<'a>>, input: &str) -> Self {
Self { state: initial_state, terminating_states, rules, band: input.chars().collect::<VecDeque<_>>(), head: 0, blank }
}
fn is_done(&self) -> bool {
self.terminating_states.contains(&self.state)
}
fn step(&mut self) {
let field = self.band.get(self.head).unwrap();
let rule = self.rules.iter().find(|rule| rule.state == self.state && &rule.read == field).unwrap();
let field = self.band.get_mut(self.head).unwrap();
*field = rule.write;
self.state = rule.new_state;
match rule.dir {
Direction::Left => {
if self.head == 0 {
self.band.push_front(self.blank)
} else {
self.head -= 1;
}
},
Direction::Right => {
if self.head == self.band.len() - 1 {
self.band.push_back(self.blank)
}
self.head += 1;
},
Direction::Stay => {},
}
}
}
impl<'a> Display for TM<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let band = self.band.iter().enumerate().map(|(i, c)| {
if i == self.head {
format!("[{}]", c)
} else {
format!(" {} ", c)
}
}).fold(String::new(), |acc, val| acc + &val);
write!(f, "{}\t{}", self.state, band)
}
}
impl<'a> Rule<'a> {
fn new(state: &'a str, read: char, write: char, dir: Direction, new_state: &'a str) -> Self {
Self { state, read, write, dir, new_state }
}
}
|
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positive integer n that are relatively prime to n
counts the integers k in the range 1 ≤ k ≤ n for which the greatest common divisor gcd(n,k) is equal to 1
counts numbers ≤ n and prime to n
If the totient number (for N) is one less than N, then N is prime.
Task
Create a totient function and:
Find and display (1 per line) for the 1st 25 integers:
the integer (the index)
the totient number for that integer
indicate if that integer is prime
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000 (optional)
Show all output here.
Related task
Perfect totient numbers
Also see
Wikipedia: Euler's totient function.
MathWorld: totient function.
OEIS: Euler totient function phi(n).
| #Scala | Scala | @tailrec
def gcd(a: Int, b: Int): Int = if(b == 0) a else gcd(b, a%b)
def totientLaz(num: Int): Int = LazyList.range(2, num).count(gcd(num, _) == 1) + 1 |
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #Kotlin | Kotlin | // version 1.1.2
import java.lang.Math.*
fun main(args: Array<String>) {
val radians = Math.PI / 4.0
val degrees = 45.0
val conv = Math.PI / 180.0
val f = "%1.15f"
var inverse: Double
println(" Radians Degrees")
println("Angle : ${f.format(radians)}\t ${f.format(degrees)}\n")
println("Sin : ${f.format(sin(radians))}\t ${f.format(sin(degrees * conv))}")
println("Cos : ${f.format(cos(radians))}\t ${f.format(cos(degrees * conv))}")
println("Tan : ${f.format(tan(radians))}\t ${f.format(tan(degrees * conv))}\n")
inverse = asin(sin(radians))
println("ASin(Sin) : ${f.format(inverse)}\t ${f.format(inverse / conv)}")
inverse = acos(cos(radians))
println("ACos(Cos) : ${f.format(inverse)}\t ${f.format(inverse / conv)}")
inverse = atan(tan(radians))
println("ATan(Tan) : ${f.format(inverse)}\t ${f.format(inverse / conv)}")
} |
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 739, 73, and 7 formed by removing digits from its right are also prime.
No zeroes are allowed in truncatable primes.
Task
The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied).
Related tasks
Find largest left truncatable prime in a given base
Sieve of Eratosthenes
See also
Truncatable Prime from MathWorld.]
| #VBScript | VBScript |
start_time = Now
lt = 0
rt = 0
For h = 1 To 1000000
If IsLeftTruncatable(h) And h > lt Then
lt = h
End If
If IsRightTruncatable(h) And h > rt Then
rt = h
End If
Next
end_time = now
WScript.StdOut.WriteLine "Largest LTP from 1..1000000: " & lt
WScript.StdOut.WriteLine "Largest RTP from 1..1000000: " & rt
WScript.StdOut.WriteLine "Elapse Time(seconds) : " & DateDiff("s",start_time,end_time)
'------------
Function IsLeftTruncatable(n)
IsLeftTruncatable = False
c = 0
For i = Len(n) To 1 Step -1
If InStr(1,n,"0") > 0 Then
Exit For
End If
If IsPrime(Right(n,i)) Then
c = c + 1
End If
Next
If c = Len(n) Then
IsLeftTruncatable = True
End If
End Function
Function IsRightTruncatable(n)
IsRightTruncatable = False
c = 0
For i = Len(n) To 1 Step -1
If InStr(1,n,"0") > 0 Then
Exit For
End If
If IsPrime(Left(n,i)) Then
c = c + 1
End If
Next
If c = Len(n) Then
IsRightTruncatable = True
End If
End Function
Function IsPrime(n)
If n = 2 Then
IsPrime = True
ElseIf n <= 1 Or n Mod 2 = 0 Then
IsPrime = False
Else
IsPrime = True
For i = 3 To Int(Sqr(n)) Step 2
If n Mod i = 0 Then
IsPrime = False
Exit For
End If
Next
End If
End Function
|
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #FunL | FunL | data Tree = Empty | Node( value, left, right )
def
preorder( Empty ) = []
preorder( Node(v, l, r) ) = [v] + preorder( l ) + preorder( r )
inorder( Empty ) = []
inorder( Node(v, l, r) ) = inorder( l ) + [v] + inorder( r )
postorder( Empty ) = []
postorder( Node(v, l, r) ) = postorder( l ) + postorder( r ) + [v]
levelorder( x ) =
def
order( [] ) = []
order( Empty : xs ) = order( xs )
order( Node(v, l, r) : xs ) = v : order( xs + [l, r] )
order( [x] )
tree = Node( 1,
Node( 2,
Node( 4,
Node( 7, Empty, Empty ),
Empty ),
Node( 5, Empty, Empty ) ),
Node( 3,
Node( 6,
Node( 8, Empty, Empty ),
Node( 9, Empty, Empty ) ),
Empty ) )
println( preorder(tree) )
println( inorder(tree) )
println( postorder(tree) )
println( levelorder(tree) ) |
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
| #Forth | Forth | : split ( str len separator len -- tokens count )
here >r 2swap
begin
2dup 2, \ save this token ( addr len )
2over search \ find next separator
while
dup negate here 2 cells - +! \ adjust last token length
2over nip /string \ start next search past separator
repeat
2drop 2drop
r> here over - ( tokens length )
dup negate allot \ reclaim dictionary
2 cells / ; \ turn byte length into token count
: .tokens ( tokens count -- )
1 ?do dup 2@ type ." ." cell+ cell+ loop 2@ type ;
s" Hello,How,Are,You,Today" s" ," split .tokens \ 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
| #Fortran | Fortran | PROGRAM Example
CHARACTER(23) :: str = "Hello,How,Are,You,Today"
CHARACTER(5) :: word(5)
INTEGER :: pos1 = 1, pos2, n = 0, i
DO
pos2 = INDEX(str(pos1:), ",")
IF (pos2 == 0) THEN
n = n + 1
word(n) = str(pos1:)
EXIT
END IF
n = n + 1
word(n) = str(pos1:pos1+pos2-2)
pos1 = pos2+pos1
END DO
DO i = 1, n
WRITE(*,"(2A)", ADVANCE="NO") TRIM(word(i)), "."
END DO
END PROGRAM Example |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Janet | Janet | (defmacro time
"Print the time it takes to evaluate body to stderr.\n
Evaluates to body."
[body]
(with-syms [$start $val]
~(let [,$start (os/clock)
,$val ,body]
(eprint (- (os/clock) ,$start))
,$val)))
(time (os/sleep 0.5)) |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Java | Java | import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
public class TimeIt {
public static void main(String[] args) {
final ThreadMXBean threadMX = ManagementFactory.getThreadMXBean();
assert threadMX.isCurrentThreadCpuTimeSupported();
threadMX.setThreadCpuTimeEnabled(true);
long start, end;
start = threadMX.getCurrentThreadCpuTime();
countTo(100000000);
end = threadMX.getCurrentThreadCpuTime();
System.out.println("Counting to 100000000 takes "+(end-start)/1000000+"ms");
start = threadMX.getCurrentThreadCpuTime();
countTo(1000000000L);
end = threadMX.getCurrentThreadCpuTime();
System.out.println("Counting to 1000000000 takes "+(end-start)/1000000+"ms");
}
public static void countTo(long x){
System.out.println("Counting...");
for(long i=0;i<x;i++);
System.out.println("Done!");
}
} |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
Find the top N salaries in each department, where N is provided as a parameter.
Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:
Employee Name,Employee ID,Salary,Department
Tyler Bennett,E10297,32000,D101
John Rappl,E21437,47000,D050
George Woltman,E00127,53500,D101
Adam Smith,E63535,18000,D202
Claire Buckman,E39876,27800,D202
David McClellan,E04242,41500,D101
Rich Holcomb,E01234,49500,D202
Nathan Adams,E41298,21900,D050
Richard Potter,E43128,15900,D101
David Motsinger,E27002,19250,D202
Tim Sampair,E03033,27000,D101
Kim Arlich,E10001,57000,D190
Timothy Grove,E16398,29900,D190
| #Haskell | Haskell | import Data.List (sortBy, groupBy)
import Text.Printf (printf)
import Data.Ord (comparing)
import Data.Function (on)
type ID = Int
type DEP = String
type NAME = String
type SALARY = Double
data Employee = Employee
{ nr :: ID
, dep :: DEP
, name :: NAME
, sal :: SALARY
}
employees :: [Employee]
employees =
fmap
(\(i, d, n, s) -> Employee i d n s)
[ (1001, "AB", "Janssen A.H.", 41000)
, (101, "KA", "'t Woud B.", 45000)
, (1013, "AB", "de Bont C.A.", 65000)
, (1101, "CC", "Modaal A.M.J.", 30000)
, (1203, "AB", "Anders H.", 50000)
, (100, "KA", "Ezelbips P.J.", 52000)
, (1102, "CC", "Zagt A.", 33000)
, (1103, "CC", "Ternood T.R.", 21000)
, (1104, "CC", "Lageln M.", 23000)
, (1105, "CC", "Amperwat A.", 19000)
, (1106, "CC", "Boon T.J.", 25000)
, (1107, "CC", "Beloop L.O.", 31000)
, (1009, "CD", "Janszoon A.", 38665)
, (1026, "CD", "Janszen H.P.", 41000)
, (1011, "CC", "de Goeij J.", 39000)
, (106, "KA", "Pragtweik J.M.V.", 42300)
, (111, "KA", "Bakeuro S.", 31000)
, (105, "KA", "Clubdrager C.", 39800)
, (104, "KA", "Karendijk F.", 23000)
, (107, "KA", "Centjes R.M.", 34000)
, (119, "KA", "Tegenstroom H.L.", 39000)
, (1111, "CD", "Telmans R.M.", 55500)
, (1093, "AB", "de Slegte S.", 46987)
, (1199, "CC", "Uitlaat G.A.S.", 44500)
]
firstN :: Int
-> (Employee -> DEP)
-> (Employee -> SALARY)
-> [Employee]
-> [[Employee]]
firstN n o1 o2 x =
fmap
(take n . sortBy (comparingDown o2))
(groupBy (groupingOn o1) (sortBy (comparing o1) x))
groupingOn
:: Eq a1
=> (a -> a1) -> a -> a -> Bool
groupingOn = ((==) `on`)
comparingDown
:: Ord a
=> (b -> a) -> b -> b -> Ordering
comparingDown = flip . comparing
main :: IO ()
main = do
printf "%-16s %3s %10s\n" "NAME" "DEP" "TIP"
putStrLn $ replicate 31 '='
mapM_ (traverse ((printf "%-16s %3s %10.2g\n" . name) <*> dep <*> sal)) $
firstN 3 dep sal employees |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #Fortran | Fortran |
! This is a fortran95 implementation of the game of tic-tac-toe.
! - Objective was to use less than 100 lines.
! - No attention has been devoted to efficiency.
! - Indentation by findent: https://sourceforge.net/projects/findent/
! - This is free software, use as you like at own risk.
! - Compile: gfortran -o tictactoe tictactoe.f90
! - Run: ./tictactoe
! Comments to: wvermin at gmail dot com
module tic
implicit none
integer :: b(9)
contains
logical function iswin(p)
integer,intent(in) :: p
iswin = &
all(b([1,2,3])==p).or.all(b([4,5,6])==p).or.all(b([7,8,9])==p).or.&
all(b([1,4,7])==p).or.all(b([2,5,8])==p).or.all(b([3,6,9])==p).or.&
all(b([1,5,9])==p).or.all(b([3,5,7])==p)
end function iswin
subroutine printb(mes)
character(len=*) :: mes
integer :: i,j
character :: s(0:2) = ['.','X','O']
print "(3a3,' ',3i3)",(s(b(3*i+1:3*i+3)),(j,j=3*i+1,3*i+3),i=0,2)
if(mes /= ' ') print "(/,a)",mes
end subroutine printb
integer recursive function minmax(player,bestm) result(bestv)
integer :: player,bestm,move,v,bm,win=1000,inf=100000
real :: x
if (all(b .ne. 0)) then
bestv = 0
else
bestv = -inf
do move=1,9
if (b(move) == 0) then
b(move) = player
if (iswin(player)) then
v = win
else
call random_number(x)
v = -minmax(3-player,bm) - int(10*x)
endif
if (v > bestv) then
bestv = v
bestm = move
endif
b(move) = 0
if (v == win) exit
endif
enddo
endif
end function minmax
end module tic
program tictactoe
! computer: player=1, user: player=2
use tic
implicit none
integer :: move,ios,v,bestmove,ply,player=2,k,values(8)
integer,allocatable :: seed(:)
call date_and_time(values=values)
call random_seed(size=k)
allocate(seed(k))
seed = values(8)+1000*values(7)+60*1000*values(6)+60*60*1000*values(5)
call random_seed(put=seed)
mainloop: do
b = 0
call printb('You have O, I have X. You enter 0: game ends.')
plyloop: do ply=0,4
if (player == 2 .or. ply >0 ) then ! user move
write(*,"(/,a)",advance='no'),'Your move? (0..9) '
getloop: do
readloop: do
read (*,*,iostat=ios),move
if (ios == 0 .and. move >= 0 .and. move <= 9) exit readloop
write(*,"(a)",advance='no'),'huh? Try again (0..9): '
enddo readloop
if ( move == 0) exit mainloop
if (b(move) == 0) exit getloop
write(*,"(a)",advance='no'),'Already occupied, again (0..9): '
enddo getloop
b(move) = 2
if(iswin(2)) then ! this should not happen
call printb('***** You win *****')
exit plyloop
endif
endif
v = minmax(1,bestmove) ! computer move
b(bestmove) = 1
if(iswin(1)) then
call printb('***** I win *****')
exit plyloop
endif
write(*,"(/,a,i3)"), 'My move: ',bestmove
call printb(' ')
enddo plyloop
if(ply == 5) write(*,"('***** Draw *****',/)")
player = 3-player
enddo mainloop
end program
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Common_Lisp | Common Lisp | (defun move (n from to via)
(cond ((= n 1)
(format t "Move from ~A to ~A.~%" from to))
(t
(move (- n 1) from via to)
(format t "Move from ~A to ~A.~%" from to)
(move (- n 1) via to from)))) |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #Ring | Ring |
tm = "0"
see tm
for n = 1 to 6
tm = thue_morse(tm)
see tm
next
func thue_morse(previous)
tm = ""
for i = 1 to len(previous)
if (substr(previous, i, 1) = "1") tm = tm + "0" else tm = tm + "1" ok
next
see nl
return (previous + tm)
|
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #Ruby | Ruby | puts s = "0"
6.times{puts s << s.tr("01","10")} |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #Rust | Rust | const ITERATIONS: usize = 8;
fn neg(sequence: &String) -> String {
sequence.chars()
.map(|ch| {
(1 - ch.to_digit(2).unwrap()).to_string()
})
.collect::<String>()
}
fn main() {
let mut sequence: String = String::from("0");
for i in 0..ITERATIONS {
println!("{}: {}", i + 1, sequence);
sequence = format!("{}{}", sequence, neg(&sequence));
}
} |
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were separated by the separators, become the elements of the output list.
Empty fields should be preserved, even at the start and end.
Rules for escaping:
"Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.
When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special).
Each occurrence of the escape character that was used to escape something, should not become part of the output.
Test case
Demonstrate that your function satisfies the following test-case:
Input
Output
string:
one^|uno||three^^^^|four^^^|^cuatro|
separator character:
|
escape character:
^
one|uno
three^^
four^|cuatro
(Print the output list in any format you like, as long as it is it easy to see what the fields are.)
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
| #Simula | Simula |
SIMSET
BEGIN
LINK CLASS ITEM(TXT); TEXT TXT;;
REF(HEAD) PROCEDURE SPLIT(TXT, SEP, ESC); TEXT TXT; CHARACTER SEP, ESC;
BEGIN
REF(HEAD) PARTS;
CHARACTER CH;
TEXT PART;
PART :- BLANKS(TXT.LENGTH);
PARTS :- NEW HEAD;
TXT.SETPOS(1);
WHILE TXT.MORE DO BEGIN
CH := TXT.GETCHAR;
IF CH = ESC THEN BEGIN
IF TXT.MORE THEN BEGIN
CH := TXT.GETCHAR;
PART.PUTCHAR(CH);
END ELSE BEGIN
ERROR("SPLIT: ESCAPE CHAR AT END OF STRING");
END;
END ELSE IF CH = SEP THEN BEGIN
NEW ITEM(COPY(PART.SUB(1,PART.POS-1))).INTO(PARTS);
PART.SETPOS(1);
END ELSE BEGIN
PART.PUTCHAR(CH);
END;
END;
NEW ITEM(COPY(PART.SUB(1,PART.POS-1))).INTO(PARTS);
SPLIT :- PARTS;
END SPLIT;
TEXT EXAMPLE;
REF(HEAD) RESULT;
REF(ITEM) PART;
INTEGER NO;
FOR EXAMPLE :- "ONE^|UNO||THREE^^^^|FOUR^^^|^CUATRO|" DO
BEGIN
OUTTEXT("INPUT: '");
OUTTEXT(EXAMPLE);
OUTTEXT("'");
OUTIMAGE;
RESULT :- SPLIT(EXAMPLE, '|', '^');
PART :- RESULT.FIRST;
NO := 0;
WHILE PART =/= NONE DO
BEGIN
NO := NO + 1;
OUTTEXT("PART");
OUTINT(NO, 0);
OUTTEXT(": '");
OUTTEXT(PART.TXT);
OUTTEXT("'");
OUTIMAGE;
PART :- PART.SUC;
END;
END;
END.
|
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were separated by the separators, become the elements of the output list.
Empty fields should be preserved, even at the start and end.
Rules for escaping:
"Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.
When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special).
Each occurrence of the escape character that was used to escape something, should not become part of the output.
Test case
Demonstrate that your function satisfies the following test-case:
Input
Output
string:
one^|uno||three^^^^|four^^^|^cuatro|
separator character:
|
escape character:
^
one|uno
three^^
four^|cuatro
(Print the output list in any format you like, as long as it is it easy to see what the fields are.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #SNOBOL4 | SNOBOL4 |
* Program: tokenize_with_escape.sbl
* To run: sbl tokenize_with_escape.sbl
* Description: Tokenize a string with escaping
* Comment: Tested using the Spitbol for Linux version of SNOBOL4
lf = substr(&alphabet,11,1) ;* New line or line feed
* Function tokenize will break parts out of a string, which are
* separated by c, which defaults to a comma, into
* an array. Parameter kp=1 to keep null parts, which is the default,
* and 0 to discard.
define('tokenize(s,c,kp)tokenizepat,part,t,i,j')
:(tokenize_end)
tokenize
c = (ident(c) ',', substr(c,1,1)) :f(freturn)
kp = (ident(kp) 1, eq(kp,0) 0, 1) :f(freturn)
t = table()
tokenizepat = breakx(c) . part c | (len(1) rem) . part
s ? eq(kp,1) rtab(1) c = s c
tokenize1
s ? tokenizepat = "" :f(tokenize2)
t[i = eq(kp,0) differ(part) i + 1] = part
t[i = eq(kp,1) i + 1] = part
:(tokenize1)
tokenize2
tokenize = array(i) :f(errr)
j = 0
tokenize3 tokenize[j = lt(j,i) j + 1] = t[j] :s(tokenize3)
:(return)
tokenize_end
* Function tokcan will a normalize a string by applying separator and escape
* rules to string ts. Parameter sep is the separator, while esc is the escape
* character. Parameter tesc is the new separator character to substitute for
* parameter sep. It defaults to a comma, ",".
define('tokcan(ts,sep,esc,tesc)tpat,part1,part2,notany') :(tokcan_end)
tokcan
tesc = (ident(tesc) ',', substr(tesc,1,1))
tpat = (breakx(sep esc) . part1
+ (sep | esc sep | esc esc | (esc len(1) . notany)) . part2
+ )
+ | (len(1) rem) . part1
tokcan1
ts ? tpat = :f(tokcan2)
part2 = (leq(part2,sep) tesc
+ ,leq(part2,esc sep) sep
+ ,leq(part2,esc esc) esc
+ ,differ(notany) leq(part2,esc notany) notany
+ )
tokcan = (ident(tokcan) "", tokcan) part1 part2
:(tokcan1)
tokcan2
:(return)
tokcan_end
test_string = "one^|uno||three^^^^|four^^^|^cuatro|"
sep = "|"
esc = "^"
hline = tokcan(test_string,sep,esc) :f(err)
output = " Input: " test_string lf
output = "Output1: " hline lf
output = "Output2: "
tokenized = tokenize(hline,",")
p1 output = "'" tokenized[z = z + 1] "'" :s(p1)
END
|
http://rosettacode.org/wiki/Topological_sort | Topological sort |
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
O(n logn) sorts
Heap sort |
Merge sort |
Patience sort |
Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
Given a mapping between items, and items they depend on, a topological sort orders items so that no item precedes an item it depends upon.
The compiling of a library in the VHDL language has the constraint that a library must be compiled after any library it depends on.
A tool exists that extracts library dependencies.
Task
Write a function that will return a valid compile order of VHDL libraries from their dependencies.
Assume library names are single words.
Items mentioned as only dependents, (sic), have no dependents of their own, but their order of compiling must be given.
Any self dependencies should be ignored.
Any un-orderable dependencies should be flagged.
Use the following data as an example:
LIBRARY LIBRARY DEPENDENCIES
======= ====================
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys
Note: the above data would be un-orderable if, for example, dw04 is added to the list of dependencies of dw01.
C.f.
Topological sort/Extracted top item.
There are two popular algorithms for topological sorting:
Kahn's 1962 topological sort [1]
depth-first search [2] [3]
| #OCaml | OCaml | let dep_libs = [
("des_system_lib", ["std"; "synopsys"; "std_cell_lib"; "des_system_lib"; "dw02"; "dw01"; "ramlib"; "ieee"]);
("dw01", (*"dw04"::*)["ieee"; "dw01"; "dware"; "gtech"]);
("dw02", ["ieee"; "dw02"; "dware"]);
("dw03", ["std"; "synopsys"; "dware"; "dw03"; "dw02"; "dw01"; "ieee"; "gtech"]);
("dw04", ["dw04"; "ieee"; "dw01"; "dware"; "gtech"]);
("dw05", ["dw05"; "ieee"; "dware"]);
("dw06", ["dw06"; "ieee"; "dware"]);
("dw07", ["ieee"; "dware"]);
("dware", ["ieee"; "dware"]);
("gtech", ["ieee"; "gtech"]);
("ramlib", ["std"; "ieee"]);
("std_cell_lib", ["ieee"; "std_cell_lib"]);
("synopsys", []);
]
let dep_libs =
let f (lib, deps) = (* remove self dependency *)
(lib,
List.filter (fun d -> d <> lib) deps) in
List.map f dep_libs
let rev_unique =
List.fold_left (fun acc x -> if List.mem x acc then acc else x::acc) []
let libs = (* list items, each being unique *)
rev_unique (List.flatten(List.map (fun (lib, deps) -> lib::deps) dep_libs))
let get_deps lib =
try (List.assoc lib dep_libs)
with Not_found -> []
let res =
let rec aux acc later todo progress =
match todo, later with
| [], [] -> (List.rev acc)
| [], _ ->
if progress
then aux acc [] later false
else invalid_arg "un-orderable data"
| x::xs, _ ->
let deps = get_deps x in
let ok = List.for_all (fun dep -> List.mem dep acc) deps in
if ok
then aux (x::acc) later xs true
else aux acc (x::later) xs progress
in
let starts, todo = List.partition (fun lib -> get_deps lib = []) libs in
aux starts [] todo false
let () =
print_string "result: \n ";
print_endline (String.concat ", " res);
;; |
http://rosettacode.org/wiki/Universal_Turing_machine | Universal Turing machine | One of the foundational mathematical constructs behind computer science
is the universal Turing Machine.
(Alan Turing introduced the idea of such a machine in 1936–1937.)
Indeed one way to definitively prove that a language
is turing-complete
is to implement a universal Turing machine in it.
Task
Simulate such a machine capable
of taking the definition of any other Turing machine and executing it.
Of course, you will not have an infinite tape,
but you should emulate this as much as is possible.
The three permissible actions on the tape are "left", "right" and "stay".
To test your universal Turing machine (and prove your programming language
is Turing complete!), you should execute the following two Turing machines
based on the following definitions.
Simple incrementer
States: q0, qf
Initial state: q0
Terminating states: qf
Permissible symbols: B, 1
Blank symbol: B
Rules:
(q0, 1, 1, right, q0)
(q0, B, 1, stay, qf)
The input for this machine should be a tape of 1 1 1
Three-state busy beaver
States: a, b, c, halt
Initial state: a
Terminating states: halt
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(a, 0, 1, right, b)
(a, 1, 1, left, c)
(b, 0, 1, left, a)
(b, 1, 1, right, b)
(c, 0, 1, left, b)
(c, 1, 1, stay, halt)
The input for this machine should be an empty tape.
Bonus:
5-state, 2-symbol probable Busy Beaver machine from Wikipedia
States: A, B, C, D, E, H
Initial state: A
Terminating states: H
Permissible symbols: 0, 1
Blank symbol: 0
Rules:
(A, 0, 1, right, B)
(A, 1, 1, left, C)
(B, 0, 1, right, C)
(B, 1, 1, right, B)
(C, 0, 1, right, D)
(C, 1, 0, left, E)
(D, 0, 1, left, A)
(D, 1, 1, left, D)
(E, 0, 1, stay, H)
(E, 1, 0, left, A)
The input for this machine should be an empty tape.
This machine runs for more than 47 millions steps.
| #Scala | Scala |
package utm.scala
import scala.annotation.tailrec
import scala.language.implicitConversions
/**
* Implementation of Universal Turing Machine in Scala that can simulate an arbitrary
* Turing machine on arbitrary input
*
* @author Abdulla Abdurakhmanov (https://github.com/abdolence/utms)
*/
class UniversalTuringMachine[S](
val rules: List[UTMRule[S]],
val initialState: S,
val finalStates: Set[S],
val blankSymbol: String,
val inputTapeVals: Iterable[String],
printEveryIter: Int = 1
) {
private val initialTape = UTMTape( inputTapeVals.toVector, 0, blankSymbol )
@tailrec
private def iterate( state: S, curIteration: Int, tape: UTMTape ): UTMTape = {
if (curIteration % printEveryIter == 0) {
print( s"${curIteration}: ${state}: " )
tape.printTape()
}
if (finalStates.contains( state )) {
println( s"Finished in the final state: ${state}" )
tape.printTape()
tape
} else {
rules.find(rule => rule.state == state && rule.fromSymbol == tape.current() ) match {
case Some( rule ) => {
val updatedTape = tape.updated( rule.toSymbol, rule.action )
iterate( rule.toState, curIteration + 1, updatedTape )
}
case _ => {
println(
s"Finished: no suitable rules found for ${state}/${tape.current()}"
)
tape.printTape()
tape
}
}
}
}
def run(): UTMTape =
iterate( state = initialState, curIteration = 0, tape = initialTape )
}
/**
* Universal Turing Machine actions
*/
sealed trait UTMAction
object UTMAction {
case object left extends UTMAction
case object right extends UTMAction
case object stay extends UTMAction
}
/**
* Universal Turing Machine rule definition
*/
case class UTMRule[S]( state: S, fromSymbol: String, toSymbol: String, action: UTMAction, toState: S )
object UTMRule {
implicit def tupleToUTMLRule[S](
tuple: ( S, String, String, UTMAction, S )
): UTMRule[S] =
UTMRule[S]( tuple._1, tuple._2, tuple._3, tuple._4, tuple._5 )
}
/**
* Universal Turing Machine Tape
*/
case class UTMTape( content: Vector[String], position: Int, blankSymbol: String ) {
private def updateContentAtPos( symbol: String ) = {
if (position >= content.length) {
content :+ symbol
} else if (position < 0) {
symbol +: content
} else if (content( position ) != symbol)
content.updated( position, symbol )
else
content
}
private[scala] def updated( symbol: String, action: UTMAction ): UTMTape = {
val updatedTape =
this.copy( content = updateContentAtPos( symbol ), position = action match {
case UTMAction.left => position - 1
case UTMAction.right => position + 1
case UTMAction.stay => position
} )
if (updatedTape.position < 0) {
updatedTape.copy(
content = blankSymbol +: updatedTape.content,
position = 0
)
} else if (updatedTape.position >= updatedTape.content.length) {
updatedTape.copy( content = updatedTape.content :+ blankSymbol )
} else
updatedTape
}
private[scala] def current(): String = {
if (content.isDefinedAt( position ))
content( position )
else
blankSymbol
}
def printTape(): Unit = {
print( "[" )
if (position < 0)
print( "˅" )
content.zipWithIndex.foreach {
case ( symbol, index ) =>
if (position == index)
print( "˅" )
else
print( " " )
print( s"$symbol" )
}
if (position >= content.length)
print( "˅" )
println( "]" )
}
}
object UniversalTuringMachine extends App {
main()
def main(): Unit = {
import UTMAction._
def createIncrementMachine() = {
sealed trait IncrementStates
case object q0 extends IncrementStates
case object qf extends IncrementStates
new UniversalTuringMachine[IncrementStates](
rules = List( ( q0, "1", "1", right, q0 ), ( q0, "B", "1", stay, qf ) ),
initialState = q0,
finalStates = Set( qf ),
blankSymbol = "B",
inputTapeVals = Seq( "1", "1", "1" )
).run()
}
def createThreeStateBusyBeaver() = {
sealed trait ThreeStateBusyStates
case object a extends ThreeStateBusyStates
case object b extends ThreeStateBusyStates
case object c extends ThreeStateBusyStates
case object halt extends ThreeStateBusyStates
new UniversalTuringMachine[ThreeStateBusyStates](
rules = List(
( a, "0", "1", right, b ),
( a, "1", "1", left, c ),
( b, "0", "1", left, a ),
( b, "1", "1", right, b ),
( c, "0", "1", left, b ),
( c, "1", "1", stay, halt )
),
initialState = a,
finalStates = Set( halt ),
blankSymbol = "0",
inputTapeVals = Seq()
).run()
}
def createFiveState2SymBusyBeaverMachine() = {
sealed trait FiveBeaverStates
case object FA extends FiveBeaverStates
case object FB extends FiveBeaverStates
case object FC extends FiveBeaverStates
case object FD extends FiveBeaverStates
case object FE extends FiveBeaverStates
case object FH extends FiveBeaverStates
new UniversalTuringMachine[FiveBeaverStates](
rules = List(
( FA, "0", "1", right, FB ),
( FA, "1", "1", left, FC ),
( FB, "0", "1", right, FC ),
( FB, "1", "1", right, FB ),
( FC, "0", "1", right, FD ),
( FC, "1", "0", left, FE ),
( FD, "0", "1", left, FA ),
( FD, "1", "1", left, FD ),
( FE, "0", "1", stay, FH ),
( FE, "1", "0", left, FA )
),
initialState = FA,
finalStates = Set( FH ),
blankSymbol = "0",
inputTapeVals = Seq(),
printEveryIter = 100000
).run()
}
createIncrementMachine()
createThreeStateBusyBeaver()
// careful here, 47 mln iterations
createFiveState2SymBusyBeaverMachine()
}
}
|
http://rosettacode.org/wiki/Totient_function | Totient function | The totient function is also known as:
Euler's totient function
Euler's phi totient function
phi totient function
Φ function (uppercase Greek phi)
φ function (lowercase Greek phi)
Definitions (as per number theory)
The totient function:
counts the integers up to a given positive integer n that are relatively prime to n
counts the integers k in the range 1 ≤ k ≤ n for which the greatest common divisor gcd(n,k) is equal to 1
counts numbers ≤ n and prime to n
If the totient number (for N) is one less than N, then N is prime.
Task
Create a totient function and:
Find and display (1 per line) for the 1st 25 integers:
the integer (the index)
the totient number for that integer
indicate if that integer is prime
Find and display the count of the primes up to 100
Find and display the count of the primes up to 1,000
Find and display the count of the primes up to 10,000
Find and display the count of the primes up to 100,000 (optional)
Show all output here.
Related task
Perfect totient numbers
Also see
Wikipedia: Euler's totient function.
MathWorld: totient function.
OEIS: Euler totient function phi(n).
| #Shale | Shale | #!/usr/local/bin/shale
primes library
init dup var {
pl sieve type primes::()
100000 0 pl generate primes::()
} =
go dup var {
i var
c0 var
c1 var
c2 var
c3 var
p var
" N Phi Is prime" println
i 1 =
{ i 25 <= } {
i pl isprime primes::() { "True" } { "False" } if i pl phi primes::() i "%2d %3d %s\n" printf
i++
} while
c0 0 =
c1 0 =
c2 0 =
c3 0 =
i 0 =
{ i count pl:: < } {
p i pl get primes::() =
p 100 < { c0++ } ifthen
p 1000 < { c1++ } ifthen
p 10000 < { c2 ++ } ifthen
p 100000 < { c3 ++ } ifthen
i++
} while
"" println
" Limit Count" println
c0 " 100 %5d\n" printf
c1 " 1,000 %5d\n" printf
c2 " 10,000 %5d\n" printf
c3 "100,000 %5d\n" printf
} =
init()
go()
|
http://rosettacode.org/wiki/Trigonometric_functions | Trigonometric functions | Task
If your language has a library or built-in functions for trigonometry, show examples of:
sine
cosine
tangent
inverses (of the above)
using the same angle in radians and degrees.
For the non-inverse functions, each radian/degree pair should use arguments that evaluate to the same angle (that is, it's not necessary to use the same angle for all three regular functions as long as the two sine calls use the same angle).
For the inverse functions, use the same number and convert its answer to radians and degrees.
If your language does not have trigonometric functions available or only has some available, write functions to calculate the functions based on any known approximation or identity.
| #Lambdatalk | Lambdatalk |
{def deg2rad {lambda {:d} {* {/ {PI} 180} :d}}}
-> deg2rad
{def rad2deg {lambda {:r} {* {/ 180 {PI}} :r}}}
-> rad2deg
{deg2rad 180}
-> 3.141592653589793 = PI
{rad2deg {PI}}°
-> 180°
{sin {deg2rad 45}}
-> 0.7071067811865475 = PI/4
{cos {deg2rad 45}}
-> 0.7071067811865476 = PI/4
{tan {deg2rad 45}}
-> 0.9999999999999999 = 1
{rad2deg {asin 0.5}}° -> 30.000000000000004°
{rad2deg {acos 0.5}}° -> 60.00000000000001°
{rad2deg {atan 1}}° -> 45°
|
http://rosettacode.org/wiki/Truncatable_primes | Truncatable primes | A truncatable prime is a prime number that when you successively remove digits from one end of the prime, you are left with a new prime number.
Examples
The number 997 is called a left-truncatable prime as the numbers 997, 97, and 7 are all prime.
The number 7393 is a right-truncatable prime as the numbers 7393, 739, 73, and 7 formed by removing digits from its right are also prime.
No zeroes are allowed in truncatable primes.
Task
The task is to find the largest left-truncatable and right-truncatable primes less than one million (base 10 is implied).
Related tasks
Find largest left truncatable prime in a given base
Sieve of Eratosthenes
See also
Truncatable Prime from MathWorld.]
| #Wren | Wren | import "/fmt" for Fmt
import "/math" for Int
var limit = 999999
var c = Int.primeSieve(limit, false)
var leftFound = false
var rightFound = false
System.print("Largest truncatable primes less than a million:")
var i = limit
while (i > 2) {
if (!c[i]) {
if (!rightFound) {
var p = (i/10).floor
while (p > 0) {
if (p%2 == 0 || c[p]) break
p = (p/10).floor
}
if (p == 0) {
System.print(" Right truncatable prime = %(Fmt.dc(0, i))")
rightFound = true
if (leftFound) return
}
}
if (!leftFound) {
var q = i.toString[1..-1]
if (!q.contains("0")) {
var p = Num.fromString(q)
while (q.count > 0) {
if (p%2 == 0 || c[p]) break
q = q[1..-1]
p = Num.fromString(q)
}
if (q == "") {
System.print(" Left truncatable prime = %(Fmt.dc(0, i))")
leftFound = true
if (rightFound) return
}
}
}
}
i = i - 2
} |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #F.C5.8Drmul.C3.A6 | Fōrmulæ |
maxnodes%=100 ! set a limit to size of tree
content%=0 ! index of content field
left%=1 ! index of left tree
right%=2 ! index of right tree
DIM tree%(maxnodes%,3) ! create space for tree
'
OPENW 1
CLEARW 1
'
@create_tree
PRINT "Preorder: ";
@preorder_traversal(1)
PRINT ""
PRINT "Inorder: ";
@inorder_traversal(1)
PRINT ""
PRINT "Postorder: ";
@postorder_traversal(1)
PRINT ""
PRINT "Levelorder: ";
@levelorder_traversal(1)
PRINT ""
'
~INP(2)
CLOSEW 1
'
' Define the example tree
'
PROCEDURE create_tree
tree%(1,content%)=1
tree%(1,left%)=2
tree%(1,right%)=3
tree%(2,content%)=2
tree%(2,left%)=4
tree%(2,right%)=5
tree%(3,content%)=3
tree%(3,left%)=6
tree%(3,right%)=0 ! 0 is used for no subtree
tree%(4,content%)=4
tree%(4,left%)=7
tree%(4,right%)=0
tree%(5,content%)=5
tree%(5,left%)=0
tree%(5,right%)=0
tree%(6,content%)=6
tree%(6,left%)=8
tree%(6,right%)=9
tree%(7,content%)=7
tree%(7,left%)=0
tree%(7,right%)=0
tree%(8,content%)=8
tree%(8,left%)=0
tree%(8,right%)=0
tree%(9,content%)=9
tree%(9,left%)=0
tree%(9,right%)=0
RETURN
'
' Preorder traversal from given node
'
PROCEDURE preorder_traversal(node%)
IF node%<>0 ! 0 means there is no node
PRINT tree%(node%,content%);
preorder_traversal(tree%(node%,left%))
preorder_traversal(tree%(node%,right%))
ENDIF
RETURN
'
' Postorder traversal from given node
'
PROCEDURE postorder_traversal(node%)
IF node%<>0 ! 0 means there is no node
postorder_traversal(tree%(node%,left%))
postorder_traversal(tree%(node%,right%))
PRINT tree%(node%,content%);
ENDIF
RETURN
'
' Inorder traversal from given node
'
PROCEDURE inorder_traversal(node%)
IF node%<>0 ! 0 means there is no node
inorder_traversal(tree%(node%,left%))
PRINT tree%(node%,content%);
inorder_traversal(tree%(node%,right%))
ENDIF
RETURN
'
' Level order traversal from given node
'
PROCEDURE levelorder_traversal(node%)
LOCAL nodes%,first_free%,current%
'
' Set up initial queue of nodes
'
DIM nodes%(maxnodes%) ! some working space to store queue of nodes
current%=1
nodes%(current%)=node%
first_free%=current%+1
'
WHILE nodes%(current%)<>0
' add the children of current node onto queue
IF tree%(nodes%(current%),left%)<>0
nodes%(first_free%)=tree%(nodes%(current%),left%)
first_free%=first_free%+1
ENDIF
IF tree%(nodes%(current%),right%)<>0
nodes%(first_free%)=tree%(nodes%(current%),right%)
first_free%=first_free%+1
ENDIF
' print the current node content
PRINT tree%(nodes%(current%),content%);
' advance to next node
current%=current%+1
WEND
RETURN
|
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
| #Frink | Frink |
println[join[".", split[",", "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
| #Gambas | Gambas | Public Sub Main()
Dim sString As String[] = Split("Hello,How,Are,You,Today")
Print sString.Join(".")
End |
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #JavaScript | JavaScript |
function test() {
let n = 0
for(let i = 0; i < 1000000; i++){
n += i
}
}
let start = new Date().valueOf()
test()
let end = new Date().valueOf()
console.log('test() took ' + ((end - start) / 1000) + ' seconds') // test() took 0.001 seconds
|
http://rosettacode.org/wiki/Time_a_function | Time a function | Task
Write a program which uses a timer (with the least granularity available
on your system) to time how long a function takes to execute.
Whenever possible, use methods which measure only the processing time used
by the current process; instead of the difference in system time
between start and finish, which could include time used by
other processes on the computer.
This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.
| #Julia | Julia | # v0.6.0
function countto(n::Integer)
i = zero(n)
println("Counting...")
while i < n
i += 1
end
println("Done!")
end
@time countto(10 ^ 5)
@time countto(10 ^ 10) |
http://rosettacode.org/wiki/Top_rank_per_group | Top rank per group | Task
Find the top N salaries in each department, where N is provided as a parameter.
Use this data as a formatted internal data structure (adapt it to your language-native idioms, rather than parse at runtime), or identify your external data source:
Employee Name,Employee ID,Salary,Department
Tyler Bennett,E10297,32000,D101
John Rappl,E21437,47000,D050
George Woltman,E00127,53500,D101
Adam Smith,E63535,18000,D202
Claire Buckman,E39876,27800,D202
David McClellan,E04242,41500,D101
Rich Holcomb,E01234,49500,D202
Nathan Adams,E41298,21900,D050
Richard Potter,E43128,15900,D101
David Motsinger,E27002,19250,D202
Tim Sampair,E03033,27000,D101
Kim Arlich,E10001,57000,D190
Timothy Grove,E16398,29900,D190
| #HicEst | HicEst | CHARACTER source="Test.txt", outP='Top_rank.txt', fmt='A20,A8,i6,2x,A10'
CHARACTER name*20, employee_ID*10, department*10, temp*10
REAL :: idx(1), N_top_salaries=3
! Open the source with 4 "," separated columns, skip line 1:
OPEN(FIle=source, Format='SL=1;4,;', LENgth=L)
ALLOCATE(idx, L)
! Sort salary column 3 descending, then department column 4, store in idx:
SORT(FIle=source, Column=3, Descending=1, Column=4, Index=idx)
! Display a spreadsheet-like scrolling dialog of the presorted source:
DLG(Text=idx, Text=source, Format=fmt, Y)
! Output the first N top salaries of each department_
OPEN(FIle=outP)
DO i = 1, L
rank = rank + 1
READ(FIle=source, Row=idx(i)) name, employee_ID, salary, department
IF(temp /= department) THEN
rank = 1
WRITE(FIle=outP)
temp = department
ENDIF
IF(rank <= N_top_salaries) THEN
WRITE(FIle=outP, Format=fmt) name, employee_ID, salary, department
ENDIF
ENDDO
END |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #FreeBASIC | FreeBASIC |
'About 400 lines of code, but it is a graphical (GUI ish) i.e. mouse driven.
'I have made provision for the player to beat the computer now and then.
Type box
As long x,y
As long wide,high,index
Dim As ulong colour
As String caption
Declare Sub show
Declare Sub NewCaption(s As String)
Declare Constructor
Declare Constructor(x As long,y As long,wide As long,_
high As long,index As long,colour As ulong,caption As String)
End Type
Constructor box
End Constructor
Constructor box(x As long,y As long,wide As long,_
high As long,index As long,colour As ulong,caption As String)
this.x=x
this.y=y
this.wide=wide
this.high=high
this.index=index
this.colour=colour
this.caption=caption
End Constructor
'ALL PROCEDURES:
Declare Function inside(B As box,px As long,py As long) As long
Declare Sub make_frame_image(im As ulong Pointer)
Declare Sub setup_grid(boxes() As box,cellsacross As long,cellsdown As long,xp As long,yp As long,w As long,h As long)
Declare Function all_clicked(b() As box) As long
Declare Sub OnCLICK(a() As box,b As box)
Declare Sub refresh_screen(b() As box,f1 As long=0,f2 As long=0)
Declare Function Get_Mouse_Events(boxes() As box) As long
Declare Sub thickline(x1 As long,y1 As long,x2 As long,y2 As long,thickness As Single,colour As ulong,im As Any Pointer=0)
Declare Sub lineto(x1 As long,y1 As long,x2 As long,y2 As long,l As long,th As Single,col As ulong,im As Any Pointer=0)
Declare Sub thickcircle(x As long,y As long,rad As long,th As Single,col As ulong,im As Any Pointer=0)
Declare Sub startup(b() As box)
Declare Sub get_computer_events(b() As box)
Declare Sub finish
'Macro used by more than one procedure
#macro incircle(cx,cy,radius,x,y)
(cx-x)*(cx-x) +(cy-y)*(cy-y)<= radius*radius
#endmacro
'=============== RUN ============================
Screen 19,32',1,16
Color ,Rgb(233,236,216) 'background colour
windowtitle string(100," ")+"Noughts and crosses"
'Globals:
Dim Shared As ulong Pointer frame
Dim Shared As long computer,player
Dim Shared As String msg1,msg2,message
message="In Play"
msg1="Computer Start"
msg2="Player Start"
'Custom Frame
frame=Imagecreate(800,600)
Dim As box boxes(0 To 9)
setup_grid(boxes(),3,3,175,85,150,150)
make_frame_image(frame)
Do
If player=0 And computer=0 Then
startup(boxes())
End If
If player Then
Get_Mouse_Events(boxes())
End If
If computer Then
get_computer_events(boxes())
End If
If all_clicked(boxes()) Then get_computer_events(boxes())
Loop Until Inkey=Chr(27)
finish
Sub box.show
Line(this.x,this.y)-(this.x+this.wide,this.y+this.high),this.colour,bf
Line(this.x,this.y)-(this.x+this.wide,this.y+this.high),Rgb(200,200,200),b
''Draw String(this.x+.5*this.wide-4*Len(this.caption),this.y+(.5*this.high-4)),this.caption,Rgb(0,0,0)
If this.index=0 Then
Draw String(this.x+.5*this.wide-4*Len(this.caption),this.y+.5*this.high-6),this.caption,Rgb(0,0,0)
End If
End Sub
Sub box.NewCaption(s As String)
Var cx=(this.x+this.x+this.wide)/2
Var cy=(this.y+this.y+this.high)/2
If s="X" Then
For k As long=20 To 0 Step -1
lineto(cx,cy,this.x,this.y,50,k,Rgb(50+10*k,5*k,0),frame)
lineto(cx,cy,this.x+this.wide,this.y+this.high,50,k,Rgb(50+10*k,5*k,0),frame)
lineto(cx,cy,this.x,this.y+this.high,50,k,Rgb(50+10*k,5*k,0),frame)
lineto(cx,cy,this.x+this.wide,this.y,50,k,Rgb(50+10*k,5*k,0),frame)
Next k
Else
For k As long=20 To 0 Step -1
thickcircle(cx,cy,40,k,Rgb(50+10*k,5*k,0),frame)
Next k
End If
End Sub
Sub get_computer_events(b() As box)
#define other(n) b(n).caption<>"0" And b(n).caption<>"C"
#define another(n) b(n).caption="0"
#define rr(f,l) (Rnd*((l)-(f))+(f))
Dim As long flag,i,k,Cwin,Pwin,NoWin
Static As long firstclick
var chance="001100"
dim as long ch
'horiz player finish
For x As long=1 To 3
If b(1+k).caption="0" And b(2+k).caption="0" And another((3+k)) Then b(3+k).Caption="0":Pwin=1:Goto fin
If b(2+k).caption="0" And b(3+k).caption="0" And another((1+k))Then b(1+k).Caption="0":Pwin=1=1:Goto fin
If b(1+k).caption="0" And b(3+k).caption="0" And another((2+k))Then b(2+k).Caption="0":Pwin=1:Goto fin
k=k+3
Next x
k=0
'vert player finish
For x As long=1 To 3
If b(1+k).caption="0" And b(4+k).caption="0" And another((7+k)) Then b(7+k).Caption="0":Pwin=1:Goto fin
If b(4+k).caption="0" And b(7+k).caption="0" And another((1+k))Then b(1+k).Caption="0":Pwin=1:Goto fin
If b(1+k).caption="0" And b(7+k).caption="0" And another((4+k))Then b(4+k).Caption="0":Pwin=1:Goto fin
k=k+1
Next x
k=0
'player finish main diag
If b(1+k).caption="0" And b(5+k).caption="0" And another((9+k)) Then b(9+k).Caption="0":Pwin=1:Goto fin
If b(1+k).caption="0" And b(9+k).caption="0" And another((5+k))Then b(5+k).Caption="0":Pwin=1:Goto fin
If b(5+k).caption="0" And b(9+k).caption="0" And another((1+k))Then b(1+k).Caption="0":Pwin=1:Goto fin
'player finish other diag
If b(7+k).caption="0" And b(5+k).caption="0" And another((3+k)) Then b(3+k).Caption="0":Pwin=1:Goto fin
If b(5+k).caption="0" And b(3+k).caption="0" And another((7+k))Then b(7+k).Caption="0":Pwin=1:Goto fin
If b(7+k).caption="0" And b(3+k).caption="0" And another((5+k))Then b(5+k).Caption="0":Pwin=1:Goto fin
'horiz computer finish
For x As long=1 To 3
If b(1+k).caption="C" And b(2+k).caption="C" And other((3+k)) Then b(3+k).Caption="C":Cwin=1:Goto fin
If b(2+k).caption="C" And b(3+k).caption="C" And other((1+k))Then b(1+k).Caption="C":Cwin=1:Goto fin
If b(1+k).caption="C" And b(3+k).caption="C" And other((2+k))Then b(2+k).Caption="C":Cwin=1:Goto fin
k=k+3
Next x
k=0
'vert computer finish
For x As long=1 To 3
If b(1+k).caption="C" And b(4+k).caption="C" And other((7+k)) Then b(7+k).Caption="C":Cwin=1:Goto fin
If b(4+k).caption="C" And b(7+k).caption="C" And other((1+k))Then b(1+k).Caption="C":Cwin=1:Goto fin
If b(1+k).caption="C" And b(7+k).caption="C" And other((4+k))Then b(4+k).Caption="C":Cwin=1:Goto fin
k=k+1
Next x
k=0
'computer finish main diag
If b(1+k).caption="C" And b(5+k).caption="C" And other((9+k)) Then b(9+k).Caption="C":Cwin=1:Goto fin
If b(1+k).caption="C" And b(9+k).caption="C" And other((5+k))Then b(5+k).Caption="C":Cwin=1:Goto fin
If b(5+k).caption="C" And b(9+k).caption="C" And other((1+k))Then b(1+k).Caption="C":Cwin=1:Goto fin
'computer finish other diag
If b(7+k).caption="C" And b(5+k).caption="C" And other((3+k)) Then b(3+k).Caption="C":Cwin=1:Goto fin
If b(5+k).caption="C" And b(3+k).caption="C" And other((7+k))Then b(7+k).Caption="C":Cwin=1:Goto fin
If b(7+k).caption="C" And b(3+k).caption="C" And other((5+k))Then b(5+k).Caption="C":Cwin=1:Goto fin
'block horizontals
For x As long=1 To 3
If b(1+k).caption="0" And b(2+k).caption="0" And other((3+k)) Then b(3+k).Caption="C":flag=1:Goto fin
If b(2+k).caption="0" And b(3+k).caption="0" And other((1+k))Then b(1+k).Caption="C":flag=1:Goto fin
If b(1+k).caption="0" And b(3+k).caption="0" And other((2+k))Then b(2+k).Caption="C":flag=1:Goto fin
k=k+3
Next x
k=0
'block verticals
For x As long=1 To 3
If b(1+k).caption="0" And b(4+k).caption="0" And other((7+k)) Then b(7+k).Caption="C":flag=1:Goto fin
If b(4+k).caption="0" And b(7+k).caption="0" And other((1+k))Then b(1+k).Caption="C":flag=1:Goto fin
If b(1+k).caption="0" And b(7+k).caption="0" And other((4+k))Then b(4+k).Caption="C":flag=1:Goto fin
k=k+1
Next x
k=0
'block main diag
If b(1+k).caption="0" And b(5+k).caption="0" And other((9+k)) Then b(9+k).Caption="C":flag=1:Goto fin
If b(1+k).caption="0" And b(9+k).caption="0" And other((5+k))Then b(5+k).Caption="C":flag=1:Goto fin
If b(5+k).caption="0" And b(9+k).caption="0" And other((1+k))Then b(1+k).Caption="C":flag=1:Goto fin
'block other diag
If b(7+k).caption="0" And b(5+k).caption="0" And other((3+k)) Then b(3+k).Caption="C":flag=1:Goto fin
If b(5+k).caption="0" And b(3+k).caption="0" And other((7+k))Then b(7+k).Caption="C":flag=1:Goto fin
If b(7+k).caption="0" And b(3+k).caption="0" And other((5+k))Then b(5+k).Caption="C":flag=1:Goto fin
If firstclick=0 Then
firstclick=1
var st="1379"
dim as long i=rr(0,3)
If Valint(b(5).caption)=0 and b(5).caption <> "C" Then b(st[i]-48).caption="C":Goto fin
End If
ch=rr(0,5)
if chance[ch]-48=1 then
If Valint(b(5).caption)<>0 Then b(5).caption="C":Goto fin
end if
If all_clicked(b()) Then Nowin=1:Goto fin
If flag=0 Then
Randomize
Do
i=rr(1,9)
If Valint(b(i).caption) <> 0 Then b(i).caption="C":Exit Do
Loop
End If
fin:
If Cwin=1 Or Pwin=1 Or NoWin=1 Then
Dim As long mx,my,mb
dim as integer x,y
screencontrol 0,x,y
for z as single=0 to 8*atn(1) step .001
dim as integer xx=x+100*cos(z)
dim as integer yy=y+100*sin(z)
screencontrol 100,xx,yy
next z
screencontrol 100,x,y
If Cwin=1 Then Message="You Loose"
If Pwin=1 Then Message="You WIN"
If Nowin=1 Then Message="DRAW"
cwin=0:k=0:pWin=0:Nowin=0:firstclick=0'i
Do
Getmouse mx,my,,mb
If inside(b(0),mx,my) And mb=1 Then finish
Var ic=incircle(500,55,20,mx,my)
If incircle(500,55,20,mx,my) And mb=1 Then Exit Do
refresh_screen(b(),ic)
Loop Until Inkey=chr(27)
For z As long=1 To Ubound(b)
b(z).caption=Str(b(z).index)
Next z
Imagedestroy frame
frame=Imagecreate(800,600)
make_frame_image(frame)
computer=0:player=0
Exit Sub
End If
player=1:computer=0
End Sub
Sub startup(b() As box)
message="In Play"
Dim As long mx,my,mb
Getmouse mx,my,,mb
For n As long=0 To Ubound(b)
If inside(b(n),mx,my) And mb=1 Then
If b(n).index=0 Then
finish
End If
End If
b(0).colour=Rgb(200,0,0)
Next n
Dim As long f1,f2
If incircle(80,230,10,mx,my) Then
f1=1:f2=0
If mb=1 Then computer=1:player=0
End If
If incircle(670,230,10,mx,my) Then
f1=0:f2=1
If mb=1 Then player=1:computer=0
End If
refresh_screen(b(),f1,f2)
End Sub
Sub thickcircle(x As long,y As long,rad As long,th As Single,col As ulong,im As Any Pointer=0)
Circle(x,y),rad+th/2,col
Circle(x,y),rad-th/2,col
Paint(x,y+rad),col,col
End Sub
Sub thickline(x1 As long,_
y1 As long,_
x2 As long,_
y2 As long,_
thickness As Single,_
colour As ulong,_
im As Any Pointer=0)
Dim p As ulong=Rgb(255, 255, 255)
If thickness<2 Then
Line(x1,y1)-(x2,y2),colour
Else
Dim As Double s,h,c
h=Sqr((x2-x1)^2+(y2-y1)^2)
If h=0 Then h=1e-6
s=(y1-y2)/h
c=(x2-x1)/h
For x As long=1 To 2
Line im,(x1+s*thickness/2,y1+c*thickness/2)-(x2+s*thickness/2,y2+c*thickness/2),p
Line im,(x1-s*thickness/2,y1-c*thickness/2)-(x2-s*thickness/2,y2-c*thickness/2),p
Line im,(x1+s*thickness/2,y1+c*thickness/2)-(x1-s*thickness/2,y1-c*thickness/2),p
Line im,(x2+s*thickness/2,y2+c*thickness/2)-(x2-s*thickness/2,y2-c*thickness/2),p
Paint im,((x1+x2)/2, (y1+y2)/2), p, p
p=colour
Next x
End If
End Sub
Sub lineto(x1 As long,y1 As long,x2 As long,y2 As long,l As long,th As Single,col As ulong,im As Any Pointer=0)
Dim As long diffx=x2-x1,diffy=y2-y1,ln=Sqr(diffx*diffx+diffy*diffy)
Dim As Single nx=diffx/ln,ny=diffy/ln
thickline(x1,y1,(x1+l*nx),(y1+l*ny),th,col,im)
End Sub
Function inside(B As box,px As long,py As long) As long
Return (px>B.x)*(px<(B.x+B.wide))*(py>B.y)*(py<(B.y+B.high))
End Function
Sub make_frame_image(im As ulong Pointer)
#macro map(a,b,x,d,c)
((d)-(c))*((x)-(a))/((b)-(a))+(c)
#endmacro
#macro logo(sx,sy,rad)
For k As Single=-rad/10 To rad/10 Step .5:Circle im,(sx,sy),rad+k,Rgb(15,118,155):Next
For k As Single=-rad/10 To rad/10 Step .5:Circle im,(sx+1.3*rad,sy+rad),rad+k,Rgb(230,193,78),2.,1.7:Next
For k As Single=-rad/10 To rad/10 Step .5:Circle im,(sx+2*1.3*rad,sy),rad+k,Rgb(21,3,0),3.25,3.05:Next
For k As Single=-rad/10 To rad/10 Step .5:Circle im,(sx+3*1.3*rad,sy+rad),rad+k,Rgb(26,143,76),2,1.8:Next
For k As Single=-rad/10 To rad/10 Step .5:Circle im,(sx+4*1.3*rad,sy),rad+k,Rgb(200,63,87),3.25,3.05:Next
#endmacro
For k As long=0 To 50
Var r=map(0,50,k,233,193-20)
Var g=map(0,50,k,236,153-20)
Var b=map(0,50,k,216,19-19)
Line im,(0+k,20+k)-(800-k,600-k),Rgb(r,g,b),b
Next k
For k As long=0 To 20
Var r=map(0,20,k,250,0)
Var g=map(0,20,k,250,0)
Var b=map(0,20,k,250,255)
Line im,(0,k)-(780,k),Rgb(r,g,b)',bf
Next k
logo(60,8,5)
logo(380,8,5)
logo(720,8,5)
End Sub
Sub setup_grid(boxes() As box,cellsacross As long,cellsdown As long,xp As long,yp As long,w As long,h As long)
Dim As long index
For y As long=yp To yp+h*(cellsdown-1) Step h
For x As long=xp To xp+w*(cellsacross-1) Step w
index=index+1
boxes(index)=Type<box>(x,y,w,h,index,Rgb(133,136,116),Str(index))
Next x
Next y
boxes(0)=Type<box>(780,-2,20,24,0,Rgb(200,0,0),"X")
End Sub
Function all_clicked(b() As box) As long
Dim As long sum
For z As long=1 To Ubound(b)
sum=sum+Valint(b(z).caption)
Next z
If sum<=0 Then Return -1
End Function
Sub OnCLICK(a() As box,b As box)
If b.caption="0" Then Exit Sub
If b.caption="C" Then Exit Sub
If b.caption <> "C" Then b.caption="0"
If b.index=0 Then finish
player=0:computer=1
End Sub
Sub refresh_screen(b() As box,f1 As long=0,f2 As long=0)
Screenlock:Cls
For n As long=0 To Ubound(b)
b(n).show 'draw boxes
If b(n).caption="0" Then b(n).NewCaption("X")
If b(n).caption="C" Then b(n).NewCaption("O")
Next n
Put(0,0),frame,trans
Draw String (390,50),message,Rgb(0,0,0)
If message <>"In Play" Then
Circle(500,55),20,Rgb(255,20,255),,,,f
If f1=-1 Then Circle(500,55),20,Rgb(202,200,200),,,,f
Draw String(480,50),"Click",Rgb(0,0,0)
End If
If computer=0 And player=0 Then
Draw String (60,200),msg1,Rgb(0,0,0)
Circle(80,230),10,Rgb(0,0,0)
Circle(80,230),5,Rgb(100,100,100),,,,f
If f1=1 Then Circle(80,230),10,Rgb(200,0,0),,,,f
Draw String (650,200),msg2,Rgb(0,0,0)
Circle(670,230),10,Rgb(0,0,0)
Circle(670,230),5,Rgb(100,100,100),,,,f
If f2=1 Then Circle(670,230),10,Rgb(200,0,0),,,,f
End If
Screenunlock:Sleep 1,1
End Sub
Function Get_Mouse_Events(boxes() As box) As long
Static released As long
Static pressed As long
Dim As long mousex,mousey,mousebutton ,x,y
Getmouse mousex,mousey,,mousebutton
Dim As box bar=Type<box>(0,0,780,50,0,0,"")
refresh_screen(boxes())
For n As long=0 To Ubound(boxes)
If inside(boxes(n),mousex,mousey) Then
If released Then
boxes(n).colour=Rgb(120,123,103)
If n=0 Then boxes(0).colour=Rgb(255,0,0)
End If
If mousebutton=1 Then
If released Then OnCLICK(boxes(),boxes(n))
Exit For
End If
Else
boxes(n).colour=Rgb(133,136,116)
If n=0 Then boxes(0).colour=Rgb(200,0,0)
End If
Next n
If mousebutton=0 Then released=1 Else released=0 'clean clicks
Return 0
End Function
Sub finish
Screenunlock
Imagedestroy frame
End
End Sub
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #D | D | import std.stdio;
void hanoi(in int n, in char from, in char to, in char via) {
if (n > 0) {
hanoi(n - 1, from, via, to);
writefln("Move disk %d from %s to %s", n, from, to);
hanoi(n - 1, via, to, from);
}
}
void main() {
hanoi(3, 'L', 'M', 'R');
} |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #Scala | Scala | def thueMorse(n: Int): String = {
val (sb0, sb1) = (new StringBuilder("0"), new StringBuilder("1"))
(0 until n).foreach { _ =>
val tmp = sb0.toString()
sb0.append(sb1)
sb1.append(tmp)
}
sb0.toString()
}
(0 to 6).foreach(i => println(s"$i : ${thueMorse(i)}")) |
http://rosettacode.org/wiki/Thue-Morse | Thue-Morse | Task
Create a Thue-Morse sequence.
See also
YouTube entry: The Fairest Sharing Sequence Ever
YouTube entry: Math and OCD - My story with the Thue-Morse sequence
Task: Fairshare between two and more
| #Sidef | Sidef | func recmap(repeat, seed, transform, callback) {
func (repeat, seed) {
callback(seed)
repeat > 0 && __FUNC__(repeat-1, transform(seed))
}(repeat, seed)
}
recmap(6, "0", {|s| s + s.tr('01', '10') }, { .say }) |
http://rosettacode.org/wiki/Tokenize_a_string_with_escaping | Tokenize a string with escaping | Task[edit]
Write a function or program that can split a string at each non-escaped occurrence of a separator character.
It should accept three input parameters:
The string
The separator character
The escape character
It should output a list of strings.
Details
Rules for splitting:
The fields that were separated by the separators, become the elements of the output list.
Empty fields should be preserved, even at the start and end.
Rules for escaping:
"Escaped" means preceded by an occurrence of the escape character that is not already escaped itself.
When the escape character precedes a character that has no special meaning, it still counts as an escape (but does not do anything special).
Each occurrence of the escape character that was used to escape something, should not become part of the output.
Test case
Demonstrate that your function satisfies the following test-case:
Input
Output
string:
one^|uno||three^^^^|four^^^|^cuatro|
separator character:
|
escape character:
^
one|uno
three^^
four^|cuatro
(Print the output list in any format you like, as long as it is it easy to see what the fields are.)
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Swift | Swift | extension String {
func tokenize(separator: Character, escape: Character) -> [String] {
var token = ""
var tokens = [String]()
var chars = makeIterator()
while let char = chars.next() {
switch char {
case separator:
tokens.append(token)
token = ""
case escape:
if let next = chars.next() {
token.append(next)
}
case _:
token.append(char)
}
}
tokens.append(token)
return tokens
}
}
print("one^|uno||three^^^^|four^^^|^cuatro|".tokenize(separator: "|", escape: "^")) |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.