task_url
stringlengths 30
116
| task_name
stringlengths 2
86
| task_description
stringlengths 0
14.4k
| language_url
stringlengths 2
53
| language_name
stringlengths 1
52
| code
stringlengths 0
61.9k
|
---|---|---|---|---|---|
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Racket | Racket |
#lang racket
(string-join (string-split "Hello,How,Are,You,Today" ",") ".")
;; -> "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
| #Scheme | Scheme | (use gauche.record)
;; This will let us treat a list as though it is a structure (record).
(define-record-type (employee (pseudo-rtd <list>)) #t #t
name id salary dept)
(define (get-fields str)
(map (^x (if (#/^\d/ x) (string->number x) x))
(string-split str #\,)))
(define (print-record column-widths record)
(display " ")
(print (string-join
(map
(^(x width)
(if (number? x)
(format "~vD" width x)
(format "~vA" width x)))
record
column-widths))))
(define (get-column-widths records)
(apply
map
(lambda column
(apply max (map (compose string-length x->string) column)))
records))
(define records
(map get-fields
(string-split
"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"
#/\s*\n\s*/)))
(define (top-salaries n records)
(let ((departments (sort (delete-duplicates (map employee-dept records))))
(col-widths (get-column-widths records))
(sorted-by-salary (sort records > employee-salary)))
(dolist (dept departments)
(print dept)
(let1 matches (filter (^x (string=? dept (employee-dept x)))
sorted-by-salary)
(for-each
(pa$ print-record col-widths)
(take* matches n)))))) |
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.
| #Tcl | Tcl | package require Tcl 8.6
# This code splits the players from the core game engine
oo::class create TicTacToe {
variable board player letter who
constructor {player1class player2class} {
set board {1 2 3 4 5 6 7 8 9}
set player(0) [$player1class new [self] [set letter(0) "X"]]
set player(1) [$player2class new [self] [set letter(1) "O"]]
set who 0
}
method PrintBoard {} {
lassign $board a1 b1 c1 a2 b2 c2 a3 b3 c3
puts [format " %s | %s | %s" $a1 $b1 $c1]
puts "---+---+---"
puts [format " %s | %s | %s" $a2 $b2 $c2]
puts "---+---+---"
puts [format " %s | %s | %s" $a3 $b3 $c3]
}
method WinForSomeone {} {
foreach w {
{0 1 2} {3 4 5} {6 7 8} {0 3 6} {1 4 7} {2 5 8} {0 4 8} {2 4 6}
} {
set b [lindex $board [lindex $w 0]]
if {$b ni "X O"} continue
foreach i $w {if {[lindex $board $i] ne $b} break}
if {[lindex $board $i] eq $b} {
foreach p $w {lappend w1 [expr {$p+1}]}
return [list $b $w1]
}
}
return ""
}
method status {} {
return $board
}
method IsDraw {} {
foreach b $board {if {[string is digit $b]} {return false}}
return true
}
method legalMoves {} {
foreach b $board {if {[string is digit $b]} {lappend legal $b}}
return $legal
}
method DoATurn {} {
set legal [my legalMoves]
my PrintBoard
while 1 {
set move [$player($who) turn]
if {$move in $legal} break
puts "Illegal move!"
}
lset board [expr {$move - 1}] $letter($who)
$player($who) describeMove $move
set who [expr {1 - $who}]
return [my WinForSomeone]
}
method game {} {
puts " Tic-tac-toe game player.
Input the index of where you wish to place your mark at your turn.\n"
while {![my IsDraw]} {
set winner [my DoATurn]
if {$winner eq ""} continue
lassign $winner winLetter winSites
my PrintBoard
puts "\n$winLetter wins across \[[join $winSites {, }]\]"
return $winLetter
}
puts "\nA draw"
}
}
# Stupid robotic player
oo::class create RandomRoboPlayer {
variable g
constructor {game letter} {
set g $game
}
method turn {} {
set legal [$g legalMoves]
return [lindex $legal [expr {int(rand()*[llength $legal])}]]
}
method describeMove {move} {
puts "I go at $move"
}
}
# Interactive human player delegate
oo::class create HumanPlayer {
variable g char
constructor {game letter} {
set g $game
set char $letter
}
method turn {} {
set legal [$g legalMoves]
puts ">>> Put your $char in any of these positions: [join $legal {}]"
while 1 {
puts -nonewline ">>> "
flush stdout
gets stdin number
if {$number in $legal} break
puts ">>> Whoops I don't understand the input!"
}
return $number
}
method describeMove {move} {
puts "You went at $move"
}
}
# Assemble the pieces
set ttt [TicTacToe new HumanPlayer RandomRoboPlayer]
$ttt game |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Kotlin | Kotlin | // version 1.1.0
class Hanoi(disks: Int) {
private var moves = 0
init {
println("Towers of Hanoi with $disks disks:\n")
move(disks, 'L', 'C', 'R')
println("\nCompleted in $moves moves\n")
}
private fun move(n: Int, from: Char, to: Char, via: Char) {
if (n > 0) {
move(n - 1, from, via, to)
moves++
println("Move disk $n from $from to $to")
move(n - 1, via, to, from)
}
}
}
fun main(args: Array<String>) {
Hanoi(3)
Hanoi(4)
} |
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.
| #Scheme | Scheme | (define pi (* 4 (atan 1)))
(define radians (/ pi 4))
(define degrees 45)
(display (sin radians))
(display " ")
(display (sin (* degrees (/ pi 180))))
(newline)
(display (cos radians))
(display " ")
(display (cos (* degrees (/ pi 180))))
(newline)
(display (tan radians))
(display " ")
(display (tan (* degrees (/ pi 180))))
(newline)
(define arcsin (asin (sin radians)))
(display arcsin)
(display " ")
(display (* arcsin (/ 180 pi)))
(newline)
(define arccos (acos (cos radians)))
(display arccos)
(display " ")
(display (* arccos (/ 180 pi)))
(newline)
(define arctan (atan (tan radians)))
(display arctan)
(display " ")
(display (* arctan (/ 180 pi)))
(newline) |
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.
| #Rust | Rust |
#![feature(box_syntax, box_patterns)]
use std::collections::VecDeque;
#[derive(Debug)]
struct TreeNode<T> {
value: T,
left: Option<Box<TreeNode<T>>>,
right: Option<Box<TreeNode<T>>>,
}
enum TraversalMethod {
PreOrder,
InOrder,
PostOrder,
LevelOrder,
}
impl<T> TreeNode<T> {
pub fn new(arr: &[[i8; 3]]) -> TreeNode<i8> {
let l = match arr[0][1] {
-1 => None,
i @ _ => Some(Box::new(TreeNode::<i8>::new(&arr[(i - arr[0][0]) as usize..]))),
};
let r = match arr[0][2] {
-1 => None,
i @ _ => Some(Box::new(TreeNode::<i8>::new(&arr[(i - arr[0][0]) as usize..]))),
};
TreeNode {
value: arr[0][0],
left: l,
right: r,
}
}
pub fn traverse(&self, tr: &TraversalMethod) -> Vec<&TreeNode<T>> {
match tr {
&TraversalMethod::PreOrder => self.iterative_preorder(),
&TraversalMethod::InOrder => self.iterative_inorder(),
&TraversalMethod::PostOrder => self.iterative_postorder(),
&TraversalMethod::LevelOrder => self.iterative_levelorder(),
}
}
fn iterative_preorder(&self) -> Vec<&TreeNode<T>> {
let mut stack: Vec<&TreeNode<T>> = Vec::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
stack.push(self);
while !stack.is_empty() {
let node = stack.pop().unwrap();
res.push(node);
match node.right {
None => {}
Some(box ref n) => stack.push(n),
}
match node.left {
None => {}
Some(box ref n) => stack.push(n),
}
}
res
}
// Leftmost to rightmost
fn iterative_inorder(&self) -> Vec<&TreeNode<T>> {
let mut stack: Vec<&TreeNode<T>> = Vec::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
let mut p = self;
loop {
// Stack parents and right children while left-descending
loop {
match p.right {
None => {}
Some(box ref n) => stack.push(n),
}
stack.push(p);
match p.left {
None => break,
Some(box ref n) => p = n,
}
}
// Visit the nodes with no right child
p = stack.pop().unwrap();
while !stack.is_empty() && p.right.is_none() {
res.push(p);
p = stack.pop().unwrap();
}
// First node that can potentially have a right child:
res.push(p);
if stack.is_empty() {
break;
} else {
p = stack.pop().unwrap();
}
}
res
}
// Left-to-right postorder is same sequence as right-to-left preorder, reversed
fn iterative_postorder(&self) -> Vec<&TreeNode<T>> {
let mut stack: Vec<&TreeNode<T>> = Vec::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
stack.push(self);
while !stack.is_empty() {
let node = stack.pop().unwrap();
res.push(node);
match node.left {
None => {}
Some(box ref n) => stack.push(n),
}
match node.right {
None => {}
Some(box ref n) => stack.push(n),
}
}
let rev_iter = res.iter().rev();
let mut rev: Vec<&TreeNode<T>> = Vec::new();
for elem in rev_iter {
rev.push(elem);
}
rev
}
fn iterative_levelorder(&self) -> Vec<&TreeNode<T>> {
let mut queue: VecDeque<&TreeNode<T>> = VecDeque::new();
let mut res: Vec<&TreeNode<T>> = Vec::new();
queue.push_back(self);
while !queue.is_empty() {
let node = queue.pop_front().unwrap();
res.push(node);
match node.left {
None => {}
Some(box ref n) => queue.push_back(n),
}
match node.right {
None => {}
Some(box ref n) => queue.push_back(n),
}
}
res
}
}
fn main() {
// Array representation of task tree
let arr_tree = [[1, 2, 3],
[2, 4, 5],
[3, 6, -1],
[4, 7, -1],
[5, -1, -1],
[6, 8, 9],
[7, -1, -1],
[8, -1, -1],
[9, -1, -1]];
let root = TreeNode::<i8>::new(&arr_tree);
for method_label in [(TraversalMethod::PreOrder, "pre-order:"),
(TraversalMethod::InOrder, "in-order:"),
(TraversalMethod::PostOrder, "post-order:"),
(TraversalMethod::LevelOrder, "level-order:")]
.iter() {
print!("{}\t", method_label.1);
for n in root.traverse(&method_label.0) {
print!(" {}", n.value);
}
print!("\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
| #Raku | Raku | 'Hello,How,Are,You,Today'.split(',').join('.').say; |
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
| #Raven | Raven | 'Hello,How,Are,You,Today' ',' split '.' join print |
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
| #Sidef | Sidef | var data = <<'EOF'.lines.map{ <name id salary dept> ~Z .split(',') -> flat.to_h }
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
EOF
var n = (ARGV ? Num(ARGV[0]) : "usage: #{__MAIN__} [n]\n".die)
for d in (data.map {|h| h{:dept} }.uniq.sort) {
var es = data.grep { _{:dept} == d }.sort_by { -Num(_{:salary}) }
say d
n.times {
es || break
printf("%-15s | %-6s | %5d\n", es.shift(){<name id salary>...})
}
print "\n"
} |
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.
| #Tiny_BASIC | Tiny BASIC | REM Tic-tac-toe for Tiny BASIC
REM
REM Released as public domain by Damian Gareth Walker, 2019
REM Created: 21-Sep-2019
REM --- Variables
REM A - first square in line examined
REM B - second square in line examined
REM C - third square in line examined
REM D - player whose pieces to count
REM E - number of DREM s pieces on a line
REM F - first square of line to examine
REM G - game winner
REM H - which side the human takes
REM I - increment for line to examine
REM L - line to examine
REM M - where to move (various uses)
REM N - piece found in a square
REM P - player currently playing
REM Q - square to examine
REM R-Z - contents of the board
REM --- Main Program
GOSUB 40
GOSUB 60
GOSUB 80
END
REM --- Subroutine to initialise the game
REM Outputs: H - Human play order
REM P - Whose turn it is
40 PRINT "Tic tac toe. Board positions are:"
PRINT " 1 2 3"
PRINT " 4 5 6"
PRINT " 7 8 9"
PRINT "Play first or second (1/2)?"
INPUT H
IF H<1 THEN GOTO 40
IF H>2 THEN GOTO 40
LET P=1
RETURN
REM --- Subroutine to take turns
REM Inputs: H - who is the human
REM P - whose turn it is
REM Outputs: G - who won the game
60 IF P=H THEN GOSUB 100
IF P<>H THEN GOSUB 120
GOSUB 200
IF G>0 THEN RETURN
LET P=3-P
IF R=0 THEN GOTO 60
IF S=0 THEN GOTO 60
IF T=0 THEN GOTO 60
IF U=0 THEN GOTO 60
IF V=0 THEN GOTO 60
IF W=0 THEN GOTO 60
IF X=0 THEN GOTO 60
IF Y=0 THEN GOTO 60
IF Z=0 THEN GOTO 60
RETURN
REM --- Victory
REM Inputs: H - which side was the human
REM P - player who won
80 IF G=H THEN PRINT "You win!"
IF G<>0 THEN IF G<>H THEN PRINT "Computer wins"
IF G=0 THEN PRINT "A draw"
RETURN
REM --- Subroutine to allow the player to move
REM Inputs: P - player number
REM Outputs: M - where the player wishes to move
100 PRINT "Move? "
INPUT Q
IF Q<1 THEN GOTO 100
IF Q>9 THEN GOTO 100
GOSUB 220
IF N<>0 THEN GOTO 100
LET M=Q
GOSUB 240
RETURN
REM --- Subroutine to make the computerREM s move
REM Inputs: P - player number
REM Outputs: M - the move chosen
120 LET M=0
LET D=3-H
GOSUB 145
IF M>0 THEN GOTO 135
LET D=H
GOSUB 145
IF M=0 THEN IF V=0 THEN LET M=5
IF M=0 THEN IF R=0 THEN LET M=1
IF M=0 THEN IF T=0 THEN LET M=3
IF M=0 THEN IF X=0 THEN LET M=7
IF M=0 THEN IF Z=0 THEN LET M=9
IF M=0 THEN IF S=0 THEN LET M=2
IF M=0 THEN IF U=0 THEN LET M=4
IF M=0 THEN IF Y=0 THEN LET M=8
IF M=0 THEN IF W=0 THEN LET M=6
135 GOSUB 240
PRINT "Computer move ",M
RETURN
REM --- Identify moves to win or avoid a loss
REM Inputs: D - player whose pieces weREM re counting
REM Changes: E - number of pieces on line being scanned
REM F - first square in winning line
REM I - increment of winning line
REM L - line being scanned (counter)
145 LET L=1
146 GOSUB 170
IF E<2 THEN GOTO 152
IF A=0 THEN LET M=F
IF B=0 THEN LET M=F+I
IF C=0 THEN LET M=F+I+I
IF M>0 THEN RETURN
152 LET L=L+1
IF L<9 THEN GOTO 146
RETURN
REM --- Count a playerREM s pieces on a line
REM Inputs: D - player whose pieces weREM re counting
REM L - line number
REM Changes: F - first square on the line
REM I - increment of the line
REM Q - individual squares to examine
REM Outputs: A - contents of first square
REM B - contents of second square
REM C - contents of third square
REM E - number of the playerREM s pieces
170 IF L>3 THEN GOTO 174
LET F=3*L-2
LET I=1
GOTO 180
174 IF L>6 THEN GOTO 178
LET F=L-3
LET I=3
GOTO 180
178 LET F=1+2*(L-7)
LET I=4-2*(L-7)
180 LET E=0
LET Q=F
GOSUB 220
LET A=N
IF N=D THEN LET E=E+1
LET Q=Q+I
GOSUB 220
LET B=N
IF N=D THEN LET E=E+1
LET Q=Q+I
GOSUB 220
LET C=N
IF N=D THEN LET E=E+1
RETURN
REM --- Subroutine to check for a win
REM Inputs: R-Z - board squares
REM Outputs: G - the winning player (0 for neither)
200 LET G=0
IF R>0 THEN IF R=S THEN IF S=T THEN LET G=R
IF U>0 THEN IF U=V THEN IF V=W THEN LET G=U
IF X>0 THEN IF X=Y THEN IF Y=Z THEN LET G=X
IF R>0 THEN IF R=U THEN IF U=X THEN LET G=R
IF S>0 THEN IF S=V THEN IF V=Y THEN LET G=S
IF T>0 THEN IF T=W THEN IF W=Z THEN LET G=T
IF R>0 THEN IF R=V THEN IF V=Z THEN LET G=R
IF T>0 THEN IF T=V THEN IF V=X THEN LET G=T
RETURN
REM --- Subroutine to see what piece is in a square
REM Inputs: Q - the square to check
REM R-Z - the contents of the squares
REM Outputs: N - the piece in that square
220 LET N=0
IF Q=1 THEN LET N=R
IF Q=2 THEN LET N=S
IF Q=3 THEN LET N=T
IF Q=4 THEN LET N=U
IF Q=5 THEN LET N=V
IF Q=6 THEN LET N=W
IF Q=7 THEN LET N=X
IF Q=8 THEN LET N=Y
IF Q=9 THEN LET N=Z
RETURN
REM --- Subroutine to put a piece in a square
REM Inputs: P - the player whose piece should be placed
REM M - the square to put the piece in
REM Changes: R-Z - the contents of the squares
240 IF M=1 THEN LET R=P
IF M=2 THEN LET S=P
IF M=3 THEN LET T=P
IF M=4 THEN LET U=P
IF M=5 THEN LET V=P
IF M=6 THEN LET W=P
IF M=7 THEN LET X=P
IF M=8 THEN LET Y=P
IF M=9 THEN LET Z=P
RETURN |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #lambdatalk | lambdatalk |
{def move
{lambda {:n :from :to :via}
{if {<= :n 0}
then >
else {move {- :n 1} :from :via :to}
move disk :n from :from to :to {br}
{move {- :n 1} :via :to :from} }}}
-> move
{move 4 A B C}
> move disk 1 from A to C
> move disk 2 from A to B
> move disk 1 from C to B
> move disk 3 from A to C
> move disk 1 from B to A
> move disk 2 from B to C
> move disk 1 from A to C
> move disk 4 from A to B
> move disk 1 from C to B
> move disk 2 from C to A
> move disk 1 from B to A
> move disk 3 from C to B
> move disk 1 from A to C
> move disk 2 from A to B
> move disk 1 from C to B
|
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.
| #Seed7 | Seed7 | $ include "seed7_05.s7i";
include "float.s7i";
include "math.s7i";
const proc: main is func
local
const float: radians is PI / 4.0;
const float: degrees is 45.0;
begin
writeln(" radians degrees");
writeln("sine: " <& sin(radians) digits 5 <& sin(degrees * PI / 180.0) digits 5 lpad 9);
writeln("cosine: " <& cos(radians) digits 5 <& cos(degrees * PI / 180.0) digits 5 lpad 9);
writeln("tangent: " <& tan(radians) digits 5 <& tan(degrees * PI / 180.0) digits 5 lpad 9);
writeln("arcsine: " <& asin(0.70710677) digits 5 <& asin(0.70710677) * 180.0 / PI digits 5 lpad 9);
writeln("arccosine: " <& acos(0.70710677) digits 5 <& acos(0.70710677) * 180.0 / PI digits 5 lpad 9);
writeln("arctangent: " <& atan(1.0) digits 5 <& atan(1.0) * 180.0 / PI digits 5 lpad 9);
end func; |
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.
| #Sidef | Sidef | var angle_deg = 45;
var angle_rad = Num.pi/4;
for arr in [
[sin(angle_rad), sin(deg2rad(angle_deg))],
[cos(angle_rad), cos(deg2rad(angle_deg))],
[tan(angle_rad), tan(deg2rad(angle_deg))],
[cot(angle_rad), cot(deg2rad(angle_deg))],
] {
say arr.join(" ");
}
for n in [
asin(sin(angle_rad)),
acos(cos(angle_rad)),
atan(tan(angle_rad)),
acot(cot(angle_rad)),
] {
say [n, rad2deg(n)].join(' ');
} |
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.
| #Scala | Scala | case class IntNode(value: Int, left: Option[IntNode] = None, right: Option[IntNode] = None) {
def preorder(f: IntNode => Unit) {
f(this)
left.map(_.preorder(f)) // Same as: if(left.isDefined) left.get.preorder(f)
right.map(_.preorder(f))
}
def postorder(f: IntNode => Unit) {
left.map(_.postorder(f))
right.map(_.postorder(f))
f(this)
}
def inorder(f: IntNode => Unit) {
left.map(_.inorder(f))
f(this)
right.map(_.inorder(f))
}
def levelorder(f: IntNode => Unit) {
def loVisit(ls: List[IntNode]): Unit = ls match {
case Nil => None
case node :: rest => f(node); loVisit(rest ++ node.left ++ node.right)
}
loVisit(List(this))
}
}
object TreeTraversal extends App {
implicit def intNode2SomeIntNode(n: IntNode) = Some[IntNode](n)
val tree = IntNode(1,
IntNode(2,
IntNode(4,
IntNode(7)),
IntNode(5)),
IntNode(3,
IntNode(6,
IntNode(8),
IntNode(9))))
List(
" preorder: " -> tree.preorder _, // `_` denotes the function value of type `IntNode => Unit` (returning nothing)
" inorder: " -> tree.inorder _,
" postorder: " -> tree.postorder _,
"levelorder: " -> tree.levelorder _) foreach {
case (name, func) =>
val s = new StringBuilder(name)
func(n => s ++= n.value.toString + " ")
println(s)
}
} |
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
| #REBOL | REBOL | print ["Original:" original: "Hello,How,Are,You,Today"]
tokens: parse original ","
dotted: "" repeat i tokens [append dotted rejoin [i "."]]
print ["Dotted: " dotted] |
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
| #Red | Red | str: "Hello,How,Are,You,Today"
>> tokens: split str ","
>> probe tokens
["Hello" "How" "Are" "You" "Today"]
>> periods: replace/all form tokens " " "." ;The word FORM converts the list series to a string removing quotes.
>> print periods ;then REPLACE/ALL spaces with period
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
| #SMEQL | SMEQL | table: Employees
----------------
empID
dept
empName
salary |
http://rosettacode.org/wiki/Tic-tac-toe | Tic-tac-toe |
Task
Play a game of tic-tac-toe.
Ensure that legal moves are played and that a winning position is notified.
Tic-tac-toe is also known as:
naughts and crosses
tic tac toe
tick tack toe
three in a row
tres en rayo and
Xs and Os
See also
MathWorld™, Tic-Tac-Toe game.
Wikipedia tic-tac-toe.
| #UNIX_Shell | UNIX Shell | #!/usr/bin/env bash
# play tic-tac-toe
main() {
local play_again=1
while (( play_again )); do
local board=(1 2 3 4 5 6 7 8 9) tokens=(X O)
show_board "${board[@]}"
# player colors: computer is red, human is green
local computer=31 human=32
if (( RANDOM % 2 )); then
players=(computer human)
colors=($computer $human)
printf 'I go first!\n'
else
players=(human computer)
colors=($human $computer)
printf 'You go first!\n'
fi
local token winner
local -i turn=0
while ! winner=$(winner "${board[@]}"); do
token=${tokens[turn%2]}
case "${players[turn%2]}" in
human) board=($(human_turn "$token" "${board[@]}"));;
computer) board=($(computer_turn "$token" "${board[@]}"));;
*) printf 'Unknown player "%s"\n' "${players[turn%2]}"; exit 1;;
esac
show_board "${board[@]}" | sed -e "s/${tokens[0]}/"$'\e['"${colors[0]}"$'m&\e[0m/g' \
-e "s/${tokens[1]}/"$'\e['"${colors[1]}"$'m&\e[0m/g'
(( turn=turn+1 ))
done
case "$winner${players[0]}" in
Ohuman|Xcomputer) printf 'I win!\n';;
Xhuman|Ocomputer) printf 'You win!\n';;
cat*) printf 'The cat wins!\n';;
esac
yorn 'Play again'
play_again=$(( ! $? ))
done
}
show_board() {
printf '\n'
printf '%s %s %s\n' "$@"
printf '\n'
}
winner() {
local board=("$@") i j k
local lines=("0 1 2" "0 3 6" "0 4 8" "1 4 7"
"2 4 6" "2 5 8" "3 4 5" "6 7 8")
local line i j k
for line in "${lines[@]}"; do
read i j k <<<"$line"
local token=${board[i]}
if [[ "${board[j]}" == $token && "${board[k]}" == $token ]]; then
printf '%s\n' "$token"
return 0
fi
done
case "${board[*]}" in
*[1-9]*) return 1;;
*) printf 'cat\n'; return 0;;
esac
}
human_turn() {
local token=$1
shift
local board=("$@")
local n=0
while (( n < 1 || n > 9 )) || [[ "${board[n-1]}" != $n ]]; do
printf 'Enter space number: ' "$n" "${board[n-1]}" >/dev/tty
read n </dev/tty >/dev/tty 2>&1
done
board[n-1]=$token
printf '%s\n' "${board[@]}"
}
computer_turn() {
local token=$1
shift
local board=("$@")
local i=0 blanks=() choice
for (( i=0; i<9; ++i )); do
if [[ "${board[i]}" == [1-9] ]]; then
blanks+=("$i")
fi
done
choice=${blanks[RANDOM % ${#blanks[@]}]}
board[choice]=$token
printf '%s\n' "${board[@]}"
}
yorn() {
local yorn=
while [[ $yorn != [Yy]* && $yorn != [Nn]* ]]; do
printf '%s? ' "$*"
read yorn
done
[[ $yorn == [Yy]* ]]
}
main "$@" |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Lasso | Lasso | #!/usr/bin/lasso9
define towermove(
disks::integer,
a,b,c
) => {
if(#disks > 0) => {
towermove(#disks - 1, #a, #c, #b )
stdoutnl("Move disk from " + #a + " to " + #c)
towermove(#disks - 1, #b, #a, #c )
}
}
towermove((integer($argv -> second || 3)), "A", "B", "C") |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Liberty_BASIC | Liberty BASIC | source$ ="A"
via$ ="B"
target$ ="C"
call hanoi 4, source$, target$, via$ ' ie call procedure to move legally 4 disks from peg A to peg C via peg B
wait
sub hanoi numDisks, source$, target$, via$
if numDisks =0 then
exit sub
else
call hanoi numDisks -1, source$, via$, target$
print " Move disk "; numDisks; " from peg "; source$; " to peg "; target$
call hanoi numDisks -1, via$, target$, source$
end if
end sub
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.
| #SQL_PL | SQL PL |
--Conversion
VALUES degrees(3.1415926);
VALUES radians(180);
-- This is equal to Pi.
--PI/4 45
VALUES sin(radians(180)/4);
VALUES sin(radians(45));
VALUES cos(radians(180)/4);
VALUES cos(radians(45));
VALUES tan(radians(180)/4);
VALUES tan(radians(45));
VALUES cot(radians(180)/4);
VALUES cot(radians(45));
VALUES asin(sin(radians(180)/4));
VALUES asin(sin(radians(45)));
VALUES atan(tan(radians(180)/4));
VALUES atan(tan(radians(45)));
--PI/3 60
VALUES sin(radians(180)/3);
VALUES sin(radians(60));
VALUES cos(radians(180)/3);
VALUES cos(radians(60));
VALUES tan(radians(180)/3);
VALUES tan(radians(60));
VALUES cot(radians(180)/3);
VALUES cot(radians(60));
VALUES asin(sin(radians(180)/3));
VALUES asin(sin(radians(60)));
VALUES atan(tan(radians(180)/3));
VALUES atan(tan(radians(60)));
|
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.
| #Scheme | Scheme | (define (preorder tree)
(if (null? tree)
'()
(append (list (car tree))
(preorder (cadr tree))
(preorder (caddr tree)))))
(define (inorder tree)
(if (null? tree)
'()
(append (inorder (cadr tree))
(list (car tree))
(inorder (caddr tree)))))
(define (postorder tree)
(if (null? tree)
'()
(append (postorder (cadr tree))
(postorder (caddr tree))
(list (car tree)))))
(define (level-order tree)
(define lst '())
(define (traverse nodes)
(if (pair? nodes)
(let ((next-nodes '()))
(do ((p nodes (cdr p)))
((null? p))
(set! lst (cons (caar p) lst))
(let* ((n '())
(n (if (null? (cadar p))
n
(cons (cadar p) n)))
(n (if (null? (caddar p))
n
(cons (caddar p) n))))
(set! next-nodes (append n next-nodes))))
(traverse (reverse next-nodes)))))
(if (null? tree)
'()
(begin
(traverse (list tree))
(reverse lst))))
(define (demonstration tree)
(define (display-values lst)
(do ((p lst (cdr p)))
((null? p))
(display (car p))
(if (pair? (cdr p))
(display " ")))
(newline))
(display "preorder: ") (display-values (preorder tree))
(display "inorder: ") (display-values (inorder tree))
(display "postorder: ") (display-values (postorder tree))
(display "level-order: ") (display-values (level-order tree)))
(define the-task-tree
'(1 (2 (4 (7 () ())
())
(5 () ()))
(3 (6 (8 () ())
(9 () ()))
())))
(demonstration the-task-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
| #Retro | Retro | {{
: char ( -$ ) " " ;
: tokenize ( $-$$ )
@char ^strings'splitAtChar withLength 1- over + 0 swap ! tempString ;
: action ( $- )
keepString ^buffer'add ;
---reveal---
: split ( $cb- )
^buffer'set !char
char ^strings'append
[ tokenize action dup 1 <> ] while drop
^buffer'get drop ;
}} |
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
| #REXX | REXX | /*REXX program separates a string of comma─delimited words, and echoes them ──► terminal*/
original = 'Hello,How,Are,You,Today' /*some words separated by commas (,). */
say 'The input string:' original /*display original string ──► terminal.*/
new= original /*make a copy of the string. */
do #=1 until new=='' /*keep processing until NEW is empty.*/
parse var new @.# ',' new /*parse words delineated by a comma (,)*/
end /*#*/ /* [↑] the new array is named @. */
say /* NEW is destructively parsed. [↑] */
say center(' Words in the string ', 40, "═") /*display a nice header for the list. */
do j=1 for # /*display all the words (one per line),*/
say @.j || left(., j\==#) /*maybe append a period (.) to a word. */
end /*j*/ /* [↑] don't append a period if last. */
say center(' End─of─list ', 40, "═") /*display a (EOL) trailer for the list.*/ |
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
| #SQL | SQL | CREATE TABLE EMP
(
EMP_ID varchar2(6 CHAR),
EMP_NAMEvarchar2(20 CHAR),
DEPT_ID varchar2(4 CHAR),
SALARY NUMBER(10,2)
);
INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)
VALUES ('E21437','John Rappl','D050',47000);
INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)
VALUES ('E10297','Tyler Bennett','D101',32000);
INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)
VALUES ('E00127','George Woltman','D101',53500);
INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)
VALUES ('E63535','Adam Smith','D202',18000);
INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)
VALUES ('E39876','Claire Buckman','D202',27800);
INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)
VALUES ('E04242','David McClellan','D101',41500);
INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)
VALUES ('E41298','Nathan Adams','D050',21900);
INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)
VALUES ('E43128','Richard Potter','D101',15900);
INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)
VALUES ('E27002','David Motsinger','D202',19250);
INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)
VALUES ('E03033','Tim Sampair','D101',27000);
INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)
VALUES ('E10001','Kim Arlich','D190',57000);
INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)
VALUES ('E16398','Timothy Grove','D190',29900);
INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)
VALUES ('E01234','Rich Holcomb','D202',49500);
INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)
VALUES ('E16399','Timothy Grave','D190',29900);
INSERT INTO EMP (EMP_ID, EMP_NAME, DEPT_ID, SALARY)
VALUES ('E16400','Timothy Grive','D190',29900);
COMMIT; |
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.
| #VBA | VBA |
Option Explicit
Private Lines(1 To 3, 1 To 3) As String
Private Nb As Byte, player As Byte
Private GameWin As Boolean, GameOver As Boolean
Sub Main_TicTacToe()
Dim p As String
InitLines
printLines Nb
Do
p = WhoPlay
Debug.Print p & " play"
If p = "Human" Then
Call HumanPlay
GameWin = IsWinner("X")
Else
Call ComputerPlay
GameWin = IsWinner("O")
End If
If Not GameWin Then GameOver = IsEnd
Loop Until GameWin Or GameOver
If Not GameOver Then
Debug.Print p & " Win !"
Else
Debug.Print "Game Over!"
End If
End Sub
Sub InitLines(Optional S As String)
Dim i As Byte, j As Byte
Nb = 0: player = 0
For i = LBound(Lines, 1) To UBound(Lines, 1)
For j = LBound(Lines, 2) To UBound(Lines, 2)
Lines(i, j) = "#"
Next j
Next i
End Sub
Sub printLines(Nb As Byte)
Dim i As Byte, j As Byte, strT As String
Debug.Print "Loop " & Nb
For i = LBound(Lines, 1) To UBound(Lines, 1)
For j = LBound(Lines, 2) To UBound(Lines, 2)
strT = strT & Lines(i, j)
Next j
Debug.Print strT
strT = vbNullString
Next i
End Sub
Function WhoPlay(Optional S As String) As String
If player = 0 Then
player = 1
WhoPlay = "Human"
Else
player = 0
WhoPlay = "Computer"
End If
End Function
Sub HumanPlay(Optional S As String)
Dim L As Byte, C As Byte, GoodPlay As Boolean
Do
L = Application.InputBox("Choose the row", "Numeric only", Type:=1)
If L > 0 And L < 4 Then
C = Application.InputBox("Choose the column", "Numeric only", Type:=1)
If C > 0 And C < 4 Then
If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then
Lines(L, C) = "X"
Nb = Nb + 1
printLines Nb
GoodPlay = True
End If
End If
End If
Loop Until GoodPlay
End Sub
Sub ComputerPlay(Optional S As String)
Dim L As Byte, C As Byte, GoodPlay As Boolean
Randomize Timer
Do
L = Int((Rnd * 3) + 1)
C = Int((Rnd * 3) + 1)
If Lines(L, C) = "#" And Not Lines(L, C) = "X" And Not Lines(L, C) = "O" Then
Lines(L, C) = "O"
Nb = Nb + 1
printLines Nb
GoodPlay = True
End If
Loop Until GoodPlay
End Sub
Function IsWinner(S As String) As Boolean
Dim i As Byte, j As Byte, Ch As String, strTL As String, strTC As String
Ch = String(UBound(Lines, 1), S)
'check lines & columns
For i = LBound(Lines, 1) To UBound(Lines, 1)
For j = LBound(Lines, 2) To UBound(Lines, 2)
strTL = strTL & Lines(i, j)
strTC = strTC & Lines(j, i)
Next j
If strTL = Ch Or strTC = Ch Then IsWinner = True: Exit For
strTL = vbNullString: strTC = vbNullString
Next i
'check diagonales
strTL = Lines(1, 1) & Lines(2, 2) & Lines(3, 3)
strTC = Lines(1, 3) & Lines(2, 2) & Lines(3, 1)
If strTL = Ch Or strTC = Ch Then IsWinner = True
End Function
Function IsEnd() As Boolean
Dim i As Byte, j As Byte
For i = LBound(Lines, 1) To UBound(Lines, 1)
For j = LBound(Lines, 2) To UBound(Lines, 2)
If Lines(i, j) = "#" Then Exit Function
Next j
Next i
IsEnd = True
End Function
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Lingo | Lingo | on hanoi (n, a, b, c)
if n > 0 then
hanoi(n-1, a, c, b)
put "Move disk from" && a && "to" && c
hanoi(n-1, b, a, c)
end if
end |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Logo | Logo | to move :n :from :to :via
if :n = 0 [stop]
move :n-1 :from :via :to
(print [Move disk from] :from [to] :to)
move :n-1 :via :to :from
end
move 4 "left "middle "right |
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.
| #Stata | Stata | scalar deg=_pi/180
display cos(30*deg)
display sin(30*deg)
display tan(30*deg)
display cos(_pi/6)
display sin(_pi/6)
display tan(_pi/6)
display acos(0.5)
display asin(0.5)
display atan(0.5) |
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.
| #SequenceL | SequenceL |
main(args(2)) :=
"preorder: " ++ toString(preOrder(testTree)) ++
"\ninoder: " ++ toString(inOrder(testTree)) ++
"\npostorder: " ++ toString(postOrder(testTree)) ++
"\nlevel-order: " ++ toString(levelOrder(testTree));
Node ::= (value : int, left : Node, right : Node);
preOrder(n) := [n.value] ++
(preOrder(n.left) when isDefined(n, left) else []) ++
(preOrder(n.right) when isDefined(n, right) else []);
inOrder(n) := (inOrder(n.left) when isDefined(n, left) else []) ++
[n.value] ++
(inOrder(n.right) when isDefined(n, right) else []);
postOrder(n) := (postOrder(n.left) when isDefined(n, left) else []) ++
(postOrder(n.right) when isDefined(n, right) else []) ++
[n.value];
levelOrder(n) := levelOrderHelper([n]);
levelOrderHelper(ns(1)) :=
let
n := head(ns);
in
[] when size(ns) = 0 else
[n.value] ++ levelOrderHelper(tail(ns) ++
([n.left] when isDefined(n, left) else []) ++
([n.right] when isDefined(n, right) else []));
testTree :=
(value : 1,
left : (value : 2,
left : (value : 4,
left : (value : 7)),
right : (value : 5)),
right : (value : 3,
left : (value : 6,
left : (value : 8),
right : (value : 9))
)
);
|
http://rosettacode.org/wiki/Tokenize_a_string | Tokenize a string | Separate the string "Hello,How,Are,You,Today" by commas into an array (or list) so that each element of it stores a different word.
Display the words to the 'user', in the simplest manner possible, separated by a period.
To simplify, you may display a trailing period.
Other tasks related to string operations:
Metrics
Array length
String length
Copy a string
Empty string (assignment)
Counting
Word frequency
Letter frequency
Jewels and stones
I before E except after C
Bioinformatics/base count
Count occurrences of a substring
Count how many vowels and consonants occur in a string
Remove/replace
XXXX redacted
Conjugate a Latin verb
Remove vowels from a string
String interpolation (included)
Strip block comments
Strip comments from a string
Strip a set of characters from a string
Strip whitespace from a string -- top and tail
Strip control codes and extended characters from a string
Anagrams/Derangements/shuffling
Word wheel
ABC problem
Sattolo cycle
Knuth shuffle
Ordered words
Superpermutation minimisation
Textonyms (using a phone text pad)
Anagrams
Anagrams/Deranged anagrams
Permutations/Derangements
Find/Search/Determine
ABC words
Odd words
Word ladder
Semordnilap
Word search
Wordiff (game)
String matching
Tea cup rim text
Alternade words
Changeable words
State name puzzle
String comparison
Unique characters
Unique characters in each string
Extract file extension
Levenshtein distance
Palindrome detection
Common list elements
Longest common suffix
Longest common prefix
Compare a list of strings
Longest common substring
Find common directory path
Words from neighbour ones
Change e letters to i in words
Non-continuous subsequences
Longest common subsequence
Longest palindromic substrings
Longest increasing subsequence
Words containing "the" substring
Sum of the digits of n is substring of n
Determine if a string is numeric
Determine if a string is collapsible
Determine if a string is squeezable
Determine if a string has all unique characters
Determine if a string has all the same characters
Longest substrings without repeating characters
Find words which contains all the vowels
Find words which contains most consonants
Find words which contains more than 3 vowels
Find words which first and last three letters are equals
Find words which odd letters are consonants and even letters are vowels or vice_versa
Formatting
Substring
Rep-string
Word wrap
String case
Align columns
Literals/String
Repeat a string
Brace expansion
Brace expansion using ranges
Reverse a string
Phrase reversals
Comma quibbling
Special characters
String concatenation
Substring/Top and tail
Commatizing numbers
Reverse words in a string
Suffixation of decimal numbers
Long literals, with continuations
Numerical and alphabetical suffixes
Abbreviations, easy
Abbreviations, simple
Abbreviations, automatic
Song lyrics/poems/Mad Libs/phrases
Mad Libs
Magic 8-ball
99 Bottles of Beer
The Name Game (a song)
The Old lady swallowed a fly
The Twelve Days of Christmas
Tokenize
Text between
Tokenize a string
Word break problem
Tokenize a string with escaping
Split a character string based on change of character
Sequences
Show ASCII table
De Bruijn sequences
Self-referential sequences
Generate lower case ASCII alphabet
| #Ring | Ring |
see substr("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
| #Ruby | Ruby | puts "Hello,How,Are,You,Today".split(',').join('.') |
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
| #Stata | Stata | import delimited employees.csv
local k 2
bysort department (salary): list salary if _N-_n<`k' |
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.
| #Wren | Wren | import "random" for Random
import "/ioutil" for Input
var r = Random.new()
var b = List.filled(3, null)
for (i in 0..2) b[i] = List.filled(3, 0) // board -> 0: blank; -1: computer; 1: human
var bestI = 0
var bestJ = 0
var checkWinner = Fn.new {
for (i in 0..2) {
if (b[i][0] != 0 && b[i][1] == b[i][0] && b[i][2] == b[i][0]) return b[i][0]
if (b[0][i] != 0 && b[1][i] == b[0][i] && b[2][i] == b[0][i]) return b[0][i]
}
if (b[1][1] == 0) return 0
if (b[1][1] == b[0][0] && b[2][2] == b[0][0]) return b[0][0]
if (b[1][1] == b[2][0] && b[0][2] == b[1][1]) return b[1][1]
return 0
}
var showBoard = Fn.new {
var t = "X O"
for (i in 0..2) {
for (j in 0..2) System.write("%(t[b[i][j] + 1]) ")
System.print()
}
System.print("-----")
}
var testMove // recursive
testMove = Fn.new { |value, depth|
var best = -1
var changed = 0
var score = checkWinner.call()
if (score != 0) return (score == value) ? 1 : -1
for (i in 0..2) {
for (j in 0..2) {
if (b[i][j] == 0) {
b[i][j] = value
changed = value
score = -testMove.call(-value, depth + 1)
b[i][j] = 0
if (score > best) {
if (depth == 0) {
bestI = i
bestJ = j
}
best = score
}
}
}
}
return (changed != 0) ? best : 0
}
var game = Fn.new { |u|
for (i in 0..2) {
for (j in 0..2) b[i][j] = 0
}
System.print("Board postions are numbered so:\n1 2 3\n4 5 6\n7 8 9")
System.print("You have O, I have X.\n")
for (k in 0..8) {
while (u) {
var move = Input.integer("Your move: ", 1, 9) - 1
var i = (move/3).floor
var j = move % 3
if (b[i][j] == 0) {
b[i][j] = 1
break
}
}
if (!u) {
if (k == 0) { // randomize if computer opens, less boring
bestI = r.int(1e6) % 3
bestJ = r.int(1e6) % 3
} else {
testMove.call(-1, 0)
}
b[bestI][bestJ] = -1
var myMove = bestI * 3 + bestJ + 1
System.print("My move: %(myMove)")
}
showBoard.call()
var win = checkWinner.call()
if (win != 0) return ((win == 1) ? "You win" : "I win") + ".\n\n"
u = !u
}
return "A draw.\n\n"
}
var user = false
while (true) {
user = !user
System.write(game.call(user))
var yn = Input.option("Play again y/n: ", "yYnN")
if (yn == "n" || yn == "N") return
System.print()
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Logtalk | Logtalk | :- object(hanoi).
:- public(run/1).
:- mode(run(+integer), one).
:- info(run/1, [
comment is 'Solves the towers of Hanoi problem for the specified number of disks.',
argnames is ['Disks']]).
run(Disks) :-
move(Disks, left, middle, right).
move(1, Left, _, Right):-
!,
report(Left, Right).
move(Disks, Left, Aux, Right):-
Disks2 is Disks - 1,
move(Disks2, Left, Right, Aux),
report(Left, Right),
move(Disks2, Aux, Left, Right).
report(Pole1, Pole2):-
write('Move a disk from '),
writeq(Pole1),
write(' to '),
writeq(Pole2),
write('.'),
nl.
:- end_object. |
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.
| #Tcl | Tcl | package require Tcl 8.5
proc PI {} {expr {4*atan(1)}}
proc deg2rad d {expr {$d/180*[PI]}}
proc rad2deg r {expr {$r*180/[PI]}}
namespace path ::tcl::mathfunc
proc trig degrees {
set radians [deg2rad $degrees]
puts [sin $radians]
puts [cos $radians]
puts [tan $radians]
set arcsin [asin [sin $radians]]; puts "$arcsin [rad2deg $arcsin]"
set arccos [acos [cos $radians]]; puts "$arccos [rad2deg $arccos]"
set arctan [atan [tan $radians]]; puts "$arctan [rad2deg $arctan]"
}
trig 60.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.
| #Sidef | Sidef | func preorder(t) {
t ? [t[0], __FUNC__(t[1])..., __FUNC__(t[2])...] : [];
}
func inorder(t) {
t ? [__FUNC__(t[1])..., t[0], __FUNC__(t[2])...] : [];
}
func postorder(t) {
t ? [__FUNC__(t[1])..., __FUNC__(t[2])..., t[0]] : [];
}
func depth(t) {
var a = [t];
var ret = [];
while (a.len > 0) {
var v = (a.shift \\ next);
ret « v[0];
a += [v[1,2]];
};
return ret;
}
var x = [1,[2,[4,[7]],[5]],[3,[6,[8],[9]]]];
say "pre: #{preorder(x)}";
say "in: #{inorder(x)}";
say "post: #{postorder(x)}";
say "depth: #{depth(x)}"; |
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
| #Rust | Rust | fn main() {
let s = "Hello,How,Are,You,Today";
let tokens: Vec<&str> = s.split(",").collect();
println!("{}", tokens.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
| #S-lang | S-lang | variable a = strchop("Hello,How,Are,You,Today", ',', 0);
print(strjoin(a, ".")); |
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
| #Swift | Swift | struct Employee {
var name: String
var id: String
var salary: Int
var department: String
}
let employees = [
Employee(name: "Tyler Bennett", id: "E10297", salary: 32000, department: "D101"),
Employee(name: "John Rappl", id: "E21437", salary: 47000, department: "D050"),
Employee(name: "George Woltman", id: "E00127", salary: 53500, department: "D101"),
Employee(name: "Adam Smith", id: "E63535", salary: 18000, department: "D202"),
Employee(name: "Claire Buckman", id: "E39876", salary: 27800, department: "D202"),
Employee(name: "David McClellan", id: "E04242", salary: 41500, department: "D101"),
Employee(name: "Rich Holcomb", id: "E01234", salary: 49500, department: "D202"),
Employee(name: "Nathan Adams", id: "E41298", salary: 21900, department: "D050"),
Employee(name: "Richard Potter", id: "E43128", salary: 15900, department: "D101"),
Employee(name: "David Motsinger", id: "E27002", salary: 19250, department: "D202"),
Employee(name: "Tim Sampair", id: "E03033", salary: 27000, department: "D101"),
Employee(name: "Kim Arlich", id: "E10001", salary: 57000, department: "D190"),
Employee(name: "Timothy Grove", id: "E16398", salary: 29900, department: "D190")
]
func highestSalaries(employees: [Employee], n: Int = 1) -> [String: [Employee]] {
return employees.reduce(into: [:], {acc, employee in
guard var cur = acc[employee.department] else {
acc[employee.department] = [employee]
return
}
if cur.count < n {
cur.append(employee)
} else if cur.last!.salary < employee.salary {
cur[n - 1] = employee
}
acc[employee.department] = cur.sorted(by: { $0.salary > $1.salary })
})
}
for (dept, employees) in highestSalaries(employees: employees, n: 3) {
let employeeString = employees.map({ "\($0.name): \($0.salary)" }).joined(separator: "\n\t")
print("\(dept)'s highest paid employees are: \n\t\(employeeString)")
} |
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.
| #XPL0 | XPL0 | \The computer marks its moves with an "O" and the player uses an "X". The
\ numeric keypad is used to make the player's move.
\
\ 7 | 8 | 9
\ ---+---+---
\ 4 | 5 | 6
\ ---+---+---
\ 1 | 2 | 3
\
\The player always goes first, but the 0 key is used to skip a move. Thus
\ it can be used to let the computer play first. Esc terminates program.
inc c:\cxpl\codes; \intrinsic routine declarations
def X0=16, Y0=10; \coordinates of character in upper-left square
int I0,
PMove, \player's move (^0..^9)
Key; \keystroke
int X, O; \bit arrays for player and computer
\ bit 0 corresponds to playing square 1, etc.
proc HLine(X, Y); \Draw a horizontal line
int X, Y;
int I;
[Cursor(X, Y);
for I:= 0 to 10 do ChOut(0, ^Ä);
]; \HLine
proc VLine(X, Y); \Draw a vertical line over the above horizontal line
int X, Y;
int I;
[for I:= 0 to 4 do
[Cursor(X, Y+I);
ChOut(0, if I&1 then ^Å else ^³);
];
]; \VLine
func Won(p); \Return 'true' if player P has won
int P;
int T, I;
[T:= [$007, $038, $1C0, $049, $092, $124, $111, $054];
for I:= 0 to 7 do \check if player matches a bit pattern for 3 in a row
if (P & T(I)) = T(I) then return true;
return false;
]; \Won
func Cats; \Return 'true' if no more moves available (Cat's game)
[if (X ! O) = $1FF then \all bit positions played
[Cursor(17, 20);
Text(0, "A draw!");
return true;
];
return false;
]; \Cats
proc DoMove(P, M, Ch); \Make move in player's bit array and display it
int P, \address of player's bit array
M, \index 0..8 where bit is placed
Ch;
int I, X, Y;
[P(0):= P(0) ! 1<<M; \make move
I:= M / 3; \display move
X:= Rem(0) * 4;
Y:= (2-I) * 2;
Cursor(X+X0, Y+Y0);
ChOut(0, Ch);
]; \DoMove
func Try(P); \Return the value of the best node for player P
int P; \address of player's bit array
int P1, I, I0, V, V0;
[P1:= if P = addr X then addr O else addr X;
if Won(P1(0)) then return -1;
if (X ! O) = $1FF then return 0;
V0:= -1; \assume the worst
for I:= 0 to 8 do \for all of the squares...
if ((O!X) & 1<<I) = 0 then \if square is unused
[P(0):= P(0) ! 1<<I; \make tenative move
V:= -(extend(Try(P1))); \get value
if V > V0 then \save best value
[V0:= V; I0:= I];
P(0):= P(0) & ~(1<<I); \undo tenative move
];
return V0 & $FF ! I0<<8;
]; \Try
proc PlayGame; \Play one game
[ChOut(0, $0C\FF\); \clear screen with a form feed
HLine(X0-1, Y0+1); \draw grid (#)
HLine(X0-1, Y0+3);
VLine(X0+2, Y0);
VLine(X0+6, Y0);
X:= 0; O:= 0; \initialize player's bit arrays to empty
loop [loop [PMove:= ChIn(1); \GET PLAYER'S MOVE (X)
if PMove = $1B\Esc\ then
[SetVid(3); exit]; \restore display and end program
if PMove = ^0 then quit;
if PMove>=^1 & PMove<=^9 & \check for legal move
((X!O) & 1<<(PMove-^1)) = 0 then quit;
ChOut(0, 7\Bel\); \beep the dude
];
if PMove # ^0 then
[DoMove(addr X, PMove-^1, ^X);
if Won(X) then
[Cursor(17, 20);
Text(0, "X wins!");
quit;
];
];
if Cats then quit;
I0:= Try(addr O) >>8; \GET COMPUTER'S MOVE (O)
DoMove(addr O, I0, ^O); \do best move
if Won(O) then
[Cursor(17, 20);
Text(0, "O wins!");
quit;
];
if Cats then quit;
];
]; \PlayGame
int CpuReg;
[SetVid(1); \set 40x25 text mode
CpuReg:= GetReg; \turn off annoying flashing cursor
CpuReg(0):= $0100; \ with BIOS interrupt 10h, function 01h
CpuReg(2):= $2000; \set cursor type to disappear
SoftInt($10);
loop [PlayGame;
Key:= ChIn(1); \keep playing games until Esc key is hit
if Key = $1B\Esc\ then
[SetVid(3); exit]; \clear screen & restore normal text mode
];
] |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #LOLCODE | LOLCODE | HAI 1.2
HOW IZ I HANOI YR N AN YR SRC AN YR DST AN YR VIA
BTW VISIBLE SMOOSH "HANOI N=" N " SRC=" SRC " DST=" DST " VIA=" VIA MKAY
BOTH SAEM N AN 0, O RLY?
YA RLY
BTW VISIBLE "Done."
GTFO
NO WAI
I HAS A LOWER ITZ DIFF OF N AN 1
I IZ HANOI YR LOWER AN YR SRC AN YR VIA AN YR DST MKAY
VISIBLE SMOOSH "Move disc " N " from " SRC " to " DST MKAY
I IZ HANOI YR LOWER AN YR VIA AN YR DST AN YR SRC MKAY
OIC
IF U SAY SO
I IZ HANOI YR 4 AN YR 1 AN YR 2 AN YR 3 MKAY
KTHXBYE
|
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.
| #VBA | VBA | Public Sub trig()
Pi = WorksheetFunction.Pi()
Debug.Print Sin(Pi / 2)
Debug.Print Sin(90 * Pi / 180)
Debug.Print Cos(0)
Debug.Print Cos(0 * Pi / 180)
Debug.Print Tan(Pi / 4)
Debug.Print Tan(45 * Pi / 180)
Debug.Print WorksheetFunction.Asin(1) * 2
Debug.Print WorksheetFunction.Asin(1) * 180 / Pi
Debug.Print WorksheetFunction.Acos(0) * 2
Debug.Print WorksheetFunction.Acos(0) * 180 / Pi
Debug.Print Atn(1) * 4
Debug.Print Atn(1) * 180 / Pi
End Sub |
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.
| #Smalltalk | Smalltalk | "Protocol: visiting"
EmptyNode>>accept: aVisitor
EmptyNode>>accept: aVisitor with: anObject
^anObject
"Protocol: enumerating"
EmptyNode>>traverse: aVisitorClass do: aBlock
^self accept: (aVisitorClass block: aBlock)
|
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
| #Scala | Scala | println("Hello,How,Are,You,Today" split "," mkString ".") |
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
| #Scheme | Scheme | (use-modules (ice-9 regex))
(define s "Hello,How,Are,You,Today")
(define words (map match:substring (list-matches "[^,]+" s)))
(do ((n 0 (+ n 1))) ((= n (length words)))
(display (list-ref words n))
(if (< n (- (length words) 1))
(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
| #Tcl | Tcl | package require Tcl 8.5
set text {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}
set data [dict create]
foreach line [split $text \n] {
lassign [split $line ,] name id salary dept
dict lappend data $dept [list $name $id $salary]
}
proc top_n_salaries {n data} {
incr n -1
dict for {dept employees} $data {
puts "Department $dept"
foreach emp [lrange [lsort -integer -decreasing -index 2 $employees] 0 $n] {
puts [format " %-20s %-8s %8d" {*}$emp]
}
puts ""
}
}
top_n_salaries 3 $data |
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.
| #Yabasic | Yabasic | 5 REM Adaptation to Yabasic of the program published in Tim Hartnell's book "Artificial Intelligence: Concepts and Programs", with some minor modifications. 6/2018.
10 REM TICTAC
15 INPUT "English (0), Spanish (other key): " IDIOMA : IF NOT IDIOMA THEN RESTORE 2020 ELSE RESTORE 2010 END IF
20 GOSUB 1180: REM INICIALIZACION
30 REM *** REQUISITOS PREVIOS AL JUEGO ***
40 FOR J = 1 TO 9
50 A(J) = 32
60 NEXT J
70 FOR J = 1 TO 5
80 D(J) = 0
90 NEXT J
100 CCONTADOR = 0
110 R$ = ""
120 GOSUB 1070: REM IMPRESION DEL TABLERO
130 REM ** CICLO PRINCIPAL **
140 GOSUB 540: REM MOVIMIENTO DEL ORDENADOR
150 GOSUB 1070: REM IMPRESION DEL TABLERO
160 GOSUB 870: REM COMPRUEBA LA VICTORIA
170 IF R$ <> "" GOTO 240
180 GOSUB 980: REM SE ACEPTA EL MOVIMIENTO DE LA PERSONA
190 GOSUB 1070: REM IMPRESION DEL TABLERO
200 GOSUB 870: REM COMPRUEBA LA VICTORIA
210 IF R$ = "" GOTO 140
220 REM ** FIN DEL CICLO PRINCIPAL **
230 REM *****************************
240 REM FIN DEL JUEGO
250 GOSUB 1070: REM IMPRESION DEL TABLERO
260 PRINT: PRINT
270 IF R$ = "G" PRINT MENSAJE$(1): BANDERA = -1
280 IF R$ = "P" PRINT MENSAJE$(2): BANDERA = 1
290 IF R$ = "D" PRINT MENSAJE$(3): GOTO 430
300 REM ACTUALIZACION DE LA BASE DE DATOS
310 FOR B = 1 TO 5
320 FOR J = 2 TO 9
330 IF M(J) = D(B) GOSUB 370
340 NEXT J
350 NEXT B
360 GOTO 430
370 REM ** REORDENACION DE LOS ELEMENTOS DE LA MATRIZ M **
380 TEMP = M(J + BANDERA)
390 M(J + BANDERA) = M(J)
400 M(J) = TEMP
410 J = 9
420 RETURN
430 PRINT: PRINT
440 PRINT MENSAJE$(4)
450 PRINT: PRINT
460 FOR J = 1 TO 9
470 PRINT M(J), " ";
480 NEXT J
490 PRINT: PRINT
500 PRINT MENSAJE$(5)
510 INPUT A$
520 GOTO 30
530 REM ************************
540 REM MOVIMIENTO DEL ORDENADOR
550 P = ASC("O")
560 X = 0
570 J = 1
580 IF A(W(J)) = A(W(J + 1)) AND A(W(J + 2)) = 32 AND A(W(J)) = P X = W(J + 2): GOTO 750
590 IF A(W(J)) = A(W(J + 2)) AND A(W(J + 1)) = 32 AND A(W(J)) = P X = W(J + 1): GOTO 750
600 IF A(W(J + 1)) = A(W(J + 2)) AND A(W(J)) = 32 AND A(W(J + 1)) = P X = W(J): GOTO 750
610 IF J < 21 J = J + 3: GOTO 580
620 IF P = ASC("O") P = ASC("X"): GOTO 570
630 REM ** SI NO SE GANA SE BUSCA UN MOVIMIENTO DE BLOQUEO **
640 REM * ENTONCES SE USA LA SIGUIENTE SECCION *
650 J = 1
660 IF A(M(J)) = 32 X = M(J): GOTO 750
670 IF J < 10 J = J + 1: GOTO 660
680 H = 0
690 H = H + 1
700 X = INT(RAN(1) * 9): IF A(X) = 32 GOTO 750
710 IF H < 100 GOTO 690
720 R$ = "D": REM ES SIMPLEMENTE UN DIBUJO
730 RETURN
740 REM *********************
750 REM REALIZA EL MOVIMIENTO
760 A(X) = ASC("O")
770 CCONTADOR = CCONTADOR + 1
780 D(CCONTADOR) = X
790 BANDERA = 0
800 FOR J = 1 TO 9
810 IF A(J) = 32 BANDERA = 1
820 NEXT J
830 IF BANDERA = 0 AND R$ = "" R$ = "D"
840 REM SI TODAS LAS CASILLAS ESTAN LLENAS Y R$ ESTA VACIO, ENTONCES ES SIMPLEMENTE UN DIBUJO
850 RETURN
860 REM *********************
870 REM COMPRUEBA LA VICTORIA
880 J = 1
890 IF A(W(J)) = 32 J = J + 3
900 IF J > 23 RETURN
910 IF A(W(J)) = A(W(J + 1)) AND A(W(J)) = A(W(J + 2)) GOTO 940
920 IF J < 22 J = J + 3: GOTO 890
930 RETURN
940 IF A(W(J)) = ASC("O") R$ = "G": REM EL ORDENADOR GANA
950 IF A(W(J)) = ASC("X") R$ = "P": REM EL ORDENADOR PIERDE
960 RETURN
970 REM ************************
980 REM MOVIMIENTO DE LA PERSONA
990 PRINT: PRINT
1000 PRINT MENSAJE$(6)
1010 PRINT MENSAJE$(7); : INPUT MOVIMIENTO
1020 IF MOVIMIENTO < 1 OR MOVIMIENTO > 9 GOTO 1010
1030 IF A(MOVIMIENTO) <> 32 GOTO 1010
1040 A(MOVIMIENTO) = ASC("X")
1050 RETURN
1060 REM *********************
1070 REM IMPRESION DEL TABLERO
1080 CLEAR SCREEN
1090 PRINT: PRINT: PRINT
1100 PRINT " 1 : 2 : 3 ", CHR$(A(1)), " : ", CHR$(A(2)), " : ", CHR$(A(3))
1110 PRINT "----------- ------------"
1120 PRINT " 4 : 5 : 6 ", CHR$(A(4)), " : ", CHR$(A(5)), " : ", CHR$(A(6))
1130 PRINT "----------- ------------"
1140 PRINT " 7 : 8 : 9 ", CHR$(A(7)), " : ", CHR$(A(8)), " : ", CHR$(A(9))
1150 PRINT
1160 RETURN
1170 REM **************
1180 REM INICIALIZACION
1190 CLEAR SCREEN
1200 DIM A(9) : REM TABLERO
1210 DIM M(10) : REM ACCESO A LA BASE DE DATOS
1220 DIM W(24) : REM DATOS DE VICTORIA O BLOQUEO
1230 DIM D(5) : REM ACCESO AL MOVIMIENTO EN EL JUEGO ACTUAL
1235 DIM MENSAJE$(1) : READ M$ : N = TOKEN(M$,MENSAJE$(),",") : RESTORE
1240 REM DATOS DE VICTORIA O BLOQUEO
1250 FOR J = 1 TO 24
1260 READ W(J)
1270 NEXT J
1280 DATA 1, 2, 3, 4, 5, 6, 7, 8, 9
1290 DATA 1, 4, 7, 2, 5, 8, 3, 6, 9
1300 DATA 1, 5, 9, 3, 5, 7
1310 REM BASE INICIAL DE DATOS
1320 FOR J = 1 TO 10
1330 READ M(J)
1340 NEXT J
1350 DATA 2, 6, 8, 4, 7, 3, 1, 9, 5, 2
1360 RETURN
2000 REM MENSAJES EN ESPAÑOL
2010 DATA "YO GANO,TU GANAS,ES SIMPLEMENTE UN DIBUJO,ESTA ES MI PRIORIDAD ACTUALIZADA,PULSE LA TECLA <RETURN> PARA CONTINUAR,REALICE SU MOVIMIENTO,MOVIMIENTO: "
2020 DATA "I WIN,YOU WIN,IT'S JUST A DRAWING,THIS IS MY PRIORITY UPDATE,PRESS <RETURN> TO CONTINUE,TO MAKE YOUR MOVE,MOVEMENT: "
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Lua | Lua | function move(n, src, dst, via)
if n > 0 then
move(n - 1, src, via, dst)
print(src, 'to', dst)
move(n - 1, via, dst, src)
end
end
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.
| #Visual_Basic_.NET | Visual Basic .NET | Module Module1
Sub Main()
Console.WriteLine("=== radians ===")
Console.WriteLine(" sin (pi/3) = {0}", Math.Sin(Math.PI / 3))
Console.WriteLine(" cos (pi/3) = {0}", Math.Cos(Math.PI / 3))
Console.WriteLine(" tan (pi/3) = {0}", Math.Tan(Math.PI / 3))
Console.WriteLine("arcsin (1/2) = {0}", Math.Asin(0.5))
Console.WriteLine("arccos (1/2) = {0}", Math.Acos(0.5))
Console.WriteLine("arctan (1/2) = {0}", Math.Atan(0.5))
Console.WriteLine()
Console.WriteLine("=== degrees ===")
Console.WriteLine(" sin (60) = {0}", Math.Sin(60 * Math.PI / 180))
Console.WriteLine(" cos (60) = {0}", Math.Cos(60 * Math.PI / 180))
Console.WriteLine(" tan (60) = {0}", Math.Tan(60 * Math.PI / 180))
Console.WriteLine("arcsin (1/2) = {0}", Math.Asin(0.5) * 180 / Math.PI)
Console.WriteLine("arccos (1/2) = {0}", Math.Acos(0.5) * 180 / Math.PI)
Console.WriteLine("arctan (1/2) = {0}", Math.Atan(0.5) * 180 / Math.PI)
End Sub
End Module |
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.
| #Swift | Swift | class TreeNode<T> {
let value: T
let left: TreeNode?
let right: TreeNode?
init(value: T, left: TreeNode? = nil, right: TreeNode? = nil) {
self.value = value
self.left = left
self.right = right
}
func preOrder(function: (T) -> Void) {
function(value)
if left != nil {
left!.preOrder(function: function)
}
if right != nil {
right!.preOrder(function: function)
}
}
func inOrder(function: (T) -> Void) {
if left != nil {
left!.inOrder(function: function)
}
function(value)
if right != nil {
right!.inOrder(function: function)
}
}
func postOrder(function: (T) -> Void) {
if left != nil {
left!.postOrder(function: function)
}
if right != nil {
right!.postOrder(function: function)
}
function(value)
}
func levelOrder(function: (T) -> Void) {
var queue: [TreeNode] = []
queue.append(self)
while queue.count > 0 {
let node = queue.removeFirst()
function(node.value)
if node.left != nil {
queue.append(node.left!)
}
if node.right != nil {
queue.append(node.right!)
}
}
}
}
typealias Node = TreeNode<Int>
let n = Node(value: 1,
left: Node(value: 2,
left: Node(value: 4,
left: Node(value: 7)),
right: Node(value: 5)),
right: Node(value: 3,
left: Node(value: 6,
left: Node(value: 8),
right: Node(value: 9))))
let fn = { print($0, terminator: " ") }
print("pre-order: ", terminator: "")
n.preOrder(function: fn)
print()
print("in-order: ", terminator: "")
n.inOrder(function: fn)
print()
print("post-order: ", terminator: "")
n.postOrder(function: fn)
print()
print("level-order: ", terminator: "")
n.levelOrder(function: fn)
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
| #Seed7 | Seed7 | var array string: tokens is 0 times "";
tokens := 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
| #Self | Self | | s = 'Hello,How,Are,You,Today' |
((s splitOn: ',') joinUsing: '.') printLine.
|
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
| #Transd | Transd | #lang transd
MainModule: {
tbl : String(
`EmployeeName,EmployeeID,Salary:Int,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`),
N: 2,
_start: (λ
(with tabl Table()
(load-table tabl tbl)
(build-index tabl "Department")
(with rows (tsd-query tabl
select: ["Department"]
as: [[String()]] :distinct sortby: "Department" )
(for row in rows do
(with recs (tsd-query tabl
select: all
as: [[String(), String(), Int(), String()]]
satisfying: (lambda Department String()
(eq Department (get row 0)))
sortby: "Salary" :desc
limit: N)
(for rec in recs do (textout rec "\n")))))))
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #M2000_Interpreter | M2000 Interpreter |
Module Hanoi {
Rem HANOI TOWERS
Print "Three disks" : Print
move(3, 1, 2, 3)
Print
Print "Four disks" : Print
move(4, 1, 2, 3)
Sub move(n, from, to, via)
If n <=0 Then Exit Sub
move(n - 1, from, via, to)
Print "Move disk"; n; " from pole"; from; " to pole"; to
move(n - 1, via, to, from)
End Sub
}
Hanoi
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #MAD | MAD | NORMAL MODE IS INTEGER
DIMENSION LIST(100)
SET LIST TO LIST
VECTOR VALUES MOVFMT =
0 $20HMOVE DISK FROM POLE ,I1,S1,8HTO POLE ,I1*$
INTERNAL FUNCTION(DUMMY)
ENTRY TO MOVE.
LOOP NUM = NUM - 1
WHENEVER NUM.E.0
PRINT FORMAT MOVFMT,FROM,DEST
OTHERWISE
SAVE RETURN
SAVE DATA NUM,FROM,VIA,DEST
TEMP=DEST
DEST=VIA
VIA=TEMP
MOVE.(0)
RESTORE DATA NUM,FROM,VIA,DEST
RESTORE RETURN
PRINT FORMAT MOVFMT,FROM,DEST
TEMP=FROM
FROM=VIA
VIA=TEMP
TRANSFER TO LOOP
END OF CONDITIONAL
FUNCTION RETURN
END OF FUNCTION
NUM = 4
FROM = 1
VIA = 2
DEST = 3
MOVE.(0)
END OF PROGRAM
|
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.
| #Wren | Wren | import "/fmt" for Fmt
var d = 30
var r = d * Num.pi / 180
var s = 0.5
var c = 3.sqrt / 2
var t = 1 / 3.sqrt
Fmt.print("sin($9.6f deg) = $f", d, (d*Num.pi/180).sin)
Fmt.print("sin($9.6f rad) = $f", r, r.sin)
Fmt.print("cos($9.6f deg) = $f", d, (d*Num.pi/180).cos)
Fmt.print("cos($9.6f rad) = $f", r, r.cos)
Fmt.print("tan($9.6f deg) = $f", d, (d*Num.pi/180).tan)
Fmt.print("tan($9.6f rad) = $f", r, r.tan)
Fmt.print("asin($f) = $9.6f deg", s, s.asin*180/Num.pi)
Fmt.print("asin($f) = $9.6f rad", s, s.asin)
Fmt.print("acos($f) = $9.6f deg", c, c.acos*180/Num.pi)
Fmt.print("acos($f) = $9.6f rad", c, c.acos)
Fmt.print("atan($f) = $9.6f deg", t, t.atan*180/Num.pi)
Fmt.print("atan($f) = $9.6f rad", t, t.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.
| #Tcl | Tcl | oo::class create tree {
# Basic tree data structure stuff...
variable val l r
constructor {value {left {}} {right {}}} {
set val $value
set l $left
set r $right
}
method value {} {return $val}
method left {} {return $l}
method right {} {return $r}
destructor {
if {$l ne ""} {$l destroy}
if {$r ne ""} {$r destroy}
}
# Traversal methods
method preorder {varName script {level 0}} {
upvar [incr level] $varName var
set var $val
uplevel $level $script
if {$l ne ""} {$l preorder $varName $script $level}
if {$r ne ""} {$r preorder $varName $script $level}
}
method inorder {varName script {level 0}} {
upvar [incr level] $varName var
if {$l ne ""} {$l inorder $varName $script $level}
set var $val
uplevel $level $script
if {$r ne ""} {$r inorder $varName $script $level}
}
method postorder {varName script {level 0}} {
upvar [incr level] $varName var
if {$l ne ""} {$l postorder $varName $script $level}
if {$r ne ""} {$r postorder $varName $script $level}
set var $val
uplevel $level $script
}
method levelorder {varName script} {
upvar 1 $varName var
set nodes [list [self]]; # A queue of nodes to process
while {[llength $nodes] > 0} {
set nodes [lassign $nodes n]
set var [$n value]
uplevel 1 $script
if {[$n left] ne ""} {lappend nodes [$n left]}
if {[$n right] ne ""} {lappend nodes [$n right]}
}
}
} |
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
| #Sidef | Sidef | 'Hello,How,Are,You,Today'.split(',').join('.').say; |
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
| #Simula | Simula | BEGIN
CLASS TEXTARRAY(N); INTEGER N;
BEGIN
TEXT ARRAY ARR(1:N);
END TEXTARRAY;
REF(TEXTARRAY) PROCEDURE SPLIT(T,DELIM); TEXT T; CHARACTER DELIM;
BEGIN
INTEGER N, I, LPOS;
REF(TEXTARRAY) A;
N := 1;
T.SETPOS(1);
WHILE T.MORE DO
IF T.GETCHAR = DELIM THEN
N := N+1;
A :- NEW TEXTARRAY(N);
I := 0;
LPOS := 1;
T.SETPOS(LPOS);
WHILE T.MORE DO
IF T.GETCHAR = DELIM THEN
BEGIN
I := I+1;
A.ARR(I) :- T.SUB(LPOS,T.POS-LPOS-1);
LPOS := T.POS;
END;
I := I+1;
A.ARR(I) :- T.SUB(LPOS,T.LENGTH-LPOS+1);
SPLIT :- A;
END SPLIT;
BEGIN
TEXT S;
REF(TEXTARRAY) TA;
INTEGER I;
S :- "HELLO,HOW,ARE,YOU,TODAY";
TA :- SPLIT(S,',');
FOR I := 1 STEP 1 UNTIL TA.N DO
BEGIN
OUTTEXT(TA.ARR(I));
OUTCHAR('.');
END;
OUTIMAGE;
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
| #TUSCRIPT | TUSCRIPT | $$ MODE TUSCRIPT
MODE DATA
$$ SET dates=*
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
$$ MODE TUSCRIPT
SET nix=SPLIT (dates,":,:",EmployeeName,Employee_ID,Salary,Department)
SET d=MIXED_SORT (department),d=REDUCE(d)
SET index=DIGIT_INDEX(salary), index=REVERSE(index)
SET employeeName=INDEX_SORT (employeeName,index)
SET employee_ID =INDEX_SORT (employee_ID,index)
SET Salary=INDEX_SORT (salary,index)
SET Department=INDEX_SORT (Department,index)
COMPILE
LOOP l=d
PRINT "Department ", l
SET rtable=QUOTES (l)
BUILD R_TABLE pos = rtable
SET id=FILTER_INDEX (department,pos,-)
RELEASE R_TABLE pos
SET en =SELECT (employeeName,#id)
SET ei =SELECT (employee_ID,#id)
SET sal =SELECT (salary,#id)
SET he =CENTER ("employeeName",-16)
SET hi =CENTER ("employee ID",-11)
SET hs =CENTER ("Salary",+10)
SET line=REPEAT ("-",37)
PRINT he,hi,hs
PRINT line
LOOP e=en,i=ei,s=sal
SET e=CENTER (e,-16), i=CENTER (i,-11), s=CENTER (s,+10)
PRINT e,i,s
ENDLOOP
PRINT " "
ENDLOOP
ENDCOMPILE |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Maple | Maple |
Hanoi := proc(n::posint,a,b,c)
if n = 1 then
printf("Move disk from tower %a to tower %a.\n",a,c);
else
Hanoi(n-1,a,c,b);
Hanoi(1,a,b,c);
Hanoi(n-1,b,a,c);
fi;
end:
printf("Moving 2 disks from tower A to tower C using tower B.\n");
Hanoi(2,A,B,C);
|
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Mathematica.2FWolfram_Language | Mathematica/Wolfram Language | Hanoi[0, from_, to_, via_] := Null
Hanoi[n_Integer, from_, to_, via_] := (Hanoi[n-1, from, via, to];Print["Move disk from pole ", from, " to ", to, "."];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.
| #XPL0 | XPL0 | include c:\cxpl\codes; \intrinsic 'code' declarations
def Pi = 3.14159265358979323846;
func real ATan(Y); \Arc tangent
real Y;
return ATan2(Y, 1.0);
func real Deg(X); \Convert radians to degrees
real X;
return 57.2957795130823 * X;
func real Rad(X); \Convert degrees to radians
real X;
return X / 57.2957795130823;
real A, B, C;
[A:= Sin(Pi/6.0);
RlOut(0, A); ChOut(0, 9\tab\); RlOut(0, Sin(Rad(30.0))); CrLf(0);
B:= Cos(Pi/6.0);
RlOut(0, B); ChOut(0, 9\tab\); RlOut(0, Cos(Rad(30.0))); CrLf(0);
C:= Tan(Pi/4.0);
RlOut(0, C); ChOut(0, 9\tab\); RlOut(0, Tan(Rad(45.0))); CrLf(0);
RlOut(0, ASin(A)); ChOut(0, 9\tab\); RlOut(0, Deg(ASin(A))); CrLf(0);
RlOut(0, ACos(B)); ChOut(0, 9\tab\); RlOut(0, Deg(ACos(B))); CrLf(0);
RlOut(0, ATan(C)); ChOut(0, 9\tab\); RlOut(0, Deg(ATan(C))); CrLf(0);
] |
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.
| #zkl | zkl |
(30.0).toRad().sin() //-->0.5
(60.0).toRad().cos() //-->0.5
(45.0).toRad().tan() //-->1
(0.523599).sin() //-->0.5
etc
(0.5).asin() //-->0.523599
(0.5).acos() //-->1.0472
(1.0).atan() //-->0.785398
(1.0).atan().toDeg() //-->45
etc |
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.
| #UNIX_Shell | UNIX Shell | left=()
right=()
value=()
# node node#, left#, right#, value
#
# if value is empty, use node#
node() {
nx=${1:-'Missing node index'}
leftx=${2}
rightx=${3}
val=${4:-$1}
value[$nx]="$val"
left[$nx]="$leftx"
right[$nx]="$rightx"
}
# define the tree
node 1 2 3
node 2 4 5
node 3 6
node 4 7
node 5
node 6 8 9
node 7
node 8
node 9
# walk NODE# ORDER
walk() {
local nx=${1-"Missing index"}
shift
for branch in "$@" ; do
case "$branch" in
left) if [[ "${left[$nx]}" ]]; then walk ${left[$nx]} $@ ; fi ;;
right) if [[ "${right[$nx]}" ]]; then walk ${right[$nx]} $@ ; fi ;;
self) printf "%d " "${value[$nx]}" ;;
esac
done
}
apush() {
local var="$1"
eval "$var=( \"\${$var[@]}\" \"$2\" )"
}
showname() {
printf "%-12s " "$1:"
}
showdata() {
showname "$1"
shift
walk "$@"
echo ''
}
preorder() { showdata $FUNCNAME $1 self left right ; }
inorder() { showdata $FUNCNAME $1 left self right ; }
postorder() { showdata $FUNCNAME $1 left right self ; }
levelorder() {
showname 'level-order'
queue=( $1 )
x=0
while [[ $x < ${#queue[*]} ]]; do
value="${queue[$x]}"
printf "%d " "$value"
for more in "${left[$value]}" "${right[$value]}" ; do
if [[ -n "$more" ]]; then
apush queue "$more"
fi
done
: $((x++))
done
echo ''
}
preorder 1
inorder 1
postorder 1
levelorder 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
| #Slate | Slate | ('Hello,How,Are,You,Today' splitWith: $,) join &separator: '.'. |
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
| #Smalltalk | Smalltalk | |array |
array := 'Hello,How,Are,You,Today' subStrings: $,.
array fold: [:concatenation :string | concatenation, '.', string ] |
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
| #TXR | TXR | @(next :args)
@{n-param}
@(next "top-rank-per-group.dat")
Employee Name,Employee ID,Salary,Department
@(collect :vars (record))
@name,@id,@salary,@dept
@(bind record (@(int-str salary) dept name id))
@(end)
@(bind (dept salary dept2 name id)
@(let* ((n (int-str n-param))
(dept-hash [group-by second record :equal-based])
(dept (hash-keys dept-hash))
(ranked (collect-each ((rec (hash-values dept-hash)))
[apply mapcar list [[sort rec > first] 0..n]])))
(cons dept [apply mapcar list ranked])))
@(output)
@ (repeat)
Department: @dept
@ (repeat)
@{name 15} (@id) $@{salary -6}
@ (end)
@ (end)
@(end) |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #MATLAB | MATLAB | function towerOfHanoi(n,A,C,B)
if (n~=0)
towerOfHanoi(n-1,A,B,C);
disp(sprintf('Move plate %d from tower %d to tower %d',[n A C]));
towerOfHanoi(n-1,B,C,A);
end
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.
| #ZX_Spectrum_Basic | ZX Spectrum Basic | 10 DEF FN d(a)=a*PI/180:REM convert degrees to radians; all ZX Spectrum trig calculations are done in radians
20 DEF FN i(r)=180*r/PI:REM convert radians to degrees for inverse functions
30 LET d=45
40 LET r=PI/4
50 PRINT SIN r,SIN FN d(d)
60 PRINT COS r,COS FN d(d)
70 PRINT TAN r,TAN FN d(d)
80 PRINT
90 LET d=.5
110 PRINT ASN d,FN i(ASN d)
120 PRINT ACS d,FN i(ACS d)
130 PRINT ATN d,FN i(ATN d) |
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.
| #Ursala | Ursala | tree =
1^:<
2^: <4^: <7^: <>, 0>, 5^: <>>,
3^: <6^: <8^: <>, 9^: <>>, 0>>
pre = ~&dvLPCo
post = ~&vLPdNCTo
in = ~&vvhPdvtL2CTiQo
lev = ~&iNCaadSPfavSLiF3RTaq
#cast %nLL
main = <.pre,in,post,lev> 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
| #SNOBOL4 | SNOBOL4 | define('split(chs,str)i,j,t,w2') :(split_end)
split t = table()
sp1 str pos(0) (break(chs) | rem) $ t<i = i + 1>
+ span(chs) (break(chs) | '') . w2 = w2 :s(sp1)
* t<i> = differ(str,'') str ;* Uncomment for CSnobol
split = array(i)
sp2 split<j = j + 1> = t<j> :s(sp2)f(return)
split_end
define('join(ch,a)i,') :(join_end)
join join = join a<i = i + 1>
join = join ?a<i + 1> ch :s(join)f(return)
join_end
* # Test and display
output = join('.',split(',','Hello,How,Are,You,Today'))
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
| #Standard_ML | Standard ML | val splitter = String.tokens (fn c => c = #",");
val main = (String.concatWith ".") o splitter; |
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
| #Ursala | Ursala | #import std
#import nat
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]-
top "n" = @tt sep`,*; mat0+ ^C(~&hz,mat`,*yS)*+ take/*"n"+ *zK2 (nleq+ %np~~)-<x&yzNC
#show+
main = top3 data |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #MiniScript | MiniScript | moveDisc = function(n, A, C, B)
if n == 0 then return
moveDisc n-1, A, B, C
print "Move disc " + n + " from pole " + A + " to pole " + C
moveDisc n-1, B, C, A
end function
// Move disc 3 from pole 1 to pole 3, with pole 2 as spare
moveDisc 3, 1, 3, 2 |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #MIPS_Assembly | MIPS Assembly |
# Towers of Hanoi
# MIPS assembly implementation (tested with MARS)
# Source: https://stackoverflow.com/questions/50382420/hanoi-towers-recursive-solution-using-mips/50383530#50383530
.data
prompt: .asciiz "Enter a number: "
part1: .asciiz "\nMove disk "
part2: .asciiz " from rod "
part3: .asciiz " to rod "
.text
.globl main
main:
li $v0, 4 # print string
la $a0, prompt
syscall
li $v0, 5 # read integer
syscall
# parameters for the routine
add $a0, $v0, $zero # move to $a0
li $a1, 'A'
li $a2, 'B'
li $a3, 'C'
jal hanoi # call hanoi routine
li $v0, 10 # exit
syscall
hanoi:
#save in stack
addi $sp, $sp, -20
sw $ra, 0($sp)
sw $s0, 4($sp)
sw $s1, 8($sp)
sw $s2, 12($sp)
sw $s3, 16($sp)
add $s0, $a0, $zero
add $s1, $a1, $zero
add $s2, $a2, $zero
add $s3, $a3, $zero
addi $t1, $zero, 1
beq $s0, $t1, output
recur1:
addi $a0, $s0, -1
add $a1, $s1, $zero
add $a2, $s3, $zero
add $a3, $s2, $zero
jal hanoi
j output
recur2:
addi $a0, $s0, -1
add $a1, $s3, $zero
add $a2, $s2, $zero
add $a3, $s1, $zero
jal hanoi
exithanoi:
lw $ra, 0($sp) # restore registers from stack
lw $s0, 4($sp)
lw $s1, 8($sp)
lw $s2, 12($sp)
lw $s3, 16($sp)
addi $sp, $sp, 20 # restore stack pointer
jr $ra
output:
li $v0, 4 # print string
la $a0, part1
syscall
li $v0, 1 # print integer
add $a0, $s0, $zero
syscall
li $v0, 4 # print string
la $a0, part2
syscall
li $v0, 11 # print character
add $a0, $s1, $zero
syscall
li $v0, 4 # print string
la $a0, part3
syscall
li $v0, 11 # print character
add $a0, $s2, $zero
syscall
beq $s0, $t1, exithanoi
j recur2
|
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.
| #VBA | VBA |
Public Value As Integer
Public LeftChild As TreeItem
Public RightChild As TreeItem
|
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
| #Swift | Swift | let text = "Hello,How,Are,You,Today"
let tokens = text.components(separatedBy: ",") // for single or multi-character separator
print(tokens)
let result = tokens.joined(separator: ".")
print(result) |
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
| #Tcl | Tcl | split $string "," |
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
| #VBA | VBA | Private Sub top_rank(filename As String, n As Integer)
Workbooks.OpenText filename:=filename, Comma:=True
Dim ws As Worksheet
Set ws = Sheets.Add: ws.Name = "output"
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"data!R1C1:R14C4", Version:=6).CreatePivotTable TableDestination:= _
"output!R3C1", TableName:="TableName", DefaultVersion:=6
With Sheets("output").PivotTables("TableName")
.InGridDropZones = True
.RowAxisLayout xlTabularRow
.AddDataField Sheets("output").PivotTables("TableName"). _
PivotFields("Salary"), "Top rank", xlSum
.PivotFields("Department").Orientation = xlRowField
.PivotFields("Department").Position = 1
.PivotFields("Salary").Orientation = xlRowField
.PivotFields("Salary").Position = 2
.PivotFields("Employee Name").Orientation = xlRowField
.PivotFields("Employee Name").Position = 3
.PivotFields("Employee ID").Orientation = xlRowField
.PivotFields("Employee ID").Position = 4
.PivotFields("Salary").PivotFilters.Add2 Type:=xlTopCount, _
DataField:=Sheets("output").PivotTables("TableName"). _
PivotFields("Top rank"), Value1:=n
.PivotFields("Salary").Subtotals = Array(False, False, False, False, _
False, False, False, False, False, False, False, False)
.PivotFields("Employee Name").Subtotals = Array(False, False, False, _
False, False, False, False, False, False, False, False, False)
.PivotFields("Department").Subtotals = Array(False, False, False, False, _
False, False, False, False, False, False, False, False)
.ColumnGrand = False
.PivotFields("Salary").AutoSort xlDescending, "Salary"
End With
End Sub
Public Sub main()
top_rank filename:="D:\data.txt", n:=3
End Sub |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #.D0.9C.D0.9A-61.2F52 | МК-61/52 | ^ 2 x^y П0 <-> 2 / {x} x#0 16
3 П3 2 П2 БП 20 3 П2 2 П3
1 П1 ПП 25 КППB ПП 28 КППA ПП 31
КППB ПП 34 КППA ИП1 ИП3 КППC ИП1 ИП2 КППC
ИП3 ИП2 КППC ИП1 ИП3 КППC ИП2 ИП1 КППC ИП2
ИП3 КППC ИП1 ИП3 КППC В/О ИП1 ИП2 БП 62
ИП2 ИП1 КППC ИП1 ИП2 ИП3 П1 -> П3 ->
П2 В/О 1 0 / + С/П КИП0 ИП0 x=0
89 3 3 1 ИНВ ^ ВП 2 С/П В/О |
http://rosettacode.org/wiki/Tree_traversal | Tree traversal | Task
Implement a binary tree where each node carries an integer, and implement:
pre-order,
in-order,
post-order, and
level-order traversal.
Use those traversals to output the following tree:
1
/ \
/ \
/ \
2 3
/ \ /
4 5 6
/ / \
7 8 9
The correct output should look like this:
preorder: 1 2 4 7 5 3 6 8 9
inorder: 7 4 2 5 1 8 6 9 3
postorder: 7 4 5 2 8 9 6 3 1
level-order: 1 2 3 4 5 6 7 8 9
See also
Wikipedia article: Tree traversal.
| #Wren | Wren | class Node {
construct new(v) {
_v = v
_left = null
_right = null
}
value { _v }
left { _left }
right { _right}
left =(n) { _left = n }
right= (n) { _right = n }
preOrder() {
System.write(this)
if (_left) _left.preOrder()
if (_right) _right.preOrder()
}
inOrder() {
if ( _left) _left.inOrder()
System.write(this)
if (_right) _right.inOrder()
}
postOrder() {
if (_left) _left.postOrder()
if (_right) _right.postOrder()
System.write(this)
}
levelOrder() {
var queue = [this]
while (true) {
var node = queue.removeAt(0)
System.write(node)
if (node.left) queue.add(node.left)
if (node.right) queue.add(node.right)
if (queue.isEmpty) break
}
}
exec(name, f) {
System.write(name)
f.call(this)
System.print()
}
toString { " %(_v)" }
}
var nodes = List.filled(10, null)
for (i in 0..9) nodes[i] = Node.new(i)
nodes[1].left = nodes[2]
nodes[1].right = nodes[3]
nodes[2].left = nodes[4]
nodes[2].right = nodes[5]
nodes[4].left = nodes[7]
nodes[3].left = nodes[6]
nodes[6].left = nodes[8]
nodes[6].right = nodes[9]
nodes[1].exec(" preOrder:", Fn.new { |n| n.preOrder() })
nodes[1].exec(" inOrder:", Fn.new { |n| n.inOrder() })
nodes[1].exec(" postOrder:", Fn.new { |n| n.postOrder() })
nodes[1].exec("level-order:", Fn.new { |n| n.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
| #tr | tr | echo 'Hello,How,Are,You,Today' | tr ',' '.' |
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
| #TUSCRIPT | TUSCRIPT |
$$ MODE TUSCRIPT
SET string="Hello,How,Are,You,Today"
SET string=SPLIT (string,":,:")
SET string=JOIN (string,".")
|
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
| #Wren | Wren | import "/dynamic" for Tuple
import "/sort" for Sort, Cmp
import "/seq" for Lst
import "/fmt" for Fmt
var Employee = Tuple.create("Employee", ["name", "id", "salary", "dept"])
var N = 2 // say
var employees = [
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")
]
var cmpByDept = Fn.new { |employee1, employee2| Cmp.string.call(employee1.dept, employee2.dept) }
Sort.insertion(employees, cmpByDept)
var groupsByDept = Lst.groups(employees) { |e| e.dept }
System.print("Highest %(N) salaries by department:\n")
for (group in groupsByDept) {
var dept = group[0]
var groupEmployees = group[1].map { |i| i[0] }.toList
var cmpBySalary = Fn.new { |employee1, employee2| Cmp.numDesc.call(employee1.salary, employee2.salary) }
Sort.insertion(groupEmployees, cmpBySalary)
var topRanked = groupEmployees.take(N)
System.print("Dept %(dept) => ")
topRanked.each { |e| Fmt.print("$-15s $s $d", e.name, e.id, e.salary) }
System.print()
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Modula-2 | Modula-2 | MODULE Towers;
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,ReadChar;
PROCEDURE Move(n,from,to,via : INTEGER);
VAR buf : ARRAY[0..63] OF CHAR;
BEGIN
IF n>0 THEN
Move(n-1, from, via, to);
FormatString("Move disk %i from pole %i to pole %i\n", buf, n, from, to);
WriteString(buf);
Move(n-1, via, to, from)
END
END Move;
BEGIN
Move(3, 1, 3, 2);
ReadChar
END Towers. |
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.
| #zkl | zkl | class Node{ var [mixin=Node]left,right; var v;
fcn init(val,[Node]l=Void,[Node]r=Void) { v,left,right=vm.arglist }
}
class BTree{ var [mixin=Node] root;
fcn init(r){ root=r }
const VISIT=Void, LEFT="left", RIGHT="right";
fcn preOrder { traverse(VISIT,LEFT, RIGHT) }
fcn inOrder { traverse(LEFT, VISIT,RIGHT) }
fcn postOrder { traverse(LEFT, RIGHT,VISIT) }
fcn [private] traverse(order){ //--> list of Nodes
sink:=List();
fcn(sink,[Node]n,order){
if(n){ foreach o in (order){
if(VISIT==o) sink.write(n);
else self.fcn(sink,n.setVar(o),order); // actually get var, eg n.left
}}
}(sink,root,vm.arglist);
sink
}
fcn levelOrder{ // breadth first
sink:=List(); q:=List(root);
while(q){
n:=q.pop(0); l:=n.left; r:=n.right;
sink.write(n);
if(l) q.append(l);
if(r) q.append(r);
}
sink
}
} |
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
| #TXR | TXR | @(next :list "Hello,How,Are,You,Today")
@(coll)@{token /[^,]+/}@(end)
@(output)
@(rep)@token.@(last)@token@(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
| #UNIX_Shell | UNIX Shell | string='Hello,How,Are,You,Today'
(IFS=,
printf '%s.' $string
echo) |
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
| #XPL0 | XPL0 | proc Sort(Array, Field, Size); \Sort Array in descending order by Field
int Array, Field, Size, I, J, T;
[for J:= Size-1 downto 0 do
for I:= 0 to J-1 do
if Array(I,Field) < Array(I+1,Field) then
[T:= Array(I); Array(I):= Array(I+1); Array(I+1):= T];
];
int Data, I, I0, Dept, N, Cnt;
[Data:=[["Tyler Bennett", "E10297", 32000, 101],
["John Rappl", "E21437", 47000, 050],
["George Woltman", "E00127", 53500, 101],
["Adam Smith", "E63535", 18000, 202],
["Claire Buckman", "E39876", 27800, 202],
["David McClellan", "E04242", 41500, 101],
["Rich Holcomb", "E01234", 49500, 202],
["Nathan Adams", "E41298", 21900, 050],
["Richard Potter", "E43128", 15900, 101],
["David Motsinger", "E27002", 19250, 202],
["Tim Sampair", "E03033", 27000, 101],
["Kim Arlich", "E10001", 57000, 190],
["Timothy Grove", "E16398", 29900, 190],
[0, 0, 0, 000]]; \sentinel
I:= 0; \find number of employees = Data size
while Data(I,0) # 0 do I:= I+1;
Sort(Data, 3, I); \sort by department field (3)
I:= 0; \sort by salary within each department
while Data(I,0) do
[Dept:= Data(I,3);
I0:= I;
repeat I:= I+1 until Data(I,3) # Dept;
Sort(@Data(I0), 2, I-I0);
];
N:= IntIn(0); \get parameter
I:= 0;
loop [Dept:= Data(I,3); \for each department
Text(0, "Department D");
if Dept < 100 then ChOut(0, ^0); IntOut(0, Dept); Text(0, ":^m^j");
Cnt:= 0;
loop [if Cnt >= N then
while Data(I,3) = Dept do I:= I+1; \skip any remaining
if Data(I,3) # Dept then quit;
IntOut(0, Data(I,2)); Text(0, " "); \salary
Text(0, Data(I,1)); Text(0, " "); \ID
Text(0, Data(I,0)); CrLf(0); \name
Cnt:= Cnt+1;
I:= I+1;
];
if Data(I,0) = 0 then quit;
];
] |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Modula-3 | Modula-3 | MODULE Hanoi EXPORTS Main;
FROM IO IMPORT Put;
FROM Fmt IMPORT Int;
PROCEDURE doHanoi(n, from, to, using: INTEGER) =
BEGIN
IF n > 0 THEN
doHanoi(n - 1, from, using, to);
Put("move " & Int(from) & " --> " & Int(to) & "\n");
doHanoi(n - 1, using, to, from);
END;
END doHanoi;
BEGIN
doHanoi(4, 1, 2, 3);
END Hanoi. |
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
| #UnixPipes | UnixPipes | token() {
(IFS=, read -r A B; echo "$A".; test -n "$B" && (echo "$B" | token))
}
echo "Hello,How,Are,You" | token |
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
| #Ursa | Ursa | decl string text
set text "Hello,How,Are,You,Today"
decl string<> tokens
set tokens (split text ",")
for (decl int i) (< i (size tokens)) (inc i)
out tokens<i> "." console
end for
out endl console |
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
| #zkl | zkl | fcn setAppend(d,[(key,data)]){ d[key]=d.find(key,T).append(data) } //-->(key,(data,data...))
fcn topNsalaries(n){
File("data.txt").pump(setAppend.fp(data:=D()),fcn(line){ //-->Dictionary(dept:salaries)
line=line.strip().split(",");
T(line[-1],line[-2]); //-->(dept,salary)
});
dss:=data.pump(List,fcn([(dept,ss)],N){ //-->(dept,(salaries), dept...)
T(dept).append(ss.sort()[-N,*].reverse());
}.fp1(n)).sort(fcn(a,b){a[0]<b[0]});
foreach d,ss in (dss){
"%s: %s".fmt(d,ss.concat(",")).println();
}
}(3); |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Monte | Monte | def move(n, fromPeg, toPeg, viaPeg):
if (n > 0):
move(n.previous(), fromPeg, viaPeg, toPeg)
traceln(`Move disk $n from $fromPeg to $toPeg`)
move(n.previous(), viaPeg, toPeg, fromPeg)
move(3, "left", "right", "middle") |
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
| #Ursala | Ursala | #import std
token_list = sep`, 'Hello,How,Are,You,Today'
#cast %s
main = mat`. token_list |
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
| #Vala | Vala | void main() {
string s = "Hello,How,Are,You,Today";
print(@"$(string.joinv(".", s.split(",")))");
} |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #MoonScript | MoonScript | hanoi = (n, src, dest, via) ->
if n > 1
hanoi n-1, src, via, dest
print "#{src} -> #{dest}"
if n > 1
hanoi n-1, via, dest, src
hanoi 4,1,3,2 |
http://rosettacode.org/wiki/Towers_of_Hanoi | Towers of Hanoi | Task
Solve the Towers of Hanoi problem with recursion.
| #Nemerle | Nemerle | using System;
using System.Console;
module Towers
{
Hanoi(n : int, from = 1, to = 3, via = 2) : void
{
when (n > 0)
{
Hanoi(n - 1, from, via, to);
WriteLine("Move disk from peg {0} to peg {1}", from, to);
Hanoi(n - 1, via, to, from);
}
}
Main() : void
{
Hanoi(4)
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.