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/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.
| #PL.2FSQL | PL/SQL | DECLARE
pi NUMBER := 4 * ATAN(1);
radians NUMBER := pi / 4;
degrees NUMBER := 45.0;
BEGIN
DBMS_OUTPUT.put_line(SIN(radians) || ' ' || SIN(degrees * pi/180) );
DBMS_OUTPUT.put_line(COS(radians) || ' ' || COS(degrees * pi/180) );
DBMS_OUTPUT.put_line(TAN(radians) || ' ' || TAN(degrees * pi/180) );
DBMS_OUTPUT.put_line(ASIN(SIN(radians)) || ' ' || ASIN(SIN(degrees * pi/180)) * 180/pi);
DBMS_OUTPUT.put_line(ACOS(COS(radians)) || ' ' || ACOS(COS(degrees * pi/180)) * 180/pi);
DBMS_OUTPUT.put_line(ATAN(TAN(radians)) || ' ' || ATAN(TAN(degrees * pi/180)) * 180/pi);
END; |
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.
| #Perl | Perl | sub preorder
{
my $t = shift or return ();
return ($t->[0], preorder($t->[1]), preorder($t->[2]));
}
sub inorder
{
my $t = shift or return ();
return (inorder($t->[1]), $t->[0], inorder($t->[2]));
}
sub postorder
{
my $t = shift or return ();
return (postorder($t->[1]), postorder($t->[2]), $t->[0]);
}
sub depth
{
my @ret;
my @a = ($_[0]);
while (@a) {
my $v = shift @a or next;
push @ret, $v->[0];
push @a, @{$v}[1,2];
}
return @ret;
}
my $x = [1,[2,[4,[7]],[5]],[3,[6,[8],[9]]]];
print "pre: @{[preorder($x)]}\n";
print "in: @{[inorder($x)]}\n";
print "post: @{[postorder($x)]}\n";
print "depth: @{[depth($x)]}\n"; |
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
| #OCaml | OCaml | let words = String.split_on_char ',' "Hello,How,Are,You,Today" in
String.concat "." words
|
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
| #Oforth | Oforth | "Hello,How,Are,You,Today" wordsWith(',') println |
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
| #PowerShell | PowerShell | function New-Employee ($Name, $ID, $Salary, $Department) {
New-Object PSObject `
| Add-Member -PassThru NoteProperty EmployeeName $Name `
| Add-Member -PassThru NoteProperty EmployeeID $ID `
| Add-Member -PassThru NoteProperty Salary $Salary `
| Add-Member -PassThru NoteProperty Department $Department
}
$data = (New-Employee 'Tyler Bennett' E10297 32000 D101),
(New-Employee 'John Rappl' E21437 47000 D050),
(New-Employee 'George Woltman' E00127 53500 D101),
(New-Employee 'Adam Smith' E63535 18000 D202),
(New-Employee 'Claire Buckman' E39876 27800 D202),
(New-Employee 'David McClellan' E04242 41500 D101),
(New-Employee 'Rich Holcomb' E01234 49500 D202),
(New-Employee 'Nathan Adams' E41298 21900 D050),
(New-Employee 'Richard Potter' E43128 15900 D101),
(New-Employee 'David Motsinger' E27002 19250 D202),
(New-Employee 'Tim Sampair' E03033 27000 D101),
(New-Employee 'Kim Arlich' E10001 57000 D190),
(New-Employee 'Timothy Grove' E16398 29900 D190)
function Get-TopRank ($n) {
$data `
| Group-Object Department `
| ForEach-Object {
$_.Group `
| Sort-Object Salary -Descending `
| Select-Object -First $n
} `
| Format-Table -GroupBy Department
} |
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.
| #R | R |
rm(list=ls())
library(RColorBrewer)
# Create tic.tac.toe function.
tic.tac.toe <- function(name="Name", mode=0, type=0){
place.na <<- matrix(1:9, 3, 3)
value <<- matrix(-3, 3, 3)
k <<- 1 ; r <<- 0
# Make game board.
image(1:3, 1:3, matrix(sample(9), 3, 3), asp=c(1, 1),
xaxt="n", yaxt="n", xlab="", ylab="", frame=F, col=brewer.pal(9, "Set3"))
segments(c(0.5,0.5,1.5,2.5), c(2.5,1.5,0.5,0.5),
c(3.5,3.5,1.5,2.5), c(2.5,1.5,3.5,3.5), lwd=8, col=gray(0.3))
segments(c(0.5,0.5,0.5,3.5), c(0.52,3.47,0.5,0.5),
c(3.5,3.5,0.5,3.5), c(0.52,3.47,3.5,3.5), lwd=8, col=gray(0.3))
# Allow player to choose between a human v. human, human v. random AI, or human vs. smart AI.
if(mode==0) title(list(paste(name, "'s Tic-Tac-Toe !"), cex=2),
"2P : Human v.s. Human", font.sub=2, cex.sub=2)
if(mode==1) title(list(paste(name, "'s Tic-Tac-Toe !"), cex=2),
"1P : Human v.s. AI (Easy)", font.sub=2, cex.sub=2)
if(mode==2) title(list(paste(name, "'s Tic-Tac-Toe !"), cex=2),
"1P : Human v.s. AI (Hard)", font.sub=2, cex.sub=2)
# Dole out symbols.
if(type==0){symbol <- "O" ; symbol.op <- "X"}
if(type==1){symbol <- "X" ; symbol.op <- "O"}
out <- list(name=name, mode=mode, type=type, symbol=symbol, symbol.op=symbol.op)
}
# Checks if the game has ended.
isGameOver <- function(){
for(i in 1:3){
total.1 <- 0 ; total.2 <- 0
for(j in 1:3){
total.1 <- total.1 + value[i, j]
total.2 <- total.2 + value[j, i]
}
if(total.1==0 | total.2==0 | total.1==3 | total.2==3){
break
}
}
total.3 <- value[1, 1] + value[2, 2] + value[3, 3]
total.4 <- value[1, 3] + value[2, 2] + value[3, 1]
if(total.1==0 | total.2==0 | total.3==0 | total.4==0 | total.1==3 | total.2==3 | total.3==3 | total.4==3){
place.na[!is.na(place.na)] <<- NA
if(total.1==0 | total.2==0 | total.3==0 | total.4==0){
title(sub=list(""You Won ?! That's a first!", col="red", font=2, cex=2.5), line=2)
}else{
title(sub=list("You Don't Get Tired of Losing ?!", col="darkblue", font=2, cex=2.5), line=2)
}
}
if(all(is.na(place.na))){
if(total.1==0 | total.2==0 | total.3==0 | total.4==0 | total.1==3 | total.2==3 | total.3==3 | total.4==3){
if(total.1==0 | total.2==0 | total.3==0 | total.4==0){
title(sub=list("You Won ! Pigs Must Be Flying!", col="orange", font=2, cex=2.5), line=2)
}else{
title(sub=list("You Lost ... Once Again !", col="darkblue", font=2, cex=2.5), line=2)
}
}else{
title(sub=list("A measly tie! Try Again", col="blue", font=2, cex=2.5), line=2)
}
}
}
# AI attack function
attack <- function(){
### Identify rows and columns
for(i in 1:3){
total.1 <- 0 ; total.2 <- 0
for(j in 1:3){
total.1 <- total.1 + value[i, j]
total.2 <- total.2 + value[j, i]
}
if(total.1==-1 | total.2==-1){
break
}
}
total.3 <- value[1, 1] + value[2, 2] + value[3, 3]
total.4 <- value[1, 3] + value[2, 2] + value[3, 1]
if(total.1==-1){
text(i, which(value[i,]!=1), symbol.op, cex=6, font=2)
place.na[i, which(value[i,]!=1)] <<- NA
value[i, which(value[i,]!=1)] <<- 1
}else if(total.2==-1){
text(which(value[,i]!=1), i, symbol.op, cex=6, font=2)
place.na[which(value[,i]!=1), i] <<- NA
value[which(value[,i]!=1), i] <<- 1
}else if(total.3==-1){
r.1 <- which(c(value[1, 1], value[2, 2], value[3, 3])!=1)
text(r.1, r.1, symbol.op, cex=6, font=2)
place.na[r.1, r.1] <<- NA
value[r.1, r.1] <<- 1
}else if(total.4==-1){
r.2 <- which(c(value[1, 3], value[2, 2], value[3, 1])!=1)
text(r.2, -r.2+4, symbol.op, cex=6, font=2)
place.na[r.2, -r.2+4] <<- NA
value[r.2, -r.2+4] <<- 1
}
}
# AI defense function
defend <- function(){
for(i in 1:3){
total.1 <- 0 ; total.2 <- 0
for(j in 1:3){
total.1 <- total.1 + value[i, j]
total.2 <- total.2 + value[j, i]
}
if(total.1==-3 | total.2==-3){
break
}
}
total.3 <- value[1, 1] + value[2, 2] + value[3, 3]
total.4 <- value[1, 3] + value[2, 2] + value[3, 1]
if(total.1==-3){
text(i, which(value[i,]!=0), symbol.op, cex=6, font=2)
place.na[i, which(value[i,]!=0)] <<- NA
value[i, which(value[i,]!=0)] <<- 1
}else if(total.2==-3){
text(which(value[,i]!=0), i, symbol.op, cex=6, font=2)
place.na[which(value[,i]!=0), i] <<- NA
value[which(value[,i]!=0), i] <<- 1
}else if(total.3==-3){
r.1 <- which(c(value[1, 1], value[2, 2], value[3, 3])!=0)
text(r.1, r.1, symbol.op, cex=6, font=2)
place.na[r.1, r.1] <<- NA
value[r.1, r.1] <<- 1
}else if(total.4==-3){
r.2 <- which(c(value[1, 3], value[2, 2], value[3, 1])!=0)
text(r.2, -r.2+4, symbol.op, cex=6, font=2)
place.na[r.2, -r.2+4] <<- NA
value[r.2, -r.2+4] <<- 1
}else{
rn <- sample(place.na[!is.na(place.na)], 1)
text(rn-3*rn%/%3.5, rn%/%3.5+1, symbol.op, cex=6, font=2)
place.na[rn-3*rn%/%3.5, rn%/%3.5+1] <<- NA
value[rn-3*rn%/%3.5, rn%/%3.5+1] <<- 1
}
}
# Allow aim in program.
aim <- function(x, y, tic.tac.toe=ttt){
mode <- tic.tac.toe$mode
symbol <<- tic.tac.toe$symbol
symbol.op <<- tic.tac.toe$symbol.op
x <<- x ; y <<- y
# Mode 0, Two Players
if(mode==0){
turn <- rep(c(0, 1), length.out=9)
if(is.na(place.na[x, y])){
cat("This square is taken !")
}else{
if(turn[k]==0){
text(x, y, symbol, cex=6, font=2)
place.na[x, y] <<- NA
value[x, y] <<- 0
}
if(turn[k]==1){
text(x, y, symbol.op, cex=6, font=2)
place.na[x, y] <<- NA
value[x, y] <<- 1
}
k <<- k + 1
}
}
# Mode 1, Random AI
if(mode==1){
if(is.na(place.na[x, y])){
cat("This square had been chosen !")
}else{
text(x, y, symbol, cex=6, font=2)
place.na[x, y] <<- NA
value[x, y] <<- 0
isGameOver()
for(i in 1:3){
total.1 <- 0 ; total.2 <- 0
for(j in 1:3){
total.1 <- total.1 + value[i, j]
total.2 <- total.2 + value[j, i]
}
if(total.1==-1 | total.2==-1){
break
}
}
total.3 <- value[1, 1] + value[2, 2] + value[3, 3]
total.4 <- value[1, 3] + value[2, 2] + value[3, 1]
if(all(is.na(place.na))){
isGameOver()
}else if(total.1==-1 | total.2==-1 | total.3==-1 | total.4==-1){
attack()
}else{
defend()
}
}
}
# Mode 2, Hard AI
if(mode==2){
if(is.na(place.na[x, y])){
cat("This square is taken!")
}else{
# AI First Turn
if(sum(is.na(place.na))==0){
text(x, y, symbol, cex=6, font=2)
place.na[x, y] <<- NA
value[x, y] <<- 0
if(is.na(place.na[2, 2])==F){
text(2, 2, symbol.op, cex=6, font=2)
place.na[2, 2] <<- NA
value[2, 2] <<- 1
}else{
corner.1 <- sample(c(1, 3), 1) ; corner.2 <- sample(c(1, 3), 1)
text(corner.1, corner.2, symbol.op, cex=6, font=2)
place.na[corner.1, corner.2] <<- NA
value[corner.1, corner.2] <<- 1
}
# AI Second Turn
}else if(sum(is.na(place.na))==2){
text(x, y, symbol, cex=6, font=2)
place.na[x, y] <<- NA
value[x, y] <<- 0
for(i in 1:3){
total.1 <- 0 ; total.2 <- 0
for(j in 1:3){
total.1 <- total.1 + value[i, j]
total.2 <- total.2 + value[j, i]
}
if(total.1==-3 | total.2==-3){
break
}
}
total.3 <- value[1, 1] + value[2, 2] + value[3, 3]
total.4 <- value[1, 3] + value[2, 2] + value[3, 1]
if(total.1==-3 | total.2==-3 | total.3==-3 | total.4==-3){
defend()
}else{
total.1 <- value[2, 1] + value[2, 2] + value[2, 3]
total.2 <- value[1, 2] + value[2, 2] + value[3, 2]
total.3 <- value[1, 1] + value[2, 2] + value[3, 3]
total.4 <- value[1, 3] + value[2, 2] + value[3, 1]
if(total.1==1 | total.2==1 | total.3==1 | total.4==1){
if((value[2, 2]==1 & total.3==1) | (value[2, 2]==1 & total.4==1)){
vector.side <- c(place.na[2, 1], place.na[1, 2], place.na[3, 2], place.na[2, 3])
rn <- sample(vector.side[!is.na(vector.side)], 1)
text(rn-3*rn%/%3.5, rn%/%3.5+1, symbol.op, cex=6, font=2)
place.na[rn-3*rn%/%3.5, rn%/%3.5+1] <<- NA
value[rn-3*rn%/%3.5, rn%/%3.5+1] <<- 1
}else{
matrix.cor <- place.na[c(1, 3), c(1, 3)]
rn <- sample(matrix.cor[!is.na(matrix.cor)], 1)
text(rn-3*rn%/%3.5, rn%/%3.5+1, symbol.op, cex=6, font=2)
place.na[rn-3*rn%/%3.5, rn%/%3.5+1] <<- NA
value[rn-3*rn%/%3.5, rn%/%3.5+1] <<- 1
}
}else{
if((x==1 & y==2) | (x==3 & y==2)){
rn <- sample(c(1, 3), 1)
text(x, rn, symbol.op, cex=6, font=2)
place.na[x, rn] <<- NA
value[x, rn] <<- 1
}else if((x==2 & y==3) | (x==2 & y==1)){
rn <- sample(c(1, 3), 1)
text(rn, y, symbol.op, cex=6, font=2)
place.na[rn, y] <<- NA
value[rn, y] <<- 1
}else if((x==1 & y==1) | (x==1 & y==3) | (x==3 & y==1) | (x==3 & y==3)){
text(-x+4, -y+4, symbol.op, cex=6, font=2)
place.na[-x+4, -y+4] <<- NA
value[-x+4, -y+4] <<- 1
}
}
}
# AI Other Turn
}else{
text(x, y, symbol, cex=6, font=2)
place.na[x, y] <<- NA
value[x, y] <<- 0
isGameOver()
for(i in 1:3){
total.1 <- 0 ; total.2 <- 0
for(j in 1:3){
total.1 <- total.1 + value[i, j]
total.2 <- total.2 + value[j, i]
}
if(total.1==-1 | total.2==-1){
break
}
}
total.3 <- value[1, 1] + value[2, 2] + value[3, 3]
total.4 <- value[1, 3] + value[2, 2] + value[3, 1]
if(all(is.na(place.na))){
isGameOver()
}else if(total.1==-1 | total.2==-1 | total.3==-1 | total.4==-1){
attack()
}else{
defend()
}
}
}
}
isGameOver()
}
# Allow users to click on program.
click <- function(tic.tac.toe=ttt){
name <- tic.tac.toe$name
mode <- tic.tac.toe$mode
type <- tic.tac.toe$type
while(length(place.na)==9){
mouse.at <- locator(n = 1, type = "n")
#cat(mouse.at$x,"\t", mouse.at$y, "\n")
x.at <- round(mouse.at$x)
y.at <- round(mouse.at$y)
#cat(x.at,"\t", y.at, "\n")
if(all(is.na(place.na))){
ttt <<- tic.tac.toe(name, mode, type)
}else if(x.at > 3.5 | x.at < 0.5 | y.at > 3.5 | y.at < 0.5){
r <<- r + 1
title(sub=list("Click outside:Quit / inside:Restart", col="deeppink", font=2, cex=2), line=2)
if(r==2){
dev.off()
break
}
}else{
if(r==1){
ttt <<- tic.tac.toe(name, mode, type)
}else{
aim(x.at, y.at)
}
}
}
}
# Play the game
start <- function(name="Name", mode=0, type=0){
x11()
ttt <<- tic.tac.toe(name, mode, type)
click()
}
#start("name", "mode" = 0 - 2, type = 0,1)
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Haskell | Haskell | hanoi :: Integer -> a -> a -> a -> [(a, a)]
hanoi 0 _ _ _ = []
hanoi n a b c = hanoi (n-1) a c b ++ [(a,b)] ++ hanoi (n-1) c b a |
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.
| #Pop11 | Pop11 | sin(30) =>
cos(45) =>
tan(45) =>
arcsin(0.7) =>
arccos(0.7) =>
arctan(0.7) =>
;;; switch to radians
true -> popradians;
sin(pi*30/180) =>
cos(pi*45/180) =>
tan(pi*45/180) =>
arcsin(0.7) =>
arccos(0.7) =>
arctan(0.7) => |
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.
| #PostScript | PostScript |
90 sin =
60 cos =
%tan of 45 degrees
45 sin 45 cos div =
%inverse tan ( arc tan of sqrt 3)
3 sqrt 1 atan =
|
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.
| #Phix | Phix | constant VALUE = 1, LEFT = 2, RIGHT = 3
constant tree = {1, {2, {4, {7, 0, 0}, 0},
{5, 0, 0}},
{3, {6, {8, 0, 0},
{9, 0, 0}},
0}}
procedure preorder(object tree)
if sequence(tree) then
printf(1,"%d ",{tree[VALUE]})
preorder(tree[LEFT])
preorder(tree[RIGHT])
end if
end procedure
procedure inorder(object tree)
if sequence(tree) then
inorder(tree[LEFT])
printf(1,"%d ",{tree[VALUE]})
inorder(tree[RIGHT])
end if
end procedure
procedure postorder(object tree)
if sequence(tree) then
postorder(tree[LEFT])
postorder(tree[RIGHT])
printf(1,"%d ",{tree[VALUE]})
end if
end procedure
procedure level_order(object tree, sequence more = {})
if sequence(tree) then
more &= {tree[LEFT],tree[RIGHT]}
printf(1,"%d ",{tree[VALUE]})
end if
if length(more) > 0 then
level_order(more[1],more[2..$])
end if
end procedure
puts(1,"\n preorder: ") preorder(tree)
puts(1,"\n inorder: ") inorder(tree)
puts(1,"\n postorder: ") postorder(tree)
puts(1,"\n level-order: ") level_order(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
| #ooRexx | ooRexx | text='Hello,How,Are,You,Today'
do while text \= ''
parse var text word1 ',' text
call charout 'STDOUT:',word1'.'
end |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #OpenEdge.2FProgress | OpenEdge/Progress | FUNCTION tokenizeString RETURNS CHAR (
i_c AS CHAR
):
DEF VAR ii AS INT.
DEF VAR carray AS CHAR EXTENT.
DEF VAR cresult AS CHAR.
EXTENT( carray ) = NUM-ENTRIES( i_c ).
DO ii = 1 TO NUM-ENTRIES( i_c ):
carray[ ii ] = ENTRY( ii, i_c ).
END.
DO ii = 1 TO EXTENT( carray ).
cresult = cresult + "." + carray[ ii ].
END.
RETURN SUBSTRING( cresult, 2 ).
END FUNCTION. /* tokenizeString */
MESSAGE
tokenizeString( "Hello,How,Are,You,Today" )
VIEW-AS ALERT-BOX. |
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
| #Prolog | Prolog | % emp(name,id,salary,dpt)
emp('Tyler Bennett','E10297',32000,'D101').
emp('John Rappl','E21437',47000,'D050').
emp('George Woltman','E00127',53500,'D101').
emp('Adam Smith','E63535',18000,'D202').
emp('Claire Buckman','E39876',27800,'D202').
emp('David McClellan','E04242',41500,'D101').
emp('Rich Holcomb','E01234',49500,'D202').
emp('Nathan Adams','E41298',21900,'D050').
emp('Richard Potter','E43128',15900,'D101').
emp('David Motsinger','E27002',19250,'D202').
emp('Tim Sampair','E03033',27000,'D101').
emp('Kim Arlich','E10001',57000,'D190').
emp('Timothy Grove','E16398',29900,'D190').
departments(Depts) :- % Find the set of departments
findall(Dpt, emp(_,_,_,Dpt), DList), list_to_set(DList, Depts).
greater(emp(_,_,Sal1,_), emp(_,_,Sal2,_)) :-
Sal1 > Sal2. % First employee salary greater than second
% Maintains a decreasing ordered list of employees truncated after (N) items.
% Rule 1: For N=0, always return an empty set.
% Rule 2: Add employee with greater salary at start of list, call with N-1
% Rule 3: Try to add new employee at N-1
% Rule 4: for an empty input list regardless of N, add the new employee
topSalary(0, _, _, []).
topSalary(N, Emp, [E|R], [Emp|Res]) :-
greater(Emp,E), N0 is N - 1, !, topSalary(N0, E, R, Res).
topSalary(N, Emp, [E|R], [E|Res]) :-
N0 is N - 1, !, topSalary(N0, Emp, R, Res).
topSalary(_, Emp, [], [Emp]).
% For each employee, add him to the list if top salary
topEmps(N, [Emp|Emps], R, Res) :-
topSalary(N, Emp, R, Rt), !, topEmps(N, Emps, Rt, Res).
topEmps(_, [], Res, Res).
% For each department, find the list of top employees in that department
topDeps(N, [Dept|T], [dept(Dept,Ro)|Res]) :-
findall(emp(Name, Id, Sal, Dept), emp(Name, Id, Sal, Dept), Emps),
topEmps(N, Emps, [], Ro), !, topDeps(N, T, Res).
topDeps(_, [], []).
% Calculate and report the list of highest salaried employees per department
topDeps(N) :-
departments(D), topDeps(N, D, Res),
member(dept(Dept,R), Res),
writef('Department: %w\n', [Dept]),
member(emp(Name,Id,Sal,_), R),
writef(' ID: %w\t%w\tSalary: %w\n', [Id,Name,Sal]),
fail.
topDeps(_). |
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.
| #Racket | Racket | + minimax.rkt -- Written in Lazy Racket, implements the general minimax algorythm as
| given in Wikipedia.
| Knows nothing about games.
V
+ game.rkt -- Written in Lazy Racket, defines general classes for the game and players.
| Knows nothing about tick-tack-toe, only about zero-sum two-player
| turn-taking games with perfect information in general.
V
+ tick-tack.rkt -- Written in Racket, implements the tick-tack-toe game.
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #HolyC | HolyC | U0 Move(U8 n, U8 from, U8 to, U8 via) {
if (n > 0) {
Move(n - 1, from, via, to);
Print("Move disk from pole %d to pole %d\n", from, to);
Move(n - 1, via, to, from);
}
}
Move(4, 1, 2, 3); |
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.
| #PowerShell | PowerShell | $rad = [Math]::PI / 4
$deg = 45
'{0,10} {1,10}' -f 'Radians','Degrees'
'{0,10:N6} {1,10:N6}' -f [Math]::Sin($rad), [Math]::Sin($deg * [Math]::PI / 180)
'{0,10:N6} {1,10:N6}' -f [Math]::Cos($rad), [Math]::Cos($deg * [Math]::PI / 180)
'{0,10:N6} {1,10:N6}' -f [Math]::Tan($rad), [Math]::Tan($deg * [Math]::PI / 180)
$temp = [Math]::Asin([Math]::Sin($rad))
'{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 / [Math]::PI)
$temp = [Math]::Acos([Math]::Cos($rad))
'{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 / [Math]::PI)
$temp = [Math]::Atan([Math]::Tan($rad))
'{0,10:N6} {1,10:N6}' -f $temp, ($temp * 180 / [Math]::PI) |
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.
| #PHP | PHP | class Node {
private $left;
private $right;
private $value;
function __construct($value) {
$this->value = $value;
}
public function getLeft() {
return $this->left;
}
public function getRight() {
return $this->right;
}
public function getValue() {
return $this->value;
}
public function setLeft($value) {
$this->left = $value;
}
public function setRight($value) {
$this->right = $value;
}
public function setValue($value) {
$this->value = $value;
}
}
class TreeTraversal {
public function preOrder(Node $n) {
echo $n->getValue() . " ";
if($n->getLeft() != null) {
$this->preOrder($n->getLeft());
}
if($n->getRight() != null){
$this->preOrder($n->getRight());
}
}
public function inOrder(Node $n) {
if($n->getLeft() != null) {
$this->inOrder($n->getLeft());
}
echo $n->getValue() . " ";
if($n->getRight() != null){
$this->inOrder($n->getRight());
}
}
public function postOrder(Node $n) {
if($n->getLeft() != null) {
$this->postOrder($n->getLeft());
}
if($n->getRight() != null){
$this->postOrder($n->getRight());
}
echo $n->getValue() . " ";
}
public function levelOrder($arg) {
$q[] = $arg;
while (!empty($q)) {
$n = array_shift($q);
echo $n->getValue() . " ";
if($n->getLeft() != null) {
$q[] = $n->getLeft();
}
if($n->getRight() != null){
$q[] = $n->getRight();
}
}
}
}
$arr = [];
for ($i=1; $i < 10; $i++) {
$arr[$i] = new Node($i);
}
$arr[6]->setLeft($arr[8]);
$arr[6]->setRight($arr[9]);
$arr[3]->setLeft($arr[6]);
$arr[4]->setLeft($arr[7]);
$arr[2]->setLeft($arr[4]);
$arr[2]->setRight($arr[5]);
$arr[1]->setLeft($arr[2]);
$arr[1]->setRight($arr[3]);
$tree = new TreeTraversal($arr);
echo "preorder:\t";
$tree->preOrder($arr[1]);
echo "\ninorder:\t";
$tree->inOrder($arr[1]);
echo "\npostorder:\t";
$tree->postOrder($arr[1]);
echo "\nlevel-order:\t";
$tree->levelOrder($arr[1]); |
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
| #Oz | Oz | for T in {String.tokens "Hello,How,Are,You,Today" &,} do
{System.printInfo T#"."}
end |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #PARI.2FGP | PARI/GP |
\\ Tokenize a string str according to 1 character delimiter d. Return a list of tokens.
\\ Using ssubstr() from http://rosettacode.org/wiki/Substring#PARI.2FGP
\\ tokenize() 3/5/16 aev
tokenize(str,d)={
my(str=Str(str,d),vt=Vecsmall(str),d1=sasc(d),Lr=List(),sn=#str,v1,p1=1);
for(i=p1,sn, v1=vt[i]; if(v1==d1, listput(Lr,ssubstr(str,p1,i-p1)); p1=i+1));
return(Lr);
}
{
\\ TEST
print(" *** Testing tokenize from Version #1:");
print("1.", tokenize("Hello,How,Are,You,Today",","));
\\ BOTH 2 & 3 are NOT OK!!
print("2.",tokenize("Hello,How,Are,You,Today,",","));
print("3.",tokenize(",Hello,,How,Are,You,Today",","));
}
|
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
| #PureBasic | PureBasic | Structure Employees
Name$
ID$
Salary.i
Department$
EndStructure
Procedure displayTopEarners(List MyEmployees.Employees(), n)
Protected filename$ = OpenFileRequester("Top rank per group", "DataFile.txt", "", 0)
If ReadFile(0, filename$)
Protected InData.Employees, txt.s, MaxNameLength
While Eof(0) = 0
AddElement(MyEmployees())
txt = ReadString(0)
With MyEmployees()
\Name$ = StringField(txt, 1, ",")
\ID$ = StringField(txt, 2, ",")
\Salary = Val(StringField(txt, 3, ","))
\Department$ = StringField(txt, 4, ",")
If Len(\Name$) > MaxNameLength: MaxNameLength = Len(\Name$): EndIf
EndWith
Wend
CloseFile(0)
Else
MessageRequester("Information", "Couldn't open the file!")
End
EndIf
If OpenConsole()
Protected OldDepartment$, count
SortStructuredList(MyEmployees(), #PB_Sort_Descending, OffsetOf(Employees\Salary), #PB_Sort_integer)
SortStructuredList(MyEmployees(), #PB_Sort_Ascending, OffsetOf(Employees\Department$), #PB_Sort_String)
ForEach MyEmployees()
With MyEmployees()
If \Department$ <> OldDepartment$
If OldDepartment$ <> ""
PrintN(#CRLF$)
EndIf
OldDepartment$ = \Department$
PrintN("Department " + \Department$ + #CRLF$ + "---------------")
PrintN(LSet("Name", MaxNameLength + 3) + LSet("ID", 7) + LSet("Salary", 7))
count = 0
EndIf
count + 1
If count <= n
PrintN(LSet(\Name$, MaxNameLength + 1) + " " + RSet(\ID$, 7) + " $" + Str(\Salary))
EndIf
EndWith
Next
PrintN(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
EndIf
EndProcedure
NewList MyEmployees.Employees()
displayTopEarners(MyEmployees(), 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.
| #Raku | Raku | my @board = 1..9;
my @winning-positions = [0..2], [3..5], [6..8], [0,3,6], [1,4,7], [2,5,8],
[0,4,8], [6,4,2];
sub get-winner() {
for @winning-positions {
return (@board[|$_][0], $_) if [eq] @board[|$_];
}
}
sub free-indexes() {
@board.keys.grep: { @board[$_] eq any(1..9) }
}
sub ai-move() {
given free-indexes.pick {
@board[$_] = 'o';
say "I go at: { $_ + 1 }\n";
}
}
sub print-board() {
print "\e[2J";
say @board.map({ "$^a | $^b | $^c" }).join("\n--+---+--\n"), "\n";
}
sub human-move() {
my $pos = prompt "Choose one of { (free-indexes() »+» 1).join(",") }: ";
if $pos eq any(free-indexes() »+» 1) {
@board[$pos - 1] = 'x';
} else {
say "Sorry, you want to put your 'x' where?";
human-move();
}
}
for flat (&ai-move, &human-move) xx * {
print-board;
last if get-winner() or not free-indexes;
.();
}
if get-winner() -> ($player, $across) {
say "$player wins across [", ($across »+» 1).join(", "), "].";
} else {
say "How boring, a draw!";
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Icon_and_Unicon | Icon and Unicon | procedure main(arglist)
hanoi(arglist[1]) | stop("Usage: hanoi n\n\rWhere n is the number of disks to move.")
end
#procedure hanoi(n:integer, needle1:1, needle2:2) # unicon shorthand for icon code 1,2,3 below
procedure hanoi(n, needle1, needle2) #: solve towers of hanoi by moving n disks from needle 1 to needle2 via other
local other
n := integer(0 < n) | runerr(n,101) # 1 ensure integer (this also ensures it's positive too)
/needle1 := 1 # 2 default
/needle2 := 2 # 3 default
if n = 1 then
write("Move disk from ", needle1, " to ", needle2)
else {
other := 6 - needle1 - needle2 # clever but somewhat un-iconish way to find other
hanoi(n-1, needle1, other)
write("Move disk from ", needle1, " to ", needle2)
hanoi(n-1, other, needle2)
}
return
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.
| #PureBasic | PureBasic | OpenConsole()
Macro DegToRad(deg)
deg*#PI/180
EndMacro
Macro RadToDeg(rad)
rad*180/#PI
EndMacro
degree = 45
radians.f = #PI/4
PrintN(StrF(Sin(DegToRad(degree)))+" "+StrF(Sin(radians)))
PrintN(StrF(Cos(DegToRad(degree)))+" "+StrF(Cos(radians)))
PrintN(StrF(Tan(DegToRad(degree)))+" "+StrF(Tan(radians)))
arcsin.f = ASin(Sin(radians))
PrintN(StrF(arcsin)+" "+Str(RadToDeg(arcsin)))
arccos.f = ACos(Cos(radians))
PrintN(StrF(arccos)+" "+Str(RadToDeg(arccos)))
arctan.f = ATan(Tan(radians))
PrintN(StrF(arctan)+" "+Str(RadToDeg(arctan)))
Input() |
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.
| #PicoLisp | PicoLisp | (de preorder (Node Fun)
(when Node
(Fun (car Node))
(preorder (cadr Node) Fun)
(preorder (caddr Node) Fun) ) )
(de inorder (Node Fun)
(when Node
(inorder (cadr Node) Fun)
(Fun (car Node))
(inorder (caddr Node) Fun) ) )
(de postorder (Node Fun)
(when Node
(postorder (cadr Node) Fun)
(postorder (caddr Node) Fun)
(Fun (car Node)) ) )
(de level-order (Node Fun)
(for (Q (circ Node) Q)
(let N (fifo 'Q)
(Fun (car N))
(and (cadr N) (fifo 'Q @))
(and (caddr N) (fifo 'Q @)) ) ) )
(setq *Tree
(1
(2 (4 (7)) (5))
(3 (6 (8) (9))) ) )
(for Order '(preorder inorder postorder level-order)
(prin (align -13 (pack Order ":")))
(Order *Tree printsp)
(prinl) ) |
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
| #Pascal | Pascal | program TokenizeString;
{$mode objfpc}{$H+}
uses
SysUtils, Classes;
const
TestString = 'Hello,How,Are,You,Today';
var
Tokens: TStringList;
I: Integer;
begin
// Uses FCL facilities, "harder" algorithm not implemented
Tokens := TStringList.Create;
try
Tokens.Delimiter := ',';
Tokens.DelimitedText := TestString;
Tokens.Delimiter := '.'; // For example
// To standard Output
WriteLn(Format('Tokenize from: "%s"', [TestString]));
WriteLn(Format('to: "%s"',[Tokens.DelimitedText]));
finally
Tokens.Free;
end;
end. |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Perl | Perl | print join('.', split /,/, 'Hello,How,Are,You,Today'), "\n"; |
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
| #Python | Python | from collections import defaultdict
from heapq import nlargest
data = [('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')]
departments = defaultdict(list)
for rec in data[1:]:
departments[rec[-1]].append(rec)
N = 3
format = " %-15s " * len(data[0])
for department, recs in sorted(departments.items()):
print ("Department %s" % department)
print (format % data[0])
for rec in nlargest(N, recs, key=lambda rec: rec[-2]):
print (format % rec)
print('') |
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.
| #REXX | REXX | /*REXX program plays (with a human) the tic─tac─toe game on an NxN grid. */
$= copies('─', 9) /*eyecatcher for error messages, prompt*/
oops = $ '***error*** ' /*literal for when an error happens. */
single = '│─┼'; jam= "║"; bar= '═'; junc= "╬"; dbl=jam || bar || junc
sw = linesize() - 1 /*obtain width of the terminal (less 1)*/
parse arg N hm cm .,@. /*obtain optional arguments from the CL*/
if N=='' | N=="," then N=3; oN=N /*N not specified? Then use default.*/
N = abs(N) /*if N < 0. then computer goes first. */
NN = N*N /*calculate the square of N. */
middle = NN % 2 + N % 2 /* " " middle " the grid. */
if N<2 then do; say oops 'tic─tac─toe grid is too small: ' N; exit 13; end
pad= left('', sw % NN) /*display padding: 6x6 in 80 columns.*/
if hm=='' then hm= "X"; /*define the marker for a human. */
if cm=='' then cm= "O" /* " " " " the computer. */
hm= aChar(hm, 'human') /*determine if the marker is legitimate*/
cm= aChar(cm, 'computer') /* " " " " " " */
parse upper value hm cm with uh uc /*use uppercase values is markers: X x*/
if uh==uc then cm= word('O X', 1 + (uh=="O") ) /*The human wants Hal's marker? Swap. */
if oN<0 then call Hmove middle /*Hal moves first? Then choose middling*/
else call showGrid /*showGrid also checks for wins & draws*/
/*tic─tac─toe game───►*/ do forever /*'til the cows come home (or QUIT). */
/*tic─tac─toe game───►*/ call CBLF /*process carbon─based lifeform's move.*/
/*tic─tac─toe game───►*/ call Hal /*determine Hal's (the computer) move.*/
/*tic─tac─toe game───►*/ end /*forever*/ /*showGrid subroutine does wins & draws*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
aChar: parse arg x,whoseX; L=length(x) /*process markers.*/
if L==1 then return testB( x ) /*1 char, as is. */
if L==2 & datatype(x, 'X') then return testB( x2c(x) ) /*2 chars, hex. */
if L==3 & datatype(x, 'W') & , /*3 chars, decimal*/
x>=0 & x<256 then return testB( d2c(x) ) /*···and in range.*/
say oops 'illegal character or character code for' whoseX "marker: " x
exit 13 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
CBLF: prompt='Please enter a cell number to place your next marker ['hm"] (or Quit):"
do forever; say $ prompt
parse pull x 1 ux 1 ox; upper ux /*get versions of answer; uppercase ux*/
if datatype(ox, 'W') then ox=ox / 1 /*normalize cell number: +0007 ───► 7 */
/*(division by unity normalizes a num.)*/
select /*perform some validations of X (cell#)*/
when abbrev('QUIT',ux,1) then call tell 'quitting.'
when x='' then iterate /*Nada? Try again.*/
when words(x)\==1 then say oops "too many" cell# 'specified:' x
when \datatype(x, 'N') then say oops "cell number isn't numeric: " x
when \datatype(x, 'W') then say oops "cell number isn't an integer: " x
when x=0 then say oops "cell number can't be zero: " x
when x<0 then say oops "cell number can't be negative: " x
when x>NN then say oops "cell number can't exceed " NN
when @.ox\=='' then say oops "cell number is already occupied: " x
otherwise leave /*forever*/
end /*select*/
end /*forever*/
/* [↓] OX is a normalized version of X*/
@.ox= hm /*place a marker for the human (CLBF). */
call showGrid /*and display the tic─tac─toe grid. */
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
Hal: select /*Hal tries various moves. */
when win(cm, N-1) then call Hmove , ec /*is this the winning move?*/
when win(hm, N-1) then call Hmove , ec /* " " a blocking " */
when @.middle== '' then call Hmove middle /*pick the center cell. */
when @.N.N == '' then call Hmove , N N /*bottom right corner cell.*/
when @.N.1 == '' then call Hmove , N 1 /* " left " " */
when @.1.N == '' then call Hmove , 1 N /* top right " " */
when @.1.1 == '' then call Hmove , 1 1 /* " left " " */
otherwise call Hmove , ac /*pick a blank cell in grid*/
end /*select*/
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
Hmove: parse arg Hplace,dr dc; if Hplace=='' then Hplace = (dr - 1)*N + dc
@.Hplace= cm /*place computer's marker. */
say; say $ 'computer places a marker ['cm"] at cell number " Hplace
call showGrid
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
showGrid: _= 0; cW= 5; cH= 3; open= 0 /*cell width, cell height.*/
do r=1 for N /*construct array of cells.*/
do c=1 for N; _= _ + 1; @.r.c= @._; open= open | @._==''
end /*c*/
end /*r*/ /* [↑] OPEN≡a cell is open*/
say /* [↑] create grid coörds.*/
z= 0; do j=1 for N /* [↓] show grids&markers.*/
do t=1 for cH; _=; __= /*MK is a marker in a cell.*/
do k=1 for N; if t==2 then z= z + 1; mk=; c#=
if t==2 then do; mk= @.z; c#= z /*c# is cell number*/
end
_= _ || jam || center(mk, cW)
__= __ || jam || center(c#, cW)
end /*k*/
say pad substr(_, 2) pad translate( substr(__, 2), single, dbl)
end /*t*/ /* [↑] show a line*/
if j==N then leave
_=
do b=1 for N; _= _ || junc || copies(bar, cW)
end /*b*/ /* [↑] a grid part*/
say pad substr(_, 2) pad translate( substr(_, 2), single, dbl)
end /*j*/
say
if win(hm) then call tell 'You ('hm") won"copies('!',random(1, 5) )
if win(cm) then call tell 'The computer ('cm") won."
if \open then call tell 'This tic─tac─toe game is a draw (a cat scratch).'
return
/*──────────────────────────────────────────────────────────────────────────────────────*/
tell: do 4; say; end; say center(' 'arg(1)" ", sw, '─'); do 5; say; end; exit
/*──────────────────────────────────────────────────────────────────────────────────────*/
testB: parse arg bx; if bx\==' ' then return bx /*test if the marker isn't a blank.*/
say oops 'character code for' whoseX "marker can't be a blank."
exit 13 /*stick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
win: parse arg wm,w; if w=='' then w= N /* [↓] see if there is a win. */
ac= /* [↓] EC ≡ means Empty Cell. */
do r=1 for N; _= 0; ec= /*see if any rows are a winner*/
do c=1 for N; _= _ + (@.r.c==wm) /*count the # of markers in col*/
if @.r.c=='' then ec= r c /*Cell empty? Then remember it*/
end /*c*/ /* [↓] AC≡means available cell*/
if ec\=='' then ac=ec /*Found an empty? Then use it.*/
if _==N | (_>=w & ec\=='') then return 1==1 /*a winner has been determined.*/
end /*r*/ /*w=N-1? Checking for near win*/
do c=1 for N; _= 0; ec= /*see if any cols are a winner*/
do r=1 for N; _= _ + (@.r.c==wm) /*count the # of markers in row*/
if @.r.c=='' then ec= r c /*Cell empty? Then remember it*/
end /*r*/
if ec\=='' then ac= ec /*Found an empty? Then remember*/
if _==N | (_>=w & ec\=='') then return 1==1 /*a winner has been determined.*/
end /*c*/
_= 0; ec= /*EC≡location of an empty cell.*/
do d=1 for N; _= _ + (@.d.d==wm) /*A winning descending diag. ? */
if @.d.d=='' then ec= d d /*Empty cell? Then note cell #*/
end /*d*/
if _==N | (_>=w & ec\=='') then return 1==1 /*a winner has been determined.*/
_= 0; r= 1
do c=N for N by -1; _=_ + (@.r.c==wm) /*A winning ascending diagonal?*/
if @.r.c=='' then ec= r c /*Empty cell? Then note cell #*/
r= r + 1 /*bump the counter for the rows*/
end /*c*/
if _==N | (_>=w & ec\=='') then return 1==1 /*a winner has been determined.*/
return 0==1 /*no winner " " " */ |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Inform_7 | Inform 7 | Hanoi is a room.
A post is a kind of supporter. A post is always fixed in place.
The left post, the middle post, and the right post are posts in Hanoi.
A disk is a kind of supporter.
The red disk is a disk on the left post.
The orange disk is a disk on the red disk.
The yellow disk is a disk on the orange disk.
The green disk is a disk on the yellow disk.
Definition: a disk is topmost if nothing is on it.
When play begins:
move 4 disks from the left post to the right post via the middle post.
To move (N - number) disk/disks from (FP - post) to (TP - post) via (VP - post):
if N > 0:
move N - 1 disks from FP to VP via TP;
say "Moving a disk from [FP] to [TP]...";
let D be a random topmost disk enclosed by FP;
if a topmost disk (called TD) is enclosed by TP, now D is on TD;
otherwise now D is on TP;
move N - 1 disks from VP to TP via FP. |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Io | Io | hanoi := method(n, from, to, via,
if (n == 1) then (
writeln("Move from ", from, " to ", to)
) else (
hanoi(n - 1, from, via, to )
hanoi(1 , from, to , via )
hanoi(n - 1, via , to , from)
)
) |
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.
| #Python | Python | Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> from math import degrees, radians, sin, cos, tan, asin, acos, atan, pi
>>> rad, deg = pi/4, 45.0
>>> print("Sine:", sin(rad), sin(radians(deg)))
Sine: 0.7071067811865475 0.7071067811865475
>>> print("Cosine:", cos(rad), cos(radians(deg)))
Cosine: 0.7071067811865476 0.7071067811865476
>>> print("Tangent:", tan(rad), tan(radians(deg)))
Tangent: 0.9999999999999999 0.9999999999999999
>>> arcsine = asin(sin(rad))
>>> print("Arcsine:", arcsine, degrees(arcsine))
Arcsine: 0.7853981633974482 44.99999999999999
>>> arccosine = acos(cos(rad))
>>> print("Arccosine:", arccosine, degrees(arccosine))
Arccosine: 0.7853981633974483 45.0
>>> arctangent = atan(tan(rad))
>>> print("Arctangent:", arctangent, degrees(arctangent))
Arctangent: 0.7853981633974483 45.0
>>> |
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.
| #Prolog | Prolog | tree :-
Tree= [1,
[2,
[4,
[7, nil, nil],
nil],
[5, nil, nil]],
[3,
[6,
[8, nil, nil],
[9,nil, nil]],
nil]],
write('preorder : '), preorder(Tree), nl,
write('inorder : '), inorder(Tree), nl,
write('postorder : '), postorder(Tree), nl,
write('level-order : '), level_order([Tree]).
preorder(nil).
preorder([Node, FG, FD]) :-
format('~w ', [Node]),
preorder(FG),
preorder(FD).
inorder(nil).
inorder([Node, FG, FD]) :-
inorder(FG),
format('~w ', [Node]),
inorder(FD).
postorder(nil).
postorder([Node, FG, FD]) :-
postorder(FG),
postorder(FD),
format('~w ', [Node]).
level_order([]).
level_order(A) :-
level_order_(A, U-U, S),
level_order(S).
level_order_([], S-[],S).
level_order_([[Node, FG, FD] | T], CS, FS) :-
format('~w ', [Node]),
append_dl(CS, [FG, FD|U]-U, CS1),
level_order_(T, CS1, FS).
level_order_([nil | T], CS, FS) :-
level_order_(T, CS, FS).
append_dl(X-Y, Y-Z, X-Z).
|
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
| #Phix | Phix | ?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
| #Phixmonti | Phixmonti | /# "Hello,How,Are,You,Today" "," "." subst print #/
"Hello,How,Are,You,Today" "," " " subst split len for get print "." print endfor |
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
| #R | R | dfr <- read.csv(tc <- textConnection(
"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")); close(tc) |
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.
| #Ring | Ring |
Load "guilib.ring"
#Provide a list to save each button status in numeric readable format
#0=nothing 1=X 2=O
lst=[]
#Provide onScreen button status and style
btns=[]
#Define who has the turn
isXTurn=true
app=new qApp
{
frmMain=new qMainWindow()
{
setWindowTitle("TicTacToe!")
resize(300,320)
move(200,200)
//buttons
pos=0
for y=0 to 2
for x=0 to 2
//Creating Buttons on the screen
pos++
Add(lst,0)
Add(btns,new qPushButton(frmMain)
{
setGeometry(x*100,y*100,100,100)
setText("-")
setclickevent("Disp(" + pos +")")
setstylesheet("font-size:24pt ; font: bold ; color:yellow ; background-color: green")
})
next
next
//StatusBar
status=new qStatusBar(frmMain)
{
showMessage("Ready",0)
}
setwindowflags(Qt_dialog)
setStatusbar(status)
show()
}
exec()
}
//Restart the game by re init buttons status
func reStart
for i=1 to 9
lst[i]=0
btns[i].setText("-")
next
isXTurn=true
func Disp x
if isXTurn=true and lst[x]=0
btns[x].setText("X")
lst[x]=1
isXTurn=false
but isXTurn=false and lst[x]=0
btns[x].setText("O")
lst[x]=2
isXTurn=true
ok
winner = CheckWinner()
#if there is no Winner and still there is ability to winner
#continue playing.
if winner<1 return ok
//Who is the winner!
switch winner
on 1
new qMessagebox(frmMain)
{
SetWindowTitle("We have a winner!")
SetText("Good job X you won!")
show()
}
on 2
new qMessagebox(frmMain)
{
SetWindowTitle("We have a winner!")
SetText("Good job O you won!")
show()
}
on 3
new qMessagebox(frmMain)
{
SetWindowTitle("Oh no it's a tie")
SetText("Oh no it's a tie!")
show()
}
off
reStart()
func CheckWinner
//vertical check
for v=1 to 9 step 3
if lst[v]!=0 and lst[v+1]!=0 and lst[v+2]!=0
if lst[v]=lst[v+1] and lst[v+1]=lst[v+2]
return lst[v]
ok
ok
next
//horzintal
for h=1 to 3
if lst[h]!=0 and lst[h+3]!=0 and lst[h+6]!=0
if lst[h]=lst[h+3] and lst[h+3]=lst[h+6]
return lst[h]
ok
ok
next
//Cross
if lst[1]!=0 and lst[5]!=0 and lst[9]!=0
if lst[1]=lst[5] and lst[5]=lst[9] return lst[1] ok
ok
if lst[3]!=0 and lst[5]!=0 and lst[7]!=0
if lst[3]=lst[5] and lst[5]=lst[7] return lst[3] ok
ok
//tie
tie=true
for i=1 to 9
if lst[i]=0 tie=false exit ok
next
if tie=true return 3 ok return 0
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Ioke | Ioke | = method(n, f, u, t,
if(n < 2,
"#{f} --> #{t}" println,
H(n - 1, f, t, u)
"#{f} --> #{t}" println
H(n - 1, u, f, t)
)
)
hanoi = method(n,
H(n, 1, 2, 3)
) |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #IS-BASIC | IS-BASIC | 100 PROGRAM "Hanoi.bas"
110 CALL HANOI(4,1,3,2)
120 DEF HANOI(DISK,FRO,TO,WITH)
130 IF DISK>0 THEN
140 CALL HANOI(DISK-1,FRO,WITH,TO)
150 PRINT "Move disk";DISK;"from";FRO;"to";TO
160 CALL HANOI(DISK-1,WITH,TO,FRO)
170 END IF
180 END DEF |
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.
| #Quackery | Quackery | [ $" bigrat.qky' loadfile ] now!
[ 2646693125139304345
1684937174853026414 ] is pi/2 ( --> n/d )
[ 2dup
2dup 3 v** 2363 18183 v* v-
2over 5 v** 12671 4363920 v* v+
2swap 1 1
2over 2 v** 445 12122 v* v+
2over 4 v** 601 872784 v* v+
2swap 6 v** 121 16662240 v* v+
v/ ] is sin ( n/d --> n/d )
[ 1 1
2over 2 v** 3665 7788 v* v-
2over 4 v** 711 25960 v* v+
2over 6 v** 2923 7850304 v* v-
2swap 1 1
2over 2 v** 229 7788 v* v+
2over 4 v** 1 2360 v* v+
2swap 6 v** 127 39251520 v* v+
v/ ] is cos ( n/d --> n/d )
[ 2dup
2dup 3 v** 5 39 v* v-
2over 5 v** 2 715 v* v+
2over 7 v** 1 135135 v* v-
2swap 1 1
2over 2 v** 6 13 v* v-
2over 4 v** 10 429 v* v+
2swap 6 v** 4 19305 v* v-
v/ ] is tan ( n/d --> n/d )
[ 2dup
2dup 3 v** 2318543 2278617 v* v-
2over 5 v** 12022609 60763120 v* v+
2swap 1 1
2over 2 v** 1798875 1519078 v* v-
2over 4 v** 3891575 12152624 v* v+
2swap 6 v** 4695545 510410208 v* v-
v/ ] is arcsin ( n/d --> n/d )
[ pi/2 2swap arcsin v- ] is arccos ( n/d --> n/d )
[ 2dup
2dup 3 v** 50 39 v* v+
2over 5 v** 283 715 v* v+
2over 7 v** 256 15015 v* v+
2swap 1 1
2over 2 v** 21 13 v* v+
2over 4 v** 105 143 v* v+
2swap 6 v** 35 429 v* v+
v/ ] is arctan ( n/d --> n/d )
[ pi/2 v* 90 1 v/ ] is deg->rad ( n/d --> n/d )
[ pi/2 v/ 90 1 v* ] is rad->deg ( n/d --> n/d )
say "With an argument of 0.5 radians"
cr cr
$ "0.5" $->v drop
sin
say "Sin approximation: " 20 point$ echo$ cr
say " Actual value: 0.47942553860420300027..."
cr cr
$ "0.5" $->v drop
cos
say "Cos approximation: " 20 point$ echo$ cr
say " Actual value: 0.87758256189037271611..."
cr cr
$ "0.5" $->v drop
tan
say "Tan approximation: " 20 point$ echo$ cr
say " Actual value: 0.54630248984379051325..."
cr cr cr
say "To radians, using approximated values from previous computations"
cr cr
$ "0.47942553860423933121" $->v drop
arcsin
say "Arcsin approximation: " 20 point$ echo$ cr
say " Actual value: 0.5"
cr cr
$ "0.87758256189037190908" $->v drop
arccos
say "Arccos approximation: " 20 point$ echo$ cr
say " Actual value: 0.5"
cr cr
$ "0.54630248984379037103" $->v drop
arctan
say "Arctan approximation: " 20 point$ echo$ cr
say " Actual value: 0.5"
cr cr cr
say "0.5 radians is approx 28.64788976 degrees" cr
cr
$ "28.64788976" $->v drop
deg->rad sin
say "Sin approximation: " 20 point$ echo$ cr
say " Actual value: 0.47942553865718102604..."
cr cr
$ "28.64788976" $->v drop
deg->rad cos
say "Cos approximation: " 20 point$ echo$ cr
say " Actual value: 0.87758256186143068872..."
cr cr
$ "28.64788976" $->v drop
deg->rad tan
say "Tan approximation: " 20 point$ echo$ cr
say " Actual value: 0.54630248992217530618..."
cr cr cr
say "To degrees, using approximated values from previous computations"
cr cr
$ "0.47942553865721735699" $->v drop
arcsin rad->deg
say "Arcsin approximation: " 20 point$ echo$ cr
say " Actual value: 28.64788976..."
cr cr
$ "0.87758256186142988169" $->v drop
arccos rad->deg
say "Arccos approximation: " 20 point$ echo$ cr
say " Actual value: 28.64788976..."
cr cr
$ "0.54630248992217516396" $->v drop
arctan rad->deg
say "Arctan approximation: " 20 point$ echo$ cr
say " Actual value: 28.64788976..." |
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.
| #R | R | deg <- function(radians) 180*radians/pi
rad <- function(degrees) degrees*pi/180
sind <- function(ang) sin(rad(ang))
cosd <- function(ang) cos(rad(ang))
tand <- function(ang) tan(rad(ang))
asind <- function(v) deg(asin(v))
acosd <- function(v) deg(acos(v))
atand <- function(v) deg(atan(v))
r <- pi/3
rd <- deg(r)
print( c( sin(r), sind(rd)) )
print( c( cos(r), cosd(rd)) )
print( c( tan(r), tand(rd)) )
S <- sin(pi/4)
C <- cos(pi/3)
T <- tan(pi/4)
print( c( asin(S), asind(S) ) )
print( c( acos(C), acosd(C) ) )
print( c( atan(T), atand(T) ) ) |
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.
| #PureBasic | PureBasic | Structure node
value.i
*left.node
*right.node
EndStructure
Structure queue
List q.i()
EndStructure
DataSection
tree:
Data.s "1(2(4(7),5),3(6(8,9)))"
EndDataSection
;Convenient routine to interpret string data to construct a tree of integers.
Procedure createTree(*n.node, *tPtr.Character)
Protected num.s, *l.node, *ntPtr.Character
Repeat
Select *tPtr\c
Case '0' To '9'
num + Chr(*tPtr\c)
Case '('
*n\value = Val(num): num = ""
*ntPtr = *tPtr + 1
If *ntPtr\c = ','
ProcedureReturn *tPtr
Else
*l = AllocateMemory(SizeOf(node))
*n\left = *l: *tPtr = createTree(*l, *ntPtr)
EndIf
Case ')', ',', #Null
If num: *n\value = Val(num): EndIf
ProcedureReturn *tPtr
EndSelect
If *tPtr\c = ','
*l = AllocateMemory(SizeOf(node)):
*n\right = *l: *tPtr = createTree(*l, *tPtr + 1)
EndIf
*tPtr + 1
ForEver
EndProcedure
Procedure enqueue(List q.i(), element)
LastElement(q())
AddElement(q())
q() = element
EndProcedure
Procedure dequeue(List q.i())
Protected element
If FirstElement(q())
element = q()
DeleteElement(q())
EndIf
ProcedureReturn element
EndProcedure
Procedure onVisit(*n.node)
Print(Str(*n\value) + " ")
EndProcedure
Procedure preorder(*n.node) ;recursive
onVisit(*n)
If *n\left
preorder(*n\left)
EndIf
If *n\right
preorder(*n\right)
EndIf
EndProcedure
Procedure inorder(*n.node) ;recursive
If *n\left
inorder(*n\left)
EndIf
onVisit(*n)
If *n\right
inorder(*n\right)
EndIf
EndProcedure
Procedure postorder(*n.node) ;recursive
If *n\left
postorder(*n\left)
EndIf
If *n\right
postorder(*n\right)
EndIf
onVisit(*n)
EndProcedure
Procedure levelorder(*n.node)
Dim q.queue(1)
Protected readQueue = 1, writeQueue, *currNode.node
enqueue(q(writeQueue)\q(),*n) ;start queue off with root
Repeat
readQueue ! 1: writeQueue ! 1
While ListSize(q(readQueue)\q())
*currNode = dequeue(q(readQueue)\q())
If *currNode\left
enqueue(q(writeQueue)\q(),*currNode\left)
EndIf
If *currNode\right
enqueue(q(writeQueue)\q(),*currNode\right)
EndIf
onVisit(*currNode)
Wend
Until ListSize(q(writeQueue)\q()) = 0
EndProcedure
If OpenConsole()
Define root.node
createTree(root,?tree)
Print("preorder: ")
preorder(root)
PrintN("")
Print("inorder: ")
inorder(root)
PrintN("")
Print("postorder: ")
postorder(root)
PrintN("")
Print("levelorder: ")
levelorder(root)
PrintN("")
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
Input()
CloseConsole()
EndIf |
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
| #PHP | PHP | <?php
$str = 'Hello,How,Are,You,Today';
echo implode('.', explode(',', $str));
?> |
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
| #Picat | Picat | import util.
go =>
S = "Hello,How,Are,You,Today",
T = S.split(","),
println(T),
T.join(".").println(),
% As a one liner:
S.split(",").join(".").println(). |
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
| #Racket | Racket | #lang racket
(struct employee (name id salary dept))
(define employees
(list (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")))
(define (top/dept N)
(for/list ([dept (remove-duplicates (map employee-dept employees))])
(define people
(filter (λ(e) (equal? dept (employee-dept e))) employees))
(cons dept (take (sort people > #:key employee-salary) N))))
(for ([dept (top/dept 2)])
(printf "Department ~a:\n" (car dept))
(for ([e (cdr dept)])
(printf " $~a: ~a (~a)\n"
(employee-salary e)
(employee-name e)
(employee-id e))))
|
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.
| #Ruby | Ruby | module TicTacToe
LINES = [[1,2,3],[4,5,6],[7,8,9],[1,4,7],[2,5,8],[3,6,9],[1,5,9],[3,5,7]]
class Game
def initialize(player_1_class, player_2_class)
@board = Array.new(10) # we ignore index 0 for convenience
@current_player_id = 0
@players = [player_1_class.new(self, "X"), player_2_class.new(self, "O")]
puts "#{current_player} goes first."
end
attr_reader :board, :current_player_id
def play
loop do
place_player_marker(current_player)
if player_has_won?(current_player)
puts "#{current_player} wins!"
print_board
return
elsif board_full?
puts "It's a draw."
print_board
return
end
switch_players!
end
end
def free_positions
(1..9).select {|position| @board[position].nil?}
end
def place_player_marker(player)
position = player.select_position!
puts "#{player} selects #{player.marker} position #{position}"
@board[position] = player.marker
end
def player_has_won?(player)
LINES.any? do |line|
line.all? {|position| @board[position] == player.marker}
end
end
def board_full?
free_positions.empty?
end
def other_player_id
1 - @current_player_id
end
def switch_players!
@current_player_id = other_player_id
end
def current_player
@players[current_player_id]
end
def opponent
@players[other_player_id]
end
def turn_num
10 - free_positions.size
end
def print_board
col_separator, row_separator = " | ", "--+---+--"
label_for_position = lambda{|position| @board[position] ? @board[position] : position}
row_for_display = lambda{|row| row.map(&label_for_position).join(col_separator)}
row_positions = [[1,2,3], [4,5,6], [7,8,9]]
rows_for_display = row_positions.map(&row_for_display)
puts rows_for_display.join("\n" + row_separator + "\n")
end
end
class Player
def initialize(game, marker)
@game = game
@marker = marker
end
attr_reader :marker
end
class HumanPlayer < Player
def select_position!
@game.print_board
loop do
print "Select your #{marker} position: "
selection = gets.to_i
return selection if @game.free_positions.include?(selection)
puts "Position #{selection} is not available. Try again."
end
end
def to_s
"Human"
end
end
class ComputerPlayer < Player
DEBUG = false # edit this line if necessary
def group_positions_by_markers(line)
markers = line.group_by {|position| @game.board[position]}
markers.default = []
markers
end
def select_position!
opponent_marker = @game.opponent.marker
winning_or_blocking_position = look_for_winning_or_blocking_position(opponent_marker)
return winning_or_blocking_position if winning_or_blocking_position
if corner_trap_defense_needed?
return corner_trap_defense_position(opponent_marker)
end
# could make this smarter by sometimes doing corner trap offense
return random_prioritized_position
end
def look_for_winning_or_blocking_position(opponent_marker)
for line in LINES
markers = group_positions_by_markers(line)
next if markers[nil].length != 1
if markers[self.marker].length == 2
log_debug "winning on line #{line.join}"
return markers[nil].first
elsif markers[opponent_marker].length == 2
log_debug "could block on line #{line.join}"
blocking_position = markers[nil].first
end
end
if blocking_position
log_debug "blocking at #{blocking_position}"
return blocking_position
end
end
def corner_trap_defense_needed?
corner_positions = [1, 3, 7, 9]
opponent_chose_a_corner = corner_positions.any?{|pos| @game.board[pos] != nil}
return @game.turn_num == 2 && opponent_chose_a_corner
end
def corner_trap_defense_position(opponent_marker)
# if you respond in the center or the opposite corner, the opponent can force you to lose
log_debug "defending against corner start by playing adjacent"
# playing in an adjacent corner could also be safe, but would require more logic later on
opponent_position = @game.board.find_index {|marker| marker == opponent_marker}
safe_responses = {1=>[2,4], 3=>[2,6], 7=>[4,8], 9=>[6,8]}
return safe_responses[opponent_position].sample
end
def random_prioritized_position
log_debug "picking random position, favoring center and then corners"
([5] + [1,3,7,9].shuffle + [2,4,6,8].shuffle).find do |pos|
@game.free_positions.include?(pos)
end
end
def log_debug(message)
puts "#{self}: #{message}" if DEBUG
end
def to_s
"Computer#{@game.current_player_id}"
end
end
end
include TicTacToe
Game.new(ComputerPlayer, ComputerPlayer).play
puts
players_with_human = [HumanPlayer, ComputerPlayer].shuffle
Game.new(*players_with_human).play |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #J | J | H =: i.@,&2 ` (({&0 2 1,0 2,{&1 0 2)@$:@<:) @. * NB. tacit using anonymous recursion |
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.
| #Racket | Racket | #lang racket
(define radians (/ pi 4))
(define degrees 45)
(displayln (format "~a ~a" (sin radians) (sin (* degrees (/ pi 180)))))
(displayln (format "~a ~a" (cos radians) (cos (* degrees (/ pi 180)))))
(displayln (format "~a ~a" (tan radians) (tan (* degrees (/ pi 180)))))
(define arcsin (asin (sin radians)))
(displayln (format "~a ~a" arcsin (* arcsin (/ 180 pi))))
(define arccos (acos (cos radians)))
(displayln (format "~a ~a" arccos (* arccos (/ 180 pi))))
(define arctan (atan (tan radians)))
(display (format "~a ~a" arctan (* arctan (/ 180 pi)))) |
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.
| #Raku | Raku | # 20210212 Updated Raku programming solution
sub postfix:<°> (\ᵒ) { ᵒ × τ / 360 }
sub postfix:<㎭🡆°> (\ᶜ) { ᶜ / π × 180 }
say sin π/3 ;
say sin 60° ;
say cos π/4 ;
say cos 45° ;
say tan π/6 ;
say tan 30° ;
( asin(3.sqrt/2), acos(1/sqrt 2), atan(1/sqrt 3) )».&{ .say and .㎭🡆°.say } |
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.
| #Python | Python | from collections import namedtuple
Node = namedtuple('Node', 'data, left, right')
tree = Node(1,
Node(2,
Node(4,
Node(7, None, None),
None),
Node(5, None, None)),
Node(3,
Node(6,
Node(8, None, None),
Node(9, None, None)),
None))
def printwithspace(i):
print(i, end=' ')
def dfs(order, node, visitor):
if node is not None:
for action in order:
if action == 'N':
visitor(node.data)
elif action == 'L':
dfs(order, node.left, visitor)
elif action == 'R':
dfs(order, node.right, visitor)
def preorder(node, visitor = printwithspace):
dfs('NLR', node, visitor)
def inorder(node, visitor = printwithspace):
dfs('LNR', node, visitor)
def postorder(node, visitor = printwithspace):
dfs('LRN', node, visitor)
def ls(node, more, visitor, order='TB'):
"Level-based Top-to-Bottom or Bottom-to-Top tree search"
if node:
if more is None:
more = []
more += [node.left, node.right]
for action in order:
if action == 'B' and more:
ls(more[0], more[1:], visitor, order)
elif action == 'T' and node:
visitor(node.data)
def levelorder(node, more=None, visitor = printwithspace):
ls(node, more, visitor, 'TB')
# Because we can
def reverse_preorder(node, visitor = printwithspace):
dfs('RLN', node, visitor)
def bottom_up_order(node, more=None, visitor = printwithspace, order='BT'):
ls(node, more, visitor, 'BT')
if __name__ == '__main__':
w = 10
for traversal in [preorder, inorder, postorder, levelorder,
reverse_preorder, bottom_up_order]:
if traversal == reverse_preorder:
w = 20
print('\nThe generalisation of function dfs allows:')
if traversal == bottom_up_order:
print('The generalisation of function ls allows:')
print(f"{traversal.__name__:>{w}}:", end=' ')
traversal(tree)
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
| #PicoLisp | PicoLisp | (mapcar pack
(split (chop "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
| #Pike | Pike | ("Hello,How,Are,You,Today" / ",") * "."; |
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
| #Raku | Raku | my @data = do for q:to/---/.lines -> $line {
E10297 32000 D101 Tyler Bennett
E21437 47000 D050 John Rappl
E00127 53500 D101 George Woltman
E63535 18000 D202 Adam Smith
E39876 27800 D202 Claire Buckman
E04242 41500 D101 David McClellan
E01234 49500 D202 Rich Holcomb
E41298 21900 D050 Nathan Adams
E43128 15900 D101 Richard Potter
E27002 19250 D202 David Motsinger
E03033 27000 D101 Tim Sampair
E10001 57000 D190 Kim Arlich
E16398 29900 D190 Timothy Grove
---
$%( < Id Salary Dept Name >
Z=>
$line.split(/ \s\s+ /)
)
}
sub MAIN(Int $N = 3) {
for @data.classify({ .<Dept> }).sort».value {
my @es = .sort: { -.<Salary> }
say '' if (state $bline)++;
say .< Dept Id Salary Name > for @es[^$N]:v;
}
} |
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.
| #Run_BASIC | Run BASIC | ' ---------------------------
' TIC TAC TOE
' ---------------------------
winBox$ = "123 456 789 159 147 258 369 357"
boxPos$ = "123 231 456 564 789 897 159 591 357 753 132 465 798 174 285 396 159 471 582 693 147 258 369 195 375"
ai$ = "519628374"
ox$ = "OX"
[newGame]
for i = 1 to 9
box$(i) = ""
next i
goto [shoTic]
[loop]
for j = 1 to 2
tic$ = mid$(ox$,j,1)
for i = 1 to 25
b$ = word$(boxPos$,i," ")
b1 = val(mid$(b$,1,1))
b2 = val(mid$(b$,2,1))
b3 = val(mid$(b$,3,1))
if box$(b1) = tic$ AND box$(b2) = tic$ AND box$(b3) = "" then
box$(b3) = "O"
goto [shoTic]
end if
next i
next j
if box$(1) = "O" AND box$(5) = "X" and box$(9) = "X" then
if box$(3) = "" then
box$(3) = "O"
goto [shoTic]
end if
if box$(7) = "" then
box$(7) = "O"
goto [shoTic]
end if
end if
for i = 1 to 9
b1 = val(mid$(ai$,i,1))
if box$(b1) = "" then
box$(b1) = "O"
exit for
end if
next i
[shoTic]
cls
' ----------------------------------------
' show tic tac toe screen
' ----------------------------------------
html "<table border=1 width=300px height=225px><TR>"
for i = 1 to 9
html "<td align=center width=33%><h1>"
if box$(i) <> "" then
html box$(i)
else
button #box, " ";box$(i);" ", [doTic]
#box setkey(str$(i))
end if
if i mod 3 = 0 then html "</tr><tr>"
next i
html "</table>"
gosub [checkWin]
wait
[doTic]
box$(val(EventKey$)) = "X"
turn = 1
gosub [checkWin]
goto [loop]
' --- check for a winner ----------
[checkWin]
for i = 1 to 8
b$ = word$(winBox$,i," ")
b1 = val(mid$(b$,1,1))
b2 = val(mid$(b$,2,1))
b3 = val(mid$(b$,3,1))
if box$(b1) = "O" and box$(b2) = "O" and box$(b3) = "O" then
print "You Lose!"
goto [playAgain]
end if
if box$(b1) = "X" and box$(b2) = "X" and box$(b3) = "X" then
print "You Win!"
goto [playAgain]
end if
next i
moveCount = 0
for i = 1 to 9
if box$(i) <> "" then moveCount = moveCount + 1
next i
if moveCount = 9 then
print "Draw!"
goto [playAgain]
end if
RETURN
[playAgain]
input "Play again (y/n)";p$
if upper$(p$) = "Y" then goto [newGame]
end |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Java | Java | public void move(int n, int from, int to, int via) {
if (n == 1) {
System.out.println("Move disk from pole " + from + " to pole " + to);
} else {
move(n - 1, from, via, to);
move(1, from, to, via);
move(n - 1, via, to, from);
}
} |
http://rosettacode.org/wiki/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.
| #RapidQ | RapidQ | $APPTYPE CONSOLE
$TYPECHECK ON
SUB pause(prompt$)
PRINT prompt$
DO
SLEEP .1
LOOP UNTIL LEN(INKEY$) > 0
END SUB
'MAIN
DEFDBL pi , radians , degrees , deg2rad
pi = 4 * ATAN(1)
deg2rad = pi / 180
radians = pi / 4
degrees = 45 * deg2rad
PRINT format$("%.6n" , SIN(radians)) + " " + format$("%.6n" , SIN(degrees))
PRINT format$("%.6n" , COS(radians)) + " " + format$("%.6n" , COS(degrees))
PRINT format$("%.6n" , TAN(radians)) + " " + format$("%.6n" , TAN(degrees))
DEFDBL temp = SIN(radians)
PRINT format$("%.6n" , ASIN(temp)) + " " + format$("%.6n" , ASIN(temp) / deg2rad)
temp = COS(radians)
PRINT format$("%.6n" , ACOS(temp)) + " " + format$("%.6n" , ACOS(temp) / deg2rad)
temp = TAN(radians)
PRINT format$("%.6n" , ATAN(temp)) + " " + format$("%.6n" , ATAN(temp) / deg2rad)
pause("Press any key to continue.")
END 'MAIN |
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.
| #Qi | Qi |
(set *tree* [1 [2 [4 [7]]
[5]]
[3 [6 [8]
[9]]]])
(define inorder
[] -> []
[V] -> [V]
[V L] -> (append (inorder L)
[V])
[V L R] -> (append (inorder L)
[V]
(inorder R)))
(define postorder
[] -> []
[V] -> [V]
[V L] -> (append (postorder L)
[V])
[V L R] -> (append (postorder L)
(postorder R)
[V]))
(define preorder
[] -> []
[V] -> [V]
[V L] -> (append [V]
(preorder L))
[V L R] -> (append [V]
(preorder L)
(preorder R)))
(define levelorder-0
[] -> []
[[] | Q] -> (levelorder-0 Q)
[[V | LR] | Q] -> [V | (levelorder-0 (append Q LR))])
(define levelorder
Node -> (levelorder-0 [Node]))
(preorder (value *tree*))
(postorder (value *tree*))
(inorder (value *tree*))
(levelorder (value *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
| #PL.2FI | PL/I | tok: Proc Options(main);
declare s character (100) initial ('Hello,How,Are,You,Today');
declare n fixed binary (31);
n = tally(s, ',')+1;
begin;
declare table(n) character (50) varying;
declare c character (1);
declare (i, k) fixed binary (31);
table = ''; k = 1;
do i = 1 to length(s);
c = substr(s, i, 1);
if c = ',' then k = k + 1;
else table(k) = table(k) || c;
end;
/* display the table */
table = table || '.';
put skip list (string(table));
end;
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
| #REXX | REXX | /*REXX program displays the top N salaries in each department (internal table). */
parse arg topN . /*get optional # for the top N salaries*/
if topN=='' | topN=="," then topN= 1 /*Not specified? Then use the default.*/
say 'Finding the top ' topN " salaries in each department."; say
@.= /*════════ employee name ID salary dept. ═══════ */
@.1 = "Tyler Bennett ,E10297, 32000, D101"
@.2 = "John Rappl ,E21437, 47000, D050"
@.3 = "George Woltman ,E00127, 53500, D101"
@.4 = "Adam Smith ,E63535, 18000, D202"
@.5 = "Claire Buckman ,E39876, 27800, D202"
@.6 = "David McClellan ,E04242, 41500, D101"
@.7 = "Rich Holcomb ,E01234, 49500, D202"
@.8 = "Nathan Adams ,E41298, 21900, D050"
@.9 = "Richard Potter ,E43128, 15900, D101"
@.10 = "David Motsinger ,E27002, 19250, D202"
@.11 = "Tim Sampair ,E03033, 27000, D101"
@.12 = "Kim Arlich ,E10001, 57000, D190"
@.13 = "Timothy Grove ,E16398, 29900, D190"
depts= /*build people database from @ array.*/
do j=1 until @.j==''; parse var @.j name.j ',' id.j "," sal.j ',' dept.j .
if wordpos(dept.j, depts)==0 then depts= depts dept.j /*a new DEPT?*/
end /*j*/
employees= j-1 /*adjust for the bumped DO loop index.*/
say 'There are ' employees "employees, " words(depts) 'departments: ' depts
say
do dep=1 for words(depts); say /*process each of the departments. */
Xdept= word(depts, dep) /*current department being processed. */
do topN; h= 0; highSal= 0 /*process the top N salaries. */
do e=1 for employees /*process each employee in department. */
if dept.e\==Xdept | sal.e<highSal then iterate /*is this the wrong info?*/
highSal= sal.e; h= e /*a higher salary was just discovered. */
end /*e*/
if h==0 then iterate /*do we have no highest paid this time?*/
say 'department: ' dept.h " $" || sal.h+0 id.h space(name.h)
dept.h= /*make sure we see the employee again. */
end /*topN*/
end /*dep*/ /*stick a fork in it, we're all done. */ |
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.
| #Rust | Rust |
use GameState::{ComputerWin, Draw, PlayerWin, Playing};
use rand::prelude::*;
#[derive(PartialEq, Debug)]
enum GameState {
PlayerWin,
ComputerWin,
Draw,
Playing,
}
type Board = [[char; 3]; 3];
fn main() {
let mut rng = StdRng::from_entropy();
let mut board: Board = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']];
draw_board(board);
loop {
player_turn(&mut board);
if check_win(board) != Playing {
break;
}
computer_turn(&mut rng, &mut board);
if check_win(board) != Playing {
break;
}
draw_board(board);
}
draw_board(board);
let announcement = match check_win(board) {
PlayerWin => "The Player has won!",
ComputerWin => "The Computer has won!",
Draw => "Draw!",
Playing => unreachable!(),
};
println!("{}", announcement);
}
fn is_empty(cell: &char) -> bool {
*cell != 'X' && *cell != 'O'
}
fn check_win(board: Board) -> GameState {
// check for win
for (i, row) in board.iter().enumerate() {
if row[0] == row[1] && row[0] == row[2] {
return which_win(row[0]);
} else if board[0][i] == board[1][i] && board[0][i] == board[2][i] {
return which_win(board[0][i]);
}
}
if board[0][0] == board[1][1] && board[0][0] == board[2][2] {
return which_win(board[0][0]);
} else if board[0][2] == board[1][1] && board[0][2] == board[2][0] {
return which_win(board[0][2]);
}
// check if it's not a draw
let is_draw = board.iter().flatten().any(is_empty);
if is_draw {
Playing
} else {
Draw
}
}
fn which_win(s: char) -> GameState {
match s {
'X' => PlayerWin,
'O' => ComputerWin,
_ => unreachable!(),
}
}
fn player_turn(board: &mut Board) {
use std::io;
println!("Player, enter your field of choice!: ");
let mut ln = String::new();
io::stdin()
.read_line(&mut ln)
.expect("Failed to read stdin");
let choice = ln.trim().parse::<usize>().expect("Failed to parse input");
let row = (choice - 1) / 3;
let col = (choice - 1) % 3;
if board[row][col] == 'X' || board[row][col] == 'O' {
println!("Someone already took this field!");
player_turn(board);
} else {
board[row][col] = 'X';
}
}
fn computer_turn<R: Rng>(rng: &mut R, board: &mut Board) {
let possible_choices: Vec<_> = board
.iter()
.flatten()
.enumerate()
.filter(|&(_, c)| is_empty(c))
.map(|(i, _)| i)
.collect();
let choice = possible_choices.choose(rng).unwrap();
println!("Computer chose: {}", choice);
let row = choice / 3;
let col = choice % 3;
board[row][col] = 'O';
}
fn draw_board(board: Board) {
for row in &board {
println!("{} {} {}", row[0], row[1], row[2]);
}
}
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #JavaScript | JavaScript | function move(n, a, b, c) {
if (n > 0) {
move(n-1, a, c, b);
console.log("Move disk from " + a + " to " + c);
move(n-1, b, a, c);
}
}
move(4, "A", "B", "C"); |
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.
| #REBOL | REBOL | rebol [
Title: "Trigonometric Functions"
URL: http://rosettacode.org/wiki/Trigonometric_Functions
]
radians: pi / 4 degrees: 45.0
; Unlike most languages, REBOL's trig functions work in degrees unless
; you specify differently.
print [sine/radians radians sine degrees]
print [cosine/radians radians cosine degrees]
print [tangent/radians radians tangent degrees]
d2r: func [
"Convert degrees to radians."
d [number!] "Degrees"
][d * pi / 180]
arcsin: arcsine sine degrees
print [d2r arcsin arcsin]
arccos: arccosine cosine degrees
print [d2r arccos arccos]
arctan: arctangent tangent degrees
print [d2r arctan arctan] |
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.
| #Quackery | Quackery | [ this ] is nil ( --> [ )
[ ' [ 1
[ 2
[ 4
[ 7 nil nil ]
nil ]
[ 5 nil nil ] ]
[ 3
[ 6
[ 8 nil nil ]
[ 9 nil nil ] ]
nil ] ] ] is tree ( --> [ )
[ dup nil = iff drop done
unpack swap rot
echo sp
recurse
recurse ] is pre-order ( [ --> )
[ dup nil = iff drop done
unpack unrot
recurse
echo sp
recurse ] is in-order ( [ --> )
[ dup nil = iff drop done
unpack swap
recurse
recurse
echo sp ] is post-order ( [ --> )
[ queue swap push
[ dup empty?
iff drop done
pop
dup nil = iff
drop again
unpack
rot echo sp
dip push push
again ] ] is level-order ( [ --> )
tree pre-order cr
tree in-order cr
tree post-order cr
tree level-order cr |
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
| #PL.2FM | PL/M | 100H:
/* CP/M CALLS */
BDOS: PROCEDURE (FN, ARG); DECLARE FN BYTE, ARG ADDRESS; GO TO 5; END BDOS;
EXIT: PROCEDURE; CALL BDOS(0,0); END EXIT;
PRINT: PROCEDURE (S); DECLARE S ADDRESS; CALL BDOS(9,S); END PRINT;
/* SPLIT A STRING ON CHARACTER 'SEP'.
THE 'PARTS' ARRAY WILL CONTAIN POINTERS TO THE START OF EACH ELEMENT.
THE AMOUNT OF PARTS IS RETURNED.
*/
TOKENIZE: PROCEDURE (SEP, STR, PARTS) ADDRESS;
DECLARE SEP BYTE, (STR, PARTS) ADDRESS;
DECLARE (N, P BASED PARTS) ADDRESS;
DECLARE CH BASED STR BYTE;
N = 0;
LOOP:
P(N) = STR;
N = N + 1;
DO WHILE CH <> '$' AND CH <> SEP;
STR = STR + 1;
END;
IF CH = '$' THEN RETURN N;
CH = '$';
STR = STR + 1;
GO TO LOOP;
END TOKENIZE;
/* TEST ON THE GIVEN INPUT */
DECLARE HELLO (24) BYTE INITIAL ('HELLO,HOW,ARE,YOU,TODAY$');
DECLARE PARTS (10) ADDRESS;
DECLARE (I, LEN) ADDRESS;
LEN = TOKENIZE(',', .HELLO, .PARTS);
DO I = 0 TO LEN-1;
CALL PRINT(PARTS(I));
CALL PRINT(.'. $');
END;
CALL EXIT;
EOF; |
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
| #Plain_English | Plain English | To run:
Start up.
Split "Hello,How,Are,You,Today" into some string things given the comma byte.
Join the string things with the period byte giving a string.
Destroy the string things.
Write the string on the console.
Wait for the escape key.
Shut down.
To join some string things with a byte giving a string:
Get a string thing from the string things.
Loop.
If the string thing is nil, exit.
Append the string thing's string to the string.
If the string thing's next is not nil, append the byte to the string.
Put the string thing's next into the string thing.
Repeat. |
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
| #Ring | Ring |
# Project : Top rank per group
load "stdlib.ring"
salary = "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"
temp = substr(salary, ",", nl)
temp = str2list(temp)
depsal = newlist(13,4)
for n = 1 to len(temp)
n1 = ceil(n/4)
n2 = n%4
if n2 = 0
n2 = 4
ok
depsal[n1][n2] = temp[n]
next
for n = 1 to len(depsal)-1
for m = n+1 to len(depsal)
if strcmp(depsal[m][4], depsal[n][4]) < 0
tmp = depsal[n]
depsal[n] = depsal[m]
depsal[m] = tmp
ok
next
next
for n = 1 to len(depsal)-1
for m = n+1 to len(depsal)
if (depsal[m][4] = depsal[n][4]) and (depsal[m][3] > depsal[n][3])
tmp = depsal[n]
depsal[n] = depsal[m]
depsal[m] = tmp
ok
next
next
see "Department : " + depsal[1][4] + nl
see "Name " + "Id " + "Salary" + nl + nl
see "" + depsal[1][1] + " " + depsal[1][2] + " " + depsal[1][3]+ nl
for n = 1 to len(depsal)-1
if (depsal[n+1][4] != depsal[n][4])
see nl
see "Department : " + depsal[n+1][4] + nl
see "Name " + "Id " + "Salary" + nl + nl
see "" + depsal[n+1][1] + " " + depsal[n+1][2] + " " + depsal[n+1][3]+ nl
else
see "" + depsal[n+1][1] + " " + depsal[n+1][2] + " " + depsal[n+1][3]+ nl
ok
next
|
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.
| #Scala | Scala | package object tictactoe {
val Human = 'X'
val Computer = 'O'
val BaseBoard = ('1' to '9').toList
val WinnerLines = List((0,1,2), (3,4,5), (6,7,8), (0,3,6), (1,4,7), (2,5,8), (0,4,8), (2,4,6))
val randomGen = new util.Random(System.currentTimeMillis)
}
package tictactoe {
class Board(aBoard : List[Char] = BaseBoard) {
def availableMoves = aBoard.filter(c => c != Human && c != Computer)
def availableMovesIdxs = for ((c,i) <- aBoard.zipWithIndex if c != Human && c != Computer) yield i
def computerPlays = new Board(aBoard.updated(availableMovesIdxs(randomGen.nextInt(availableMovesIdxs.length)), Computer))
def humanPlays(move : Char) = new Board(aBoard.updated(aBoard.indexOf(move), Human))
def isDraw = aBoard.forall(c => c == Human || c == Computer)
def isWinner(winner : Char) =
WinnerLines.exists{case (i,j,k) => aBoard(i) == winner && aBoard(j) == winner && aBoard(k) == winner}
def isOver = isWinner(Computer) || isWinner(Human) || isDraw
def print {
aBoard.grouped(3).foreach(row => println(row(0) + " " + row(1) + " " + row(2)))
}
def printOverMessage {
if (isWinner(Human)) println("You win.")
else if (isWinner(Computer)) println("Computer wins.")
else if (isDraw) println("It's a draw.")
else println("Not over yet, or something went wrong.")
}
}
object TicTacToe extends App {
def play(board : Board, turn : Char) {
// Reads a char from input until it is one of
// the available moves in the current board
def readValidMove() : Char = {
print("Choose a move: ")
val validMoves = board.availableMoves
val move = readChar
if (validMoves.contains(move)) {
move
} else {
println("Invalid move. Choose another one in " + validMoves)
readValidMove()
}
}
board.print
if (board.isOver) {
board.printOverMessage
return
}
if (turn == Human) { // Human plays
val nextBoard = board.humanPlays(readValidMove)
play(nextBoard, Computer)
} else { // Computer plays
println("Computer plays: ")
val nextBoard = board.computerPlays
play(nextBoard, Human)
}
}
play(new Board(),Human)
}
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Joy | Joy | DEFINE hanoi == [[rolldown] infra] dip
[ [ [null] [pop pop] ]
[ [dup2 [[rotate] infra] dip pred]
[ [dup rest put] dip
[[swap] infra] dip pred ]
[] ] ]
condnestrec. |
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.
| #REXX | REXX | ┌──────────────────────────────────────────────────────────────────────────┐
│ One common method that ensures enough accuracy in REXX is specifying │
│ more precision (via NUMERIC DIGITS nnn) than is needed, and then │
│ displaying the number of digits that are desired, or the number(s) │
│ could be re-normalized using the FORMAT BIF. │
│ │
│ The technique used (below) is to set the numeric digits ten higher │
│ than the desired digits, as specified by the SHOWDIGS variable. │
└──────────────────────────────────────────────────────────────────────────┘
|
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.
| #Ring | Ring |
pi = 3.14
decimals(8)
see "sin(pi/4.0) = " + sin(pi/4.0) + nl
see "cos(pi/4.0) = " + cos(pi/4.0) + nl
see "tan(pi/4.0) = " + tan(pi/4.0)+ nl
see "asin(sin(pi/4.0)) = " + asin(sin(pi/4.0)) + nl
see "acos(cos(pi/4.0)) = " + acos(cos(pi/4.0)) + nl
see "atan(tan(pi/4.0)) = " + atan(tan(pi/4.0)) + nl
see "atan2(3,4) = " + atan2(3,4) + nl
|
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.
| #Racket | Racket |
#lang racket
(define the-tree ; Node: (list <data> <left> <right>)
'(1 (2 (4 (7 #f #f) #f) (5 #f #f)) (3 (6 (8 #f #f) (9 #f #f)) #f)))
(define (preorder tree visit)
(let loop ([t tree])
(when t (visit (car t)) (loop (cadr t)) (loop (caddr t)))))
(define (inorder tree visit)
(let loop ([t tree])
(when t (loop (cadr t)) (visit (car t)) (loop (caddr t)))))
(define (postorder tree visit)
(let loop ([t tree])
(when t (loop (cadr t)) (loop (caddr t)) (visit (car t)))))
(define (levelorder tree visit)
(let loop ([trees (list tree)])
(unless (null? trees)
((compose1 loop (curry filter values) append*)
(for/list ([t trees] #:when t) (visit (car t)) (cdr t))))))
(define (run order)
(printf "~a:" (object-name order))
(order the-tree (λ(x) (printf " ~s" x)))
(newline))
(for-each run (list preorder inorder postorder levelorder))
|
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
| #Pop11 | Pop11 | ;;; Make a list of strings from a string using space as separator
lvars list;
sysparse_string('the cat sat on the mat') -> list;
;;; print the list of strings
list =>
** [the cat sat on the mat] |
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
| #PowerShell | PowerShell | $words = "Hello,How,Are,You,Today".Split(',')
[string]::Join('.', $words) |
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
| #Ruby | Ruby | require "csv"
data = <<EOS
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
EOS
def show_top_salaries_per_group(data, n)
table = CSV.parse(data, :headers=>true, :header_converters=>:symbol)
groups = table.group_by{|emp| emp[:department]}.sort
groups.each do |dept, emps|
puts dept
# max by salary
emps.max_by(n) {|emp| emp[:salary].to_i}.each do |e|
puts " %-16s %6s %7d" % [e[:employee_name], e[:employee_id], e[:salary]]
end
puts
end
end
show_top_salaries_per_group(data, 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.
| #Scilab | Scilab | function [] = startGame()
//Board size and marks
N = 3;
marks = ["X" "O"];
//Creating empty board
board = string(zeros(N,N));
for i = 1:(N*N)
board(i) = "";
end
//Initialising players
clc();
players= [%F %F];
players = playerSetup(marks);
//Console header
header = [strsplit(marks(1)+" is ----")';...
strsplit(marks(2)+" is ----")'];
for i = 1:2
if players(i) then
header(i,6:10) = strsplit("P"+string(i)+". ");
else
header(i,6:10) = strsplit("COMP.");
end
end
//Game loop
sleep(1000);
win_flag = %F;
count = 0;
while count<N*N
//Clear console, and print header and board
clc();
printf("%s\n %s\n",strcat(header(1,:)),strcat(header(2,:)));
dispBoard(board);
//Find which player should move
player_n = modulo(count,2) + 1;
if players(player_n) == %T then
//Human plays
pos = [];
valid_move = %F;
disp(marks(player_n)+"''s turn.");
while valid_move ~= %T
[pos,valid_move] = readHumanMove(board);
if ~valid_move then
disp("You should input a valid cell number.");
end
end
if valid_move then
board = updateBoard(board,pos,marks(player_n));
else
error("Invalid move.");
end
else
//Computer plays
disp("Computer is playing.");
board = ComputerMove(board,marks(player_n),marks);
sleep(800);
end
//Count number of movements
count = count + 1;
//Check if the game has finished
[win_flag,winning_mark] = detectWin(board)
if win_flag then
break
end
end
//Clear screen at the end of game
clc();
disp("Game finished:");
dispBoard(board);
//Print results
if win_flag then
disp(winning_mark+" won!");
else
disp("It''s a tie.");
end
//Play again?
play_again = "";
while play_again ~= "Y" & play_again ~= "N"
play_again = input("Would you like to play again? (Y/N)","s");
play_again = strsplit(play_again);
play_again = convstr(play_again(1),"u");
if play_again ~= "Y" & play_again ~= "N" then
disp("Invalid answer.");
end
end
if play_again == "Y" then
startGame();
else
disp("Quit game.");
end
endfunction
function players = playerSetup(marks)
//Determines who plays which mark
players = [%F %F]; //True for human, Flase for computer
printf("\n%s always starts.\n",marks(1));
for i = 1:2
user_input = "";
while user_input ~= "Y" & user_input ~= "N"
user_input = input("Would you like to play as "+marks(i)+"? (Y/N)","s");
user_input = strsplit(user_input);
user_input = convstr(user_input(1),"u");
if user_input ~= "Y" & user_input ~= "N" then
disp("Invalid answer.");
end
end
//Print choice
if user_input == "Y" then
players(i) = %T;
printf("%s shall be player %d (P%d).\n\n",marks(i),i,i);
else
printf("%s shall be the computer (COMP).\n\n",marks(i));
end
end
endfunction
function [] = dispBoard(board)
//Print ASCII board on console
//Get board marks
marks = [" " " "];
mark_inds = find(board ~= "");
if mark_inds ~= [] then
marks(1) = board(mark_inds(1));
mark_inds = find( (board ~= "") & (board ~= marks(1)) );
if mark_inds ~= [] then
marks(2) = board(mark_inds(1));
end
end
//Transpose to display for humans
//[compatibility with readHumanMove()]
disp_board = board';
rows = 3*size(board,'r');
cols = 4*size(board,'c');
ascii_board = string(zeros(rows, cols));
mark_1=[...
strsplit(" |")';...
strsplit(" "+marks(1)+" |")';...
strsplit("___|")'];
mark_2=[...
strsplit(" |")';...
strsplit(" "+marks(2)+" |")';...
strsplit("___|")'];
Blank_mark=[...
strsplit(" |")';...
strsplit(" |")';...
strsplit("___|")'];
for r = ([1:size(board,'r')] - 1 )
for c = ([1:size(board,'c')] - 1)
if disp_board(r+1,c+1) == marks(1) then
ascii_board((r*3 + 1):((r+1)*3),...
(c*4 + 1):((c+1)*4)) = mark_1;
elseif disp_board(r+1,c+1) == marks(2) then
ascii_board((r*3 + 1):((r+1)*3),...
(c*4 + 1):((c+1)*4)) = mark_2;
else
ascii_board((r*3 + 1):((r+1)*3),...
(c*4 + 1):((c+1)*4)) = Blank_mark;
end
end
end
for i = 1:cols
if modulo(i,4)>0 then
ascii_board(rows,i) = " ";
end
end
for i = 1:rows
ascii_board(i,cols) = " ";
end
printf("\n");
for i = 1:size(ascii_board,'r')
printf("%s\n",strcat(ascii_board(i,:)))
end
endfunction
function moves_board = availableMoves(board)
//Find empty cells on the board
moves_board = board;
for i = 1:(size(board,'r')*size(board,'c'))
if board(i) == "" then
moves_board(i) = string(i);
else
moves_board(i) = "_";
end
end
endfunction
function varargout = readHumanMove(board)
//Read human input
printf("\nAvailable cells:");
moves_board = availableMoves(board);
disp(moves_board');
x = input("\nEnter a move (0 to quit game): ");
valid = %F;
pos = 0;
total = size(moves_board,'r') * size(moves_board,'c');
//Check if it is a valid move
if x == 0 then
disp("Quit game.")
abort
elseif (x>=1 & x<=total) then
if (moves_board(x) == string(x)) then
valid = %T;
pos = x;
end
end
varargout = list(pos,valid);
endfunction
function varargout = updateBoard(board,pos,player)
//Add move to the board
if board(pos) ~= "" then
error('Error: Invalid move.');
end
board(pos) = player
varargout = list(board);
endfunction
function varargout = detectWin(board)
//Detect if there is a winner or not
win_flag = %F;
winner = "";
//Get board marks
marks = ["" ""];
mark_inds = find(board ~= "");
marks(1) = board(mark_inds(1))
mark_inds = find( (board ~= "") & (board ~= marks(1)) );
marks(2) = board(mark_inds(1));
//If there is a minimum number of moves, check if there is a winner
n_moves = find(~(board == ""));
n_moves = length(n_moves)
if n_moves >= size(board,'r') then
board_X = (board == marks(1));
board_O = (board == marks(2));
for i = 1:size(board,'r')
//Check rows
if find(~board_X(i,:)) == [] then
win_flag = %T;
winner = marks(1);
break
end
if find(~board_O(i,:)) == [] then
win_flag = %T;
winner = marks(2);
break
end
//Check columns
if find(~board_X(:,i)) == [] then
win_flag = %T;
winner = marks(1);
break
end
if find(~board_O(:,i)) == [] then
win_flag = %T;
winner = marks(2);
break
end
end
//Check diagonal
if ~win_flag then
if find(~diag(board_X)) == [] then
win_flag = %T;
winner = marks(1);
elseif find(~diag(board_O)) == [] then
win_flag = %T;
winner = marks(2);
end
end
//Check anti-diagonal
if ~win_flag then
board_X = board_X(:,$:-1:1);
board_O = board_O(:,$:-1:1);
if find(~diag(board_X)) == [] then
win_flag = %T;
winner = marks(1);
elseif find(~diag(board_O)) == [] then
win_flag = %T;
winner = marks(2);
end
end
end
varargout = list(win_flag,winner)
endfunction
function threat_pos = findThreat(board,player)
//Returns a list of moves that can finish the game
//Available moves
move_inds = find(~( availableMoves(board) == "_" ));
//If there is a minimum number of moves, check if there is a threat
threat_pos = [];
if (size(board,'r')*size(board,'c')) - length(move_inds) >...
(size(board,'r') - 1) then
for i = 1:length(move_inds)
temp_board = updateBoard(board,move_inds(i),player);
[win_flag,winner] = detectWin(temp_board);
if win_flag & winner == player then
threat_pos = [threat_pos move_inds(i)];
end
end
end
endfunction
function varargout = ComputerMove(board,mark,all_marks)
//Atomatically add a move to the board with no human input
//Find winning moves moves
move_inds = findThreat(board,mark);
//If there are no winning moves, find opponent's winning moves
//to block opponent's victory
if move_inds == [] then
if mark == all_marks(1) then
opponent = all_marks(2);
elseif mark == all_marks(2) then
opponent = all_marks(1);
end
move_inds = findThreat(board,opponent);
end
//If there are no winning moves or threats, find all possible moves
if move_inds == [] then
move_inds = find(~( availableMoves(board) == "_" ));
end
//Choose a random move among the selected possible moves
pos = grand(1,"prm",move_inds);
pos = pos(1);
//Update board by adding a new mark
board(pos) = mark;
varargout = list(board);
endfunction
startGame() |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #jq | jq | # n is the number of disks to move from From to To
def move(n; From; To; Via):
if n > 0 then
# move all but the largest at From to Via (according to the rules):
move(n-1; From; Via; To),
# ... so the largest disk at From is now free to move to its final destination:
"Move disk from \(From) to \(To)",
# Move the remaining disks at Via to To:
move(n-1; Via; To; From)
else empty
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.
| #Ruby | Ruby | radians = Math::PI / 4
degrees = 45.0
def deg2rad(d)
d * Math::PI / 180
end
def rad2deg(r)
r * 180 / Math::PI
end
#sine
puts "#{Math.sin(radians)} #{Math.sin(deg2rad(degrees))}"
#cosine
puts "#{Math.cos(radians)} #{Math.cos(deg2rad(degrees))}"
#tangent
puts "#{Math.tan(radians)} #{Math.tan(deg2rad(degrees))}"
#arcsine
arcsin = Math.asin(Math.sin(radians))
puts "#{arcsin} #{rad2deg(arcsin)}"
#arccosine
arccos = Math.acos(Math.cos(radians))
puts "#{arccos} #{rad2deg(arccos)}"
#arctangent
arctan = Math.atan(Math.tan(radians))
puts "#{arctan} #{rad2deg(arctan)}" |
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.
| #Raku | Raku | class TreeNode {
has TreeNode $.parent;
has TreeNode $.left;
has TreeNode $.right;
has $.value;
method pre-order {
flat gather {
take $.value;
take $.left.pre-order if $.left;
take $.right.pre-order if $.right
}
}
method in-order {
flat gather {
take $.left.in-order if $.left;
take $.value;
take $.right.in-order if $.right;
}
}
method post-order {
flat gather {
take $.left.post-order if $.left;
take $.right.post-order if $.right;
take $.value;
}
}
method level-order {
my TreeNode @queue = (self);
flat gather while @queue.elems {
my $n = @queue.shift;
take $n.value;
@queue.push($n.left) if $n.left;
@queue.push($n.right) if $n.right;
}
}
}
my TreeNode $root .= new( value => 1,
left => TreeNode.new( value => 2,
left => TreeNode.new( value => 4, left => TreeNode.new(value => 7)),
right => TreeNode.new( value => 5)
),
right => TreeNode.new( value => 3,
left => TreeNode.new( value => 6,
left => TreeNode.new(value => 8),
right => TreeNode.new(value => 9)
)
)
);
say "preorder: ",$root.pre-order.join(" ");
say "inorder: ",$root.in-order.join(" ");
say "postorder: ",$root.post-order.join(" ");
say "levelorder:",$root.level-order.join(" "); |
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
| #Prolog | Prolog | splitup(Sep,[token(B)|BL]) --> splitup(Sep,B,BL).
splitup(Sep,[A|AL],B) --> [A], {\+ [A] = Sep }, splitup(Sep,AL,B).
splitup(Sep,[],[B|BL]) --> Sep, splitup(Sep,B,BL).
splitup(_Sep,[],[]) --> [].
start :-
phrase(splitup(",",Tokens),"Hello,How,Are,You,Today"),
phrase(splitup(".",Tokens),Backtogether),
string_to_list(ABack,Backtogether),
writeln(ABack). |
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
| #Run_BASIC | Run BASIC | perSal$ = "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"
while word$(perSal$,n+1,chr$(13)) <> "" : n = n + 1 : wend ' get count of employees
dim depSal$(n)
for i = 1 to n
depSal$(i) = word$(perSal$,i,chr$(13))
next i
sw = 1
while sw = 1
sw = 0
for i = 1 to n -1
if word$(depSal$(i),4,",")+word$(depSal$(i),3,",") > word$(depSal$(i+1),4,",")+word$(depSal$(i+1),3,",") then
temp$ = depSal$(i)
depSal$(i) = depSal$(i+1)
depSal$(i+1) = temp$
sw = 1
end if
next i
wend
print "Employee Name";chr$(9);"ID";chr$(9);"Salary"
for i = 1 to n
if dep$ <> word$(depSal$(i),4,",") then
dep$ = word$(depSal$(i),4,",")
print : print"Department:";dep$
end if
print word$(depSal$(i),1,",");chr$(9);word$(depSal$(i),2,",");chr$(9);word$(depSal$(i),3,",")
next i |
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.
| #SQL | SQL |
--Setup
DROP TABLE IF EXISTS board;
CREATE TABLE board (p CHAR, r INTEGER, c INTEGER);
INSERT INTO board VALUES('.', 0, 0),('.', 0, 1),('.', 0, 2),('.', 1, 0),('.', 1, 1),('.', 1, 2),('.', 2, 0),('.', 2, 1),('.', 2, 2);
-- Use a trigger for move events
DROP TRIGGER IF EXISTS after_moved;
CREATE TRIGGER after_moved after UPDATE ON board FOR each ROW WHEN NEW.p <> '.' AND NEW.p <> 'O'
BEGIN
-- Verify move is valid
SELECT
CASE
WHEN (SELECT v FROM msg) LIKE '%Wins!' THEN raise(ABORT, 'The game is already over.')
WHEN (SELECT OLD.p FROM board WHERE rowid = rid) <> '.' THEN raise(ABORT, 'That position has already been taken. Please choose an available position.')
WHEN NEW.p <> 'X' THEN raise(ABORT, 'Please place an ''X''')
END
FROM (
SELECT rowid rid FROM board
WHERE p = NEW.p
EXCEPT
SELECT p FROM board WHERE p = OLD.p
);
-- Check for game over
UPDATE msg SET v = (
SELECT
CASE
WHEN MAX(num) >= 3 THEN 'X Wins!'
WHEN (SELECT COUNT(*) FROM board WHERE p = '.') = 0 THEN 'Cat Wins!'
ELSE 'Move made'
END
FROM ( -- Is Game Over
SELECT COUNT(*) num FROM board WHERE p = 'X' GROUP BY r UNION -- Horz
SELECT COUNT(*) num FROM board WHERE p = 'X' GROUP BY c UNION -- Vert
SELECT COUNT(*) num FROM board WHERE p = 'X' AND r = c UNION -- Diag TL->BR
SELECT COUNT(*) num FROM board WHERE p = 'X' AND (2-r) = c -- Diag TR->BL
)
);
--Have computer player make a random move
UPDATE board SET p = 'O'
WHERE rowid = (SELECT rid FROM (SELECT MAX(rnd),rid FROM (SELECT rowid rid, random() rnd FROM board WHERE p = '.')))
AND (SELECT v FROM msg) NOT LIKE '%Wins!';
--NOTE: SQLite doesn't allow update order by in triggers, otherwise we could just use this beautiful line:
-- update board set p = 'O' where p = '.' order by random() limit 1;
--Check to see if the computer player won
UPDATE msg SET v = (
SELECT
CASE
WHEN MAX(num) >= 3 THEN 'O Wins!'
ELSE v
END
FROM ( -- Is Game Over
SELECT COUNT(*) num FROM board WHERE p = 'O' GROUP BY r UNION -- Horz
SELECT COUNT(*) num FROM board WHERE p = 'O' GROUP BY c UNION -- Vert
SELECT COUNT(*) num FROM board WHERE p = 'O' AND r = c UNION -- Diag TL->BR
SELECT COUNT(*) num FROM board WHERE p = 'O' AND (2-r) = c -- Diag TR->BL
)
);
END;
-- UI to display the logical board as a grid
DROP VIEW IF EXISTS ui;
CREATE VIEW ui AS
SELECT CASE WHEN p = '.' THEN col0.rowid ELSE p END c0, c1, c2
FROM board AS col0
JOIN (SELECT CASE WHEN p = '.' THEN board.rowid ELSE p END c1, r FROM board WHERE c = 1) AS col1 ON col0.r = col1.r
JOIN (SELECT CASE WHEN p = '.' THEN board.rowid ELSE p END c2, r FROM board WHERE c = 2) AS col2 ON col0.r = col2.r
WHERE c = 0;
DROP TABLE IF EXISTS msg;
CREATE TABLE msg (v text);
INSERT INTO msg VALUES('');
-- Readme
SELECT * FROM ui;
.print "Use this to play:"
.print "->update board set p = 'X' where rowid = ?; select * from ui; select * from msg;"'
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Jsish | Jsish | /* Towers of Hanoi, in Jsish */
function move(n, a, b, c) {
if (n > 0) {
move(n-1, a, c, b);
puts("Move disk from " + a + " to " + c);
move(n-1, b, a, c);
}
}
if (Interp.conf('unitTest')) move(4, "A", "B", "C");
/*
=!EXPECTSTART!=
Move disk from A to B
Move disk from A to C
Move disk from B to C
Move disk from A to B
Move disk from C to A
Move disk from C to B
Move disk from A to B
Move disk from A to C
Move disk from B to C
Move disk from B to A
Move disk from C to A
Move disk from B to C
Move disk from A to B
Move disk from A to C
Move disk from B to C
=!EXPECTEND!=
*/ |
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.
| #Run_BASIC | Run BASIC | ' Find these three ratios: Sine, Cosine, Tangent. (These ratios have NO units.)
deg = 45.0
' Run BASIC works in radians; so, first convert deg to rad as shown in next line.
rad = deg * (atn(1)/45)
print "Ratios for a "; deg; " degree angle, (or "; rad; " radian angle.)"
print "Sine: "; SIN(rad)
print "Cosine: "; COS(rad)
print "Tangent: "; TAN(rad)
print "Inverse Functions - - (Using above ratios)"
' Now, use those ratios to work backwards to show their original angle in radians.
' Also, use this: rad / (atn(1)/45) = deg (To change radians to degrees.)
print "Arcsine: "; ASN(SIN(rad)); " radians, (or "; ASN(SIN(rad))/(atn(1)/45); " degrees)"
print "Arccosine: "; ACS(COS(rad)); " radians, (or "; ACS(COS(rad))/(atn(1)/45); " degrees)"
print "Arctangent: "; ATN(TAN(rad)); " radians, (or "; ATN(TAN(rad))/(atn(1)/45); " degrees)"
' This code also works in Liberty BASIC.
' The above (atn(1)/45) = approx .01745329252 |
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.
| #REBOL | REBOL |
tree: [1 [2 [4 [7 [] []] []] [5 [] []]] [3 [6 [8 [] []] [9 [] []]] []]]
; "compacted" version
tree: [1 [2 [4 [7 ] ] [5 ]] [3 [6 [8 ] [9 ]] ]]
visit: func [tree [block!]][prin rejoin [first tree " "]]
left: :second
right: :third
preorder: func [tree [block!]][
if not empty? tree [visit tree]
attempt [preorder left tree]
attempt [preorder right tree]
]
prin "preorder: " preorder tree
print ""
inorder: func [tree [block!]][
attempt [inorder left tree]
if not empty? tree [visit tree]
attempt [inorder right tree]
]
prin "inorder: " inorder tree
print ""
postorder: func [tree [block!]][
attempt [postorder left tree]
attempt [postorder right tree]
if not empty? tree [visit tree]
]
prin "postorder: " postorder tree
print ""
queue: []
enqueue: func [tree [block!]][append/only queue tree]
dequeue: func [queue [block!]][take queue]
level-order: func [tree [block!]][
clear head queue
queue: enqueue tree
while [not empty? queue] [
tree: dequeue queue
if not empty? tree [visit tree]
attempt [enqueue left tree]
attempt [enqueue right tree]
]
]
prin "level-order: " level-order 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
| #Python | Python | text = "Hello,How,Are,You,Today"
tokens = text.split(',')
print ('.'.join(tokens)) |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Q | Q | words: "," vs "Hello,How,Are,You,Today"
"." sv words |
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
| #Rust | Rust | #[derive(Debug)]
struct Employee<S> {
// Allow S to be any suitable string representation
id: S,
name: S,
department: S,
salary: u32,
}
impl<S> Employee<S> {
fn new(name: S, id: S, salary: u32, department: S) -> Self {
Self {
id,
name,
department,
salary,
}
}
}
#[rustfmt::skip]
fn load_data() -> Vec<Employee<&'static str>> {
vec![
Employee::new("Tyler Bennett", "E10297", 32000, "D101"),
Employee::new("John Rappl", "E21437", 47000, "D050"),
Employee::new("George Woltman", "E00127", 53500, "D101"),
Employee::new("Adam Smith", "E63535", 18000, "D202"),
Employee::new("Claire Buckman", "E39876", 27800, "D202"),
Employee::new("David McClellan", "E04242", 41500, "D101"),
Employee::new("Rich Holcomb", "E01234", 49500, "D202"),
Employee::new("Nathan Adams", "E41298", 21900, "D050"),
Employee::new("Richard Potter", "E43128", 15900, "D101"),
Employee::new("David Motsinger", "E27002", 19250, "D202"),
Employee::new("Tim Sampair", "E03033", 27000, "D101"),
Employee::new("Kim Arlich", "E10001", 57000, "D190"),
Employee::new("Timothy Grove", "E16398", 29900, "D190"),
// Added to demonstrate various tie situations
Employee::new("Kim Tie", "E16400", 57000, "D190"),
Employee::new("Timothy Tie", "E16401", 29900, "D190"),
Employee::new("Timothy Kim", "E16401", 19900, "D190"),
]
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let n = {
println!("How many top salaries to list? ");
let mut buf = String::new();
std::io::stdin().read_line(&mut buf)?;
buf.trim().parse::<u32>()?
};
let mut employees = load_data();
// Reverse order, then just pick top N employees
employees.sort_by(|a, b| b.salary.cmp(&a.salary));
let sorted = employees
.into_iter()
.fold(std::collections::BTreeMap::new(), |mut acc, next| {
// We store the number of unique salaries as well to handle
// ties (and list always all employees with the same salary)
let mut bucket = acc
.entry(next.department)
.or_insert_with(|| (0, Vec::<Employee<_>>::new()));
match bucket.1.last().map(|e| e.salary) {
Some(last_salary) if last_salary == next.salary => {
if bucket.0 <= n {
bucket.1.push(next);
}
}
_ => {
if bucket.0 < n {
bucket.0 += 1; // Next unique salary
bucket.1.push(next);
}
}
}
acc
});
for (department, (_, employees)) in sorted {
println!("{}", department);
employees
.iter()
.for_each(|employee| println!(" {:?}", employee));
}
Ok(())
} |
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.
| #Swift | Swift |
import Darwin
enum Token : CustomStringConvertible {
case cross, circle
func matches(tokens: [Token?]) -> Bool {
for token in tokens {
guard let t = token, t == self else {
return false
}
}
return true
}
func emptyCell(in tokens: [Token?]) -> Int? {
if tokens[0] == nil
&& tokens[1] == self
&& tokens[2] == self {
return 0
} else
if tokens[0] == self
&& tokens[1] == nil
&& tokens[2] == self {
return 1
} else
if tokens[0] == self
&& tokens[1] == self
&& tokens[2] == nil {
return 2
}
return nil
}
var description: String {
switch self {
case .cross: return "x"
case .circle: return "o"
}
}
}
struct Board {
var cells: [Token?] = [nil, nil, nil, nil, nil, nil, nil, nil, nil]
func cells(atCol col: Int) -> [Token?] {
return [cells[col], cells[col + 3], cells[col + 6]]
}
func cells(atRow row: Int) -> [Token?] {
return [cells[row * 3], cells[row * 3 + 1], cells[row * 3 + 2]]
}
func cellsTopLeft() -> [Token?] {
return [cells[0], cells[4], cells[8]]
}
func cellsBottomLeft() -> [Token?] {
return [cells[6], cells[4], cells[2]]
}
func winner() -> Token? {
let r0 = cells(atRow: 0)
let r1 = cells(atRow: 1)
let r2 = cells(atRow: 2)
let c0 = cells(atCol: 0)
let c1 = cells(atCol: 1)
let c2 = cells(atCol: 2)
let tl = cellsTopLeft()
let bl = cellsBottomLeft()
if Token.cross.matches(tokens: r0)
|| Token.cross.matches(tokens: r1)
|| Token.cross.matches(tokens: r2)
|| Token.cross.matches(tokens: c0)
|| Token.cross.matches(tokens: c1)
|| Token.cross.matches(tokens: c2)
|| Token.cross.matches(tokens: tl)
|| Token.cross.matches(tokens: bl) {
return .cross
} else
if Token.circle.matches(tokens: r0)
|| Token.circle.matches(tokens: r1)
|| Token.circle.matches(tokens: r2)
|| Token.circle.matches(tokens: c0)
|| Token.circle.matches(tokens: c1)
|| Token.circle.matches(tokens: c2)
|| Token.circle.matches(tokens: tl)
|| Token.circle.matches(tokens: bl) {
return .circle
}
return nil
}
func atCapacity() -> Bool {
return cells.filter { $0 == nil }.count == 0
}
mutating func play(token: Token, at location: Int) {
cells[location] = token
}
func findBestLocation(for player: Token) -> Int? {
let r0 = cells(atRow: 0)
let r1 = cells(atRow: 1)
let r2 = cells(atRow: 2)
let c0 = cells(atCol: 0)
let c1 = cells(atCol: 1)
let c2 = cells(atCol: 2)
let tl = cellsTopLeft()
let bl = cellsBottomLeft()
if let cell = player.emptyCell(in: r0) {
return cell
} else if let cell = player.emptyCell(in: r1) {
return cell + 3
} else if let cell = player.emptyCell(in: r2) {
return cell + 6
} else if let cell = player.emptyCell(in: c0) {
return cell * 3
} else if let cell = player.emptyCell(in: c1) {
return cell * 3 + 1
} else if let cell = player.emptyCell(in: c2) {
return cell * 3 + 2
} else if let cell = player.emptyCell(in: tl) {
return cell == 0 ? 0 : (cell == 1 ? 4 : 8)
} else if let cell = player.emptyCell(in: bl) {
return cell == 0 ? 6 : (cell == 1 ? 4 : 2)
}
return nil
}
func findMove() -> Int {
let empties = cells.enumerated().filter { $0.1 == nil }
let r = Int(arc4random()) % empties.count
return empties[r].0
}
}
extension Board : CustomStringConvertible {
var description: String {
var result = "\n---------------\n"
for (idx, cell) in cells.enumerated() {
if let cell = cell {
result += "| \(cell) |"
} else {
result += "| \(idx) |"
}
if (idx + 1) % 3 == 0 {
result += "\n---------------\n"
}
}
return result
}
}
while true {
var board = Board()
print("Who do you want to play as ('o' or 'x'): ", separator: "", terminator: "")
let answer = readLine()?.characters.first ?? "x"
var player: Token = answer == "x" ? .cross : .circle
var pc: Token = player == .cross ? .circle : .cross
print(board)
while true {
print("Choose cell to play on: ", separator: "", terminator: "")
var pos = Int(readLine() ?? "0") ?? 0
while !board.atCapacity() && board.cells[pos] != nil {
print("Invalid move. Choose cell to play on: ", separator: "", terminator: "")
pos = Int(readLine() ?? "0") ?? 0
}
if board.atCapacity() {
print("Draw")
break
}
board.play(token: player, at: pos)
print(board)
if let winner = board.winner() {
print("winner is \(winner)")
break
} else if board.atCapacity() {
print("Draw")
break
}
if let win = board.findBestLocation(for: pc) {
board.play(token: pc, at: win)
} else if let def = board.findBestLocation(for: player) {
board.play(token: pc, at: def)
} else {
board.play(token: pc, at: board.findMove())
}
print(board)
if let winner = board.winner() {
print("winner is \(winner)")
break
}
}
}
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Julia | Julia |
function solve(n::Integer, from::Integer, to::Integer, via::Integer)
if n == 1
println("Move disk from $from to $to")
else
solve(n - 1, from, via, to)
solve(1, from, to, via)
solve(n - 1, via, to, from)
end
end
solve(4, 1, 2, 3)
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #K | K | h:{[n;a;b;c]if[n>0;_f[n-1;a;c;b];`0:,//$($n,":",$a,"->",$b,"\n");_f[n-1;c;b;a]]}
h[4;1;2;3]
1:1->3
2:1->2
1:3->2
3:1->3
1:2->1
2:2->3
1:1->3
4:1->2
1:3->2
2:3->1
1:2->1
3:3->2
1:1->3
2:1->2
1:3->2 |
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.
| #Rust | Rust | // 20210221 Rust programming solution
use std::f64::consts::PI;
fn main() {
let angle_radians: f64 = PI/4.0;
let angle_degrees: f64 = 45.0;
println!("{} {}", angle_radians.sin(), angle_degrees.to_radians().sin());
println!("{} {}", angle_radians.cos(), angle_degrees.to_radians().cos());
println!("{} {}", angle_radians.tan(), angle_degrees.to_radians().tan());
let asin = angle_radians.sin().asin();
println!("{} {}", asin, asin.to_degrees());
let acos = angle_radians.cos().acos();
println!("{} {}", acos, acos.to_degrees());
let atan = angle_radians.tan().atan();
println!("{} {}", atan, atan.to_degrees());
} |
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.
| #SAS | SAS | data _null_;
pi = 4*atan(1);
deg = 30;
rad = pi/6;
k = pi/180;
x = 0.2;
a = sin(rad);
b = sin(deg*k);
put a b;
a = cos(rad);
b = cos(deg*k);
put a b;
a = tan(rad);
b = tan(deg*k);
put a b;
a=arsin(x);
b=arsin(x)/k;
put a b;
a=arcos(x);
b=arcos(x)/k;
put a b;
a=atan(x);
b=atan(x)/k;
put a b;
run; |
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.
| #REXX | REXX |
/* REXX ***************************************************************
* Tree traversal
= 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
= level-order: 1 2 3 4 5 6 7 8 9
= postorder: 7 4 5 2 8 9 6 3 1
= inorder: 7 4 2 5 1 8 6 9 3
* 17.06.2012 Walter Pachl not thoroughly tested
**********************************************************************/
debug=0
wl_soll=1 2 4 7 5 3 6 8 9
il_soll=7 4 2 5 1 8 6 9 3
pl_soll=7 4 5 2 8 9 6 3 1
ll_soll=1 2 3 4 5 6 7 8 9
Call mktree
wl.=''; wl='' /* preorder */
ll.=''; ll='' /* level-order */
il='' /* inorder */
pl='' /* postorder */
/**********************************************************************
* First walk the tree and construct preorder and level-order lists
**********************************************************************/
done.=0
lvl=1
z=root
Call note z
Do Until z=0
z=go_next(z)
Call note z
End
Call show 'preorder: ',wl,wl_soll
Do lvl=1 To 4
ll=ll ll.lvl
End
Call show 'level-order:',ll,ll_soll
/**********************************************************************
* Next construct postorder list
**********************************************************************/
done.=0
ridone.=0
z=lbot(root)
Call notep z
Do Until z=0
br=brother(z)
If br>0 &,
done.br=0 Then Do
ridone.br=1
z=lbot(br)
Call notep z
End
Else
z=father(z)
Call notep z
End
Call show 'postorder: ',pl,pl_soll
/**********************************************************************
* Finally construct inorder list
**********************************************************************/
done.=0
ridone.=0
z=lbot(root)
Call notei z
Do Until z=0
z=father(z)
Call notei z
ri=node.z.0rite
If ridone.z=0 Then Do
ridone.z=1
If ri>0 Then Do
z=lbot(ri)
Call notei z
End
End
End
/**********************************************************************
* And now show the results and check them for correctness
**********************************************************************/
Call show 'inorder: ',il,il_soll
Exit
show: Parse Arg Which,have,soll
/**********************************************************************
* Show our result and show it it's correct
**********************************************************************/
have=space(have)
If have=soll Then
tag=''
Else
tag='*wrong*'
Say which have tag
If tag<>'' Then
Say '------------>'soll 'is the expected result'
Return
brother: Procedure Expose node.
/**********************************************************************
* Return the right node of this node's father or 0
**********************************************************************/
Parse arg no
nof=node.no.0father
brot1=node.nof.0rite
Return brot1
notei: Procedure Expose debug il done.
/**********************************************************************
* append the given node to il
**********************************************************************/
Parse Arg nd
If nd<>0 &,
done.nd=0 Then
il=il nd
If debug Then
Say 'notei' nd
done.nd=1
Return
notep: Procedure Expose debug pl done.
/**********************************************************************
* append the given node to pl
**********************************************************************/
Parse Arg nd
If nd<>0 &,
done.nd=0 Then Do
pl=pl nd
If debug Then
Say 'notep' nd
End
done.nd=1
Return
father: Procedure Expose node.
/**********************************************************************
* Return the father of the argument
* or 0 if the root is given as argument
**********************************************************************/
Parse Arg nd
Return node.nd.0father
lbot: Procedure Expose node.
/**********************************************************************
* From node z: Walk down on the left side until you reach the bottom
* and return the bottom node
* If z has no left son (at the bottom of the tree) returm itself
**********************************************************************/
Parse Arg z
Do i=1 To 100
If node.z.0left<>0 Then
z=node.z.0left
Else
Leave
End
Return z
note:
/**********************************************************************
* add the node to the preorder list unless it's already there
* add the node to the level list
**********************************************************************/
If z<>0 &, /* it's a node */
done.z=0 Then Do /* not yet done */
wl=wl z /* add it to the preorder list*/
ll.lvl=ll.lvl z /* add it to the level list */
done.z=1 /* remember it's done */
End
Return
go_next: Procedure Expose node. lvl
/**********************************************************************
* find the next node to visit in the treewalk
**********************************************************************/
next=0
Parse arg z
If node.z.0left<>0 Then Do /* there is a left son */
If node.z.0left.done=0 Then Do /* we have not visited it */
next=node.z.0left /* so we go there */
node.z.0left.done=1 /* note we were here */
lvl=lvl+1 /* increase the level */
End
End
If next=0 Then Do /* not moved yet */
If node.z.0rite<>0 Then Do /* there is a right son */
If node.z.0rite.done=0 Then Do /* we have not visited it */
next=node.z.0rite /* so we go there */
node.z.0rite.done=1 /* note we were here */
lvl=lvl+1 /* increase the level */
End
End
End
If next=0 Then Do /* not moved yet */
next=node.z.0father /* go to the father */
lvl=lvl-1 /* decrease the level */
End
Return next /* that's the next node */
/* or zero if we are done */
mknode: Procedure Expose node.
/**********************************************************************
* create a new node
**********************************************************************/
Parse Arg name
z=node.0+1
node.z.0name=name
node.z.0father=0
node.z.0left =0
node.z.0rite =0
node.0=z
Return z /* number of the node just created */
attleft: Procedure Expose node.
/**********************************************************************
* make son the left son of father
**********************************************************************/
Parse Arg son,father
node.son.0father=father
z=node.father.0left
If z<>0 Then Do
node.z.0father=son
node.son.0left=z
End
node.father.0left=son
Return
attrite: Procedure Expose node.
/**********************************************************************
* make son the right son of father
**********************************************************************/
Parse Arg son,father
node.son.0father=father
z=node.father.0rite
If z<>0 Then Do
node.z.0father=son
node.son.0rite=z
End
node.father.0rite=son
le=node.father.0left
If le>0 Then
node.le.0brother=node.father.0rite
Return
mktree: Procedure Expose node. root
/**********************************************************************
* build the tree according to the task
**********************************************************************/
node.=0
a=mknode('A'); root=a
b=mknode('B'); Call attleft b,a
c=mknode('C'); Call attrite c,a
d=mknode('D'); Call attleft d,b
e=mknode('E'); Call attrite e,b
f=mknode('F'); Call attleft f,c
g=mknode('G'); Call attleft g,d
h=mknode('H'); Call attleft h,f
i=mknode('I'); Call attrite i,f
Call show_tree 1
Return
show_tree: Procedure Expose node.
/**********************************************************************
* Show the tree
* f
* l1 1 r1
* l r l r
* l r l r l r l r
* 12345678901234567890
**********************************************************************/
Parse Arg f
l.=''
l.1=overlay(f ,l.1, 9)
l1=node.f.0left ;l.2=overlay(l1 ,l.2, 5)
/*b1=node.f.0brother ;l.2=overlay(b1 ,l.2, 9) */
r1=node.f.0rite ;l.2=overlay(r1 ,l.2,13)
l1g=node.l1.0left ;l.3=overlay(l1g ,l.3, 3)
/*b1g=node.l1.0brother ;l.3=overlay(b1g ,l.3, 5) */
r1g=node.l1.0rite ;l.3=overlay(r1g ,l.3, 7)
l2g=node.r1.0left ;l.3=overlay(l2g ,l.3,11)
/*b2g=node.r1.0brother ;l.3=overlay(b2g ,l.3,13) */
r2g=node.r1.0rite ;l.3=overlay(r2g ,l.3,15)
l1ls=node.l1g.0left ;l.4=overlay(l1ls,l.4, 2)
/*b1ls=node.l1g.0brother ;l.4=overlay(b1ls,l.4, 3) */
r1ls=node.l1g.0rite ;l.4=overlay(r1ls,l.4, 4)
l1rs=node.r1g.0left ;l.4=overlay(l1rs,l.4, 6)
/*b1rs=node.r1g.0brother ;l.4=overlay(b1rs,l.4, 7) */
r1rs=node.r1g.0rite ;l.4=overlay(r1rs,l.4, 8)
l2ls=node.l2g.0left ;l.4=overlay(l2ls,l.4,10)
/*b2ls=node.l2g.0brother ;l.4=overlay(b2ls,l.4,11) */
r2ls=node.l2g.0rite ;l.4=overlay(r2ls,l.4,12)
l2rs=node.r2g.0left ;l.4=overlay(l2rs,l.4,14)
/*b2rs=node.r2g.0brother ;l.4=overlay(b2rs,l.4,15) */
r2rs=node.r2g.0rite ;l.4=overlay(r2rs,l.4,16)
Do i=1 To 4
Say translate(l.i,' ','0')
Say ''
End
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
| #QB64 | QB64 | a$ = "Hello,How,Are,You,Today" ' | Initialize original string.
FOR na = 1 TO LEN(a$) ' | Start loop to count number of commas.
IF MID$(a$, na, 1) = "," THEN nc = nc + 1 ' | For each comma, increment nc.
NEXT ' | End of loop.
DIM t$(nc) ' | Dim t$ array with total number of commas (nc). Array base is 0.
FOR nb = 1 TO LEN(a$) ' | Start loop to find each word.
c$ = MID$(a$, nb, 1) ' | Look at each character in the string.
IF c$ = "," THEN ' | If the character is a comma, increase the t$ array for the next word.
t = t + 1 ' | t = token word count. Starts at 0 because array base is 0.
ELSE ' | Or...
t$(t) = t$(t) + c$ ' | Add each character to the current token (t$) word.
END IF ' | End of decision tree.
NEXT ' | End of loop.
FOR nd = 0 TO t ' | Start loop to create final desired output.
tf$ = tf$ + t$(nd) + "." ' | Add each token word from t$ followed by a period to the final tf$.
NEXT ' | End of loop.
PRINT LEFT$(tf$, LEN(tf$) - 1) ' | Print all but the last period of tf$.
END ' | Program end.
|
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Quackery | Quackery | [ [] [] rot
witheach
[ dup char , = iff
[ drop nested join [] ]
else join ]
nested join ] is tokenise ( $ --> [ )
[ witheach [ echo$ say "." ] ] is display ( [ --> )
$ "Hello,How,Are,You,Today" tokenise display |
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
| #Scala | Scala | import scala.io.Source
import scala.language.implicitConversions
import scala.language.reflectiveCalls
import scala.collection.immutable.TreeMap
object TopRank extends App {
val topN = 3
val rawData = """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""".stripMargin
class Employee(name: String, id: String,
val salary: Int,
val department: String) {
override def toString = s"$id\t$salary\t$name"
}
// A TreeMap has sorted keys
val data: TreeMap[String, Seq[TopRank.Employee]] = // TreeMap is a sorted map
TreeMap((Source.fromString(rawData) getLines ()).toSeq // Runtime parsing
.drop(1) // Drop header
.map(_.split(";")) //read fields into list of employees
.map(emp => new Employee(emp(0), emp(1), emp(2).toInt, emp(3)))
.groupBy(_.department).toSeq: _*)
implicit def iterableWithAvg[T: Numeric](data: Iterable[T]) = new {
def average[T](ts: Iterable[T])(implicit num: Numeric[T]) = {
num.toDouble(ts.sum) / ts.size
}
def avg = average(data)
}
val a = data.flatMap { case (_, emps) => emps.map(_.salary) }.avg
println(s"Reporting top $topN salaries in each department.\n")
println(s"Total of ${data.foldLeft(0)(_ + _._2.size)} employees in ${data.size} departments")
println(f"Average salary: $a%8.2f\n")
data.foreach {
case (dep, emps) => println(f"Department: $dep pop: ${emps.size} avg: ${emps.map(_.salary).avg}%8.2f\n"
+ emps.sortBy(-_.salary).take(topN)
.map(_.toString).mkString("\t", "\n\t", ""))
}
} |
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.
| #Tailspin | Tailspin |
processor Tic-Tac-Toe
@: [1..9 -> (position:$) -> $::value];
source isWonOrDone
[$@Tic-Tac-Toe(1..3) -> #, $@Tic-Tac-Toe(4..6) -> #, $@Tic-Tac-Toe(7..9) -> #,
$@Tic-Tac-Toe(1..9:3) -> #, $@Tic-Tac-Toe(2..9:3) -> #, $@Tic-Tac-Toe(3..9:3) -> #,
$@Tic-Tac-Toe([1,5,9]) -> #, $@Tic-Tac-Toe([3,5,7]) -> #
] -> \(
when <=[]?($@Tic-Tac-Toe <~[<1..9>]>)> do 'draw' !
when <~=[]> do $(1) !
\) !
when <[<=$(first)::raw>+ VOID]> do '$(first); wins!'!
end isWonOrDone
source validMoves
$@Tic-Tac-Toe -> \[i](<1..9> $ !\) !
end validMoves
templates move
when <?($@Tic-Tac-Toe($.position) <position>)> do @Tic-Tac-Toe($.position): $.mark;
$ !
otherwise
'Incorrect move$#10;' -> !OUT::write
end move
source showString
'$:1..9:3 -> '$#10;$@Tic-Tac-Toe($..$+2)...;';$#10;' !
end showString
end Tic-Tac-Toe
composer toInt
<INT>
end toInt
source play
def board: $Tic-Tac-Toe;
@: 'X';
templates getMove
[] -> #
when <=[]> do
$board::showString -> !OUT::write
'$@play; to move $board::validMoves;:$#10;' -> !OUT::write
[{mark: $@play, position: $IN::readline -> toInt} -> board::move] -> #
otherwise
$(1) !
end getMove
$getMove -> #
when <{}> do
'$.mark; played $.position;$#10;' -> !OUT::write
@: $@ -> \(<='X'> 'O'! <='O'> 'X' !\);
[$board::isWonOrDone] -> \(
when <=[]> do $getMove!
otherwise '$(1);$#10;' -> !OUT::write
\) -> #
end play
$play -> !VOID |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Klingphix | Klingphix | include ..\Utilitys.tlhy
:moveDisc %B !B %C !C %A !A %n !n { n A C B }
$n [
$n 1 - $A $B $C moveDisc
( "Move disc " $n " from pole " $A " to pole " $C ) lprint nl
$n 1 - $B $C $A moveDisc
] if
;
{ Move disc 3 from pole 1 to pole 3, with pole 2 as spare }
3 1 3 2 moveDisc
" " input |
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.
| #Scala | Scala | import scala.math._
object Gonio extends App {
//Pi / 4 rad is 45 degrees. All answers should be the same.
val radians = Pi / 4
val degrees = 45.0
println(s"${sin(radians)} ${sin(toRadians(degrees))}")
//cosine
println(s"${cos(radians)} ${cos(toRadians(degrees))}")
//tangent
println(s"${tan(radians)} ${tan(toRadians(degrees))}")
//arcsine
val bgsin = asin(sin(radians))
println(s"$bgsin ${toDegrees(bgsin)}")
val bgcos = acos(cos(radians))
println(s"$bgcos ${toDegrees(bgcos)}")
//arctangent
val bgtan = atan(tan(radians))
println(s"$bgtan ${toDegrees(bgtan)}")
val bgtan2 = atan2(1, 1)
println(s"$bgtan ${toDegrees(bgtan)}")
} |
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.
| #Ruby | Ruby | BinaryTreeNode = Struct.new(:value, :left, :right) do
def self.from_array(nested_list)
value, left, right = nested_list
if value
self.new(value, self.from_array(left), self.from_array(right))
end
end
def walk_nodes(order, &block)
order.each do |node|
case node
when :left then left && left.walk_nodes(order, &block)
when :self then yield self
when :right then right && right.walk_nodes(order, &block)
end
end
end
def each_preorder(&b) walk_nodes([:self, :left, :right], &b) end
def each_inorder(&b) walk_nodes([:left, :self, :right], &b) end
def each_postorder(&b) walk_nodes([:left, :right, :self], &b) end
def each_levelorder
queue = [self]
until queue.empty?
node = queue.shift
yield node
queue << node.left if node.left
queue << node.right if node.right
end
end
end
root = BinaryTreeNode.from_array [1, [2, [4, 7], [5]], [3, [6, [8], [9]]]]
BinaryTreeNode.instance_methods.select{|m| m=~/.+order/}.each do |mthd|
printf "%-11s ", mthd[5..-1] + ':'
root.send(mthd) {|node| print "#{node.value} "}
puts
end |
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #R | R | text <- "Hello,How,Are,You,Today"
junk <- strsplit(text, split=",")
print(paste(unlist(junk), collapse=".")) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.