code
stringlengths 1
46.1k
⌀ | label
class label 1.18k
classes | domain_label
class label 21
classes | index
stringlengths 4
5
|
---|---|---|---|
from math import gcd
def (n):
return sum(1 for k in range(1, n + 1) if gcd(n, k) == 1)
if __name__ == '__main__':
def is_prime(n):
return (n) == n - 1
for n in range(1, 26):
print(f)
count = 0
for n in range(1, 10_000 + 1):
count += is_prime(n)
if n in {100, 1000, 10_000}:
print(f) | 108Totient function
| 3python
| xpbwr |
def f(x) x.abs ** 0.5 + 5 * x ** 3 end
puts
nums = 11.times.map{ gets.to_f }
nums.reverse_each do |n|
print
res = f(n)
puts res > 400? : res
end | 106Trabb Pardo–Knuth algorithm
| 14ruby
| c369k |
sub tokenize {
my ($string, $sep, $esc) = (shift, quotemeta shift, quotemeta shift);
my @fields = split /$esc . (*SKIP)(*FAIL) | $sep/sx, $string, -1;
return map { s/$esc(.)/$1/gsr } @fields;
} | 112Tokenize a string with escaping
| 2perl
| mtoyz |
use std::io::{self, BufRead};
fn op(x: f32) -> Option<f32> {
let y = x.abs().sqrt() + 5.0 * x * x * x;
if y < 400.0 {
Some(y)
} else {
None
}
}
fn main() {
println!("Please enter 11 numbers (one number per line)");
let stdin = io::stdin();
let xs = stdin
.lock()
.lines()
.map(|ox| ox.unwrap().trim().to_string())
.flat_map(|s| str::parse::<f32>(&s))
.take(11)
.collect::<Vec<_>>();
for x in xs.into_iter().rev() {
match op(x) {
Some(y) => println!("{}", y),
None => println!("overflow"),
};
}
} | 106Trabb Pardo–Knuth algorithm
| 15rust
| l6ycc |
object TPKa extends App {
final val numbers = scala.collection.mutable.MutableList[Double]()
final val in = new java.util.Scanner(System.in)
while (numbers.length < CAPACITY) {
print("enter a number: ")
try {
numbers += in.nextDouble()
}
catch {
case _: Exception =>
in.next()
println("invalid input, try again")
}
}
numbers reverseMap { x =>
val fx = Math.pow(Math.abs(x), .5D) + 5D * (Math.pow(x, 3))
if (fx < THRESHOLD)
print("%8.3f ->%8.3f\n".format(x, fx))
else
print("%8.3f ->%s\n".format(x, Double.PositiveInfinity.toString))
}
private final val THRESHOLD = 400D
private final val CAPACITY = 11
} | 106Trabb Pardo–Knuth algorithm
| 16scala
| u9cv8 |
void move(int n, int from, int via, int to)
{
if (n > 1) {
move(n - 1, from, to, via);
printf(, from, to);
move(n - 1, via, from, to);
} else {
printf(, from, to);
}
}
int main()
{
move(4, 1,2,3);
return 0;
} | 119Towers of Hanoi
| 5c
| ekcav |
import Foundation
print("Enter 11 numbers for the TrabbPardoKnuth algorithm:")
let f: (Double) -> Double = { sqrt(fabs($0)) + 5 * pow($0, 3) }
(1...11)
.generate()
.map { i -> Double in
print("\(i): ", terminator: "")
guard let s = readLine(), let n = Double(s) else { return 0 }
return n
}
.reverse()
.forEach {
let result = f($0)
print("f(\($0))", result > 400.0? "OVERFLOW": result, separator: "\t")
} | 106Trabb Pardo–Knuth algorithm
| 17swift
| 9z3mj |
sub complement
{
my $s = shift;
$s =~ tr/01/10/;
return $s;
}
my $str = '0';
for (0..6) {
say $str;
$str .= complement($str);
} | 114Thue-Morse
| 2perl
| 5ctu2 |
null | 110Topological sort
| 11kotlin
| sabq7 |
from __future__ import print_function
def run_utm(
state = None,
blank = None,
rules = [],
tape = [],
halt = None,
pos = 0):
st = state
if not tape: tape = [blank]
if pos < 0: pos += len(tape)
if pos >= len(tape) or pos < 0: raise Error( )
rules = dict(((s0, v0), (v1, dr, s1)) for (s0, v0, v1, dr, s1) in rules)
while True:
print(st, '\t', end=)
for i, v in enumerate(tape):
if i == pos: print(% (v,), end=)
else: print(v, end=)
print()
if st == halt: break
if (st, tape[pos]) not in rules: break
(v1, dr, s1) = rules[(st, tape[pos])]
tape[pos] = v1
if dr == 'left':
if pos > 0: pos -= 1
else: tape.insert(0, blank)
if dr == 'right':
pos += 1
if pos >= len(tape): tape.append(blank)
st = s1
print()
run_utm(
halt = 'qf',
state = 'q0',
tape = list(),
blank = 'B',
rules = map(tuple,
[.split(),
.split()]
)
)
print()
run_utm(
halt = 'halt',
state = 'a',
blank = '0',
rules = map(tuple,
[.split(),
.split(),
.split(),
.split(),
.split(),
.split()]
)
)
print()
run_utm(halt = 'STOP',
state = 'A',
blank = '0',
tape = .split(),
rules = map(tuple,
[.split(),
.split(),
.split(),
.split(),
.split(),
.split(),
.split(),
.split(),
.split(),
.split(),
.split(),
.split(),
.split(),
.split()]
)
) | 103Universal Turing machine
| 3python
| n0niz |
public class Trig {
public static void main(String[] args) { | 111Trigonometric functions
| 9java
| d0wn9 |
def left_truncatable?(n)
truncatable?(n) {|i| i.to_s[1..-1].to_i}
end
def right_truncatable?(n)
truncatable?(n) {|i| i/10}
end
def truncatable?(n, &trunc_func)
return false if n.to_s.include?
loop do
n = trunc_func.call(n)
return true if n.zero?
return false unless Prime.prime?(n)
end
end
require 'prime'
primes = Prime.each(1_000_000).to_a.reverse
p primes.detect {|p| left_truncatable? p}
p primes.detect {|p| right_truncatable? p} | 102Truncatable primes
| 14ruby
| zn3tw |
<?php
function thueMorseSequence($length) {
$sequence = '';
for ($digit = $n = 0 ; $n < $length ; $n++) {
$x = $n ^ ($n - 1);
if (($x ^ ($x >> 1)) & 0x55555555) {
$digit = 1 - $digit;
}
$sequence .= $digit;
}
return $sequence;
}
for ($n = 10 ; $n <= 100 ; $n += 10) {
echo sprintf('%3d', $n), ': ', thueMorseSequence($n), PHP_EOL;
} | 114Thue-Morse
| 12php
| oxk85 |
def token_with_escape(a, escape = '^', separator = '|'):
'''
Issue python -m doctest thisfile.py to run the doctests.
>>> print(token_with_escape('one^|uno||three^^^^|four^^^|^cuatro|'))
['one|uno', '', 'three^^', 'four^|cuatro', '']
'''
result = []
token = ''
state = 0
for c in a:
if state == 0:
if c == escape:
state = 1
elif c == separator:
result.append(token)
token = ''
else:
token += c
elif state == 1:
token += c
state = 0
result.append(token)
return result | 112Tokenize a string with escaping
| 3python
| 9zimf |
var
radians = Math.PI / 4, | 111Trigonometric functions
| 10javascript
| 6d838 |
fn is_prime(n: u32) -> bool {
if n < 2 {
return false;
}
if n% 2 == 0 {
return n == 2;
}
if n% 3 == 0 {
return n == 3;
}
let mut p = 5;
while p * p <= n {
if n% p == 0 {
return false;
}
p += 2;
if n% p == 0 {
return false;
}
p += 4;
}
true
}
fn is_left_truncatable(p: u32) -> bool {
let mut n = 10;
let mut q = p;
while p > n {
if!is_prime(p% n) || q == p% n {
return false;
}
q = p% n;
n *= 10;
}
true
}
fn is_right_truncatable(p: u32) -> bool {
let mut q = p / 10;
while q > 0 {
if!is_prime(q) {
return false;
}
q /= 10;
}
true
}
fn main() {
let limit = 1000000;
let mut largest_left = 0;
let mut largest_right = 0;
let mut p = limit;
while p >= 2 {
if is_prime(p) && is_left_truncatable(p) {
largest_left = p;
break;
}
p -= 1;
}
println!("Largest left truncatable prime is {}", largest_left);
p = limit;
while p >= 2 {
if is_prime(p) && is_right_truncatable(p) {
largest_right = p;
break;
}
p -= 1;
}
println!("Largest right truncatable prime is {}", largest_right);
} | 102Truncatable primes
| 15rust
| 3d6z8 |
package empty
func Empty() {}
func Count() { | 118Time a function
| 0go
| 7utr2 |
import java.lang.management.ManagementFactory
import java.lang.management.ThreadMXBean
def threadMX = ManagementFactory.threadMXBean
assert threadMX.currentThreadCpuTimeSupported
threadMX.threadCpuTimeEnabled = true
def clockCpuTime = { Closure c ->
def start = threadMX.currentThreadCpuTime
c.call()
(threadMX.currentThreadCpuTime - start)/1000000
} | 118Time a function
| 7groovy
| u9ov9 |
(defn towers-of-hanoi [n from to via]
(when (pos? n)
(towers-of-hanoi (dec n) from via to)
(printf "Move from%s to%s\n" from to)
(recur (dec n) via to from))) | 119Towers of Hanoi
| 6clojure
| 0e5sj |
require
def (n)
n.prime_division.inject(1) {|res, (pr, exp)| res *= (pr-1) * pr**(exp-1) }
end
1.upto 25 do |n|
tot = (n)
puts prime
end
[100, 1_000, 10_000, 100_000].each do |u|
puts
end | 108Totient function
| 14ruby
| sa1qw |
object TruncatablePrimes {
def main(args: Array[String]): Unit = {
val max = 1000000
println(
s"""|ltPrime: ${ltPrimes.takeWhile(_ <= max).last}
|rtPrime: ${rtPrimes.takeWhile(_ <= max).last}
|""".stripMargin)
}
def ltPrimes: LazyList[Int] = 2 #:: LazyList.from(3, 2).filter(isLeftTruncPrime)
def rtPrimes: LazyList[Int] = 2 #:: LazyList.from(3, 2).filter(isRightTruncPrime)
def isPrime(num: Int): Boolean = (num > 1) && !LazyList.range(3, math.sqrt(num).toInt + 1, 2).exists(num%_ == 0)
def isLeftTruncPrime(num: Int): Boolean = !num.toString.contains('0') && Iterator.unfold(num.toString){str => if(str.nonEmpty) Some((str.toInt, str.tail)) else None}.forall(isPrime)
def isRightTruncPrime(num: Int): Boolean = !num.toString.exists(_.asDigit%2 == 0) && Iterator.unfold(num.toString){str => if(str.nonEmpty) Some((str.toInt, str.init)) else None}.forall(isPrime)
} | 102Truncatable primes
| 16scala
| mz9yc |
import System.CPUTime (getCPUTime)
timeIt :: (Fractional c) => (a -> IO b) -> a -> IO c
timeIt action arg = do
startTime <- getCPUTime
action arg
finishTime <- getCPUTime
return $ fromIntegral (finishTime - startTime) / 1000000000000
timeIt_ :: (Fractional c) => (a -> b) -> a -> IO c
timeIt_ f = timeIt ((`seq` return ()) . f) | 118Time a function
| 8haskell
| 8wg0z |
m='0'
print(m)
for i in range(0,6):
m0=m
m=m.replace('0','a')
m=m.replace('1','0')
m=m.replace('a','1')
m=m0+m
print(m) | 114Thue-Morse
| 3python
| 4lz5k |
def tokenize(string, sep, esc)
sep = Regexp.escape(sep)
esc = Regexp.escape(esc)
string.scan(/\G (?:^ |
m.gsub(/
end
end
p tokenize('one^|uno||three^^^^|four^^^|^cuatro|', '|', '^') | 112Tokenize a string with escaping
| 14ruby
| l6dcl |
use num::integer::gcd;
fn main() { | 108Totient function
| 15rust
| 0easl |
package main
import (
"fmt"
"sort"
) | 115Top rank per group
| 0go
| d0pne |
thue_morse <- function(steps) {
sb1 <- "0"
sb2 <- "1"
for (idx in 1:steps) {
tmp <- sb1
sb1 <- paste0(sb1, sb2)
sb2 <- paste0(sb2, tmp)
}
sb1
}
cat(thue_morse(6), "\n") | 114Thue-Morse
| 13r
| 2ynlg |
const SEPARATOR: char = '|';
const ESCAPE: char = '^';
const STRING: &str = "one^|uno||three^^^^|four^^^|^cuatro|";
fn tokenize(string: &str) -> Vec<String> {
let mut token = String::new();
let mut tokens: Vec<String> = Vec::new();
let mut chars = string.chars();
while let Some(ch) = chars.next() {
match ch {
SEPARATOR => {
tokens.push(token);
token = String::new();
},
ESCAPE => {
if let Some(next) = chars.next() {
token.push(next);
}
},
_ => token.push(ch),
}
}
tokens.push(token);
tokens
}
fn main() {
println!("{:#?}", tokenize(STRING));
} | 112Tokenize a string with escaping
| 15rust
| 2yflt |
object TokenizeStringWithEscaping0 extends App {
val (markerSpE,markerSpF) = ("\ufffe" , "\uffff")
def tokenize(str: String, sep: String, esc: String): Array[String] = {
val s0 = str.replace( esc + esc, markerSpE).replace(esc + sep, markerSpF)
val s = if (s0.last.toString == esc) s0.replace(esc, "") + esc else s0.replace(esc, "")
s.split(sep.head).map (_.replace(markerSpE, esc).replace(markerSpF, sep))
}
def str = "one^|uno||three^^^^|four^^^|^cuatro|"
tokenize(str, "|", "^").foreach(it => println(if (it.isEmpty) "<empty token>" else it))
} | 112Tokenize a string with escaping
| 16scala
| 5c3ut |
class Turing
class Tape
def initialize(symbols, blank, starting_tape)
@symbols = symbols
@blank = blank
@tape = starting_tape
@index = 0
end
def read
retval = @tape[@index]
unless retval
retval = @tape[@index] = @blank
end
raise unless @tape.member?(retval)
return retval
end
def write(symbol)
@tape[@index] = symbol
end
def right
@index += 1
end
def left
if @index == 0
@tape.unshift @blank
else
@index -= 1
end
end
def stay
end
def get_tape
return @tape
end
end
def initialize(symbols, blank,
initial_state, halt_states, running_states,
rules, starting_tape = [])
@tape = Tape.new(symbols, blank, starting_tape)
@initial_state = initial_state
@halt_states = halt_states
@running_states = running_states
@rules = rules
@halted = false
end
def run
raise if @halted
state = @initial_state
while (true)
break if @halt_states.member? state
raise unless @running_states.member? state
symbol = @tape.read
outsym, action, state = @rules[state][symbol]
@tape.write outsym
@tape.send action
end
@halted = true
return @tape.get_tape
end
end | 103Universal Turing machine
| 14ruby
| fofdr |
func isPrime(_ n: Int) -> Bool {
if n < 2 {
return false
}
if n% 2 == 0 {
return n == 2
}
if n% 3 == 0 {
return n == 3
}
var p = 5
while p * p <= n {
if n% p == 0 {
return false
}
p += 2
if n% p == 0 {
return false
}
p += 4
}
return true
}
func isLeftTruncatable(_ p: Int) -> Bool {
var n = 10
var q = p
while p > n {
if!isPrime(p% n) || q == p% n {
return false
}
q = p% n
n *= 10
}
return true
}
func isRightTruncatable(_ p: Int) -> Bool {
var q = p / 10
while q > 0 {
if!isPrime(q) {
return false
}
q /= 10
}
return true
}
let limit = 1000000
var largestLeft = 0
var largestRight = 0
var p = limit
while p >= 2 {
if isPrime(p) && isLeftTruncatable(p) {
largestLeft = p
break
}
p -= 1
}
print("Largest left truncatable prime is \(largestLeft)")
p = limit
while p >= 2 {
if isPrime(p) && isRightTruncatable(p) {
largestRight = p
break
}
p -= 1
}
print("Largest right truncatable prime is \(largestRight)") | 102Truncatable primes
| 17swift
| tizfl |
def displayRank(employees, number) {
employees.groupBy { it.Department }.sort().each { department, staff ->
println "Department $department"
println " Name ID Salary"
staff.sort { e1, e2 -> e2.Salary <=> e1.Salary }
staff[0..<Math.min(number, staff.size())].each { e ->
println " ${e.Name.padRight(20)}${e.ID}${sprintf('%8d', e.Salary)}"
}
println()
}
}
def employees = [
[Name: 'Tyler Bennett', ID: 'E10297', Salary: 32000, Department: 'D101'],
[Name: 'John Rappl', ID: 'E21437', Salary: 47000, Department: 'D050'],
[Name: 'George Woltman', ID: 'E00127', Salary: 53500, Department: 'D101'],
[Name: 'Adam Smith', ID: 'E63535', Salary: 18000, Department: 'D202'],
[Name: 'Claire Buckman', ID: 'E39876', Salary: 27800, Department: 'D202'],
[Name: 'David McClellan', ID: 'E04242', Salary: 41500, Department: 'D101'],
[Name: 'Rich Holcomb', ID: 'E01234', Salary: 49500, Department: 'D202'],
[Name: 'Nathan Adams', ID: 'E41298', Salary: 21900, Department: 'D050'],
[Name: 'Richard Potter', ID: 'E43128', Salary: 15900, Department: 'D101'],
[Name: 'David Motsinger', ID: 'E27002', Salary: 19250, Department: 'D202'],
[Name: 'Tim Sampair', ID: 'E03033', Salary: 27000, Department: 'D101'],
[Name: 'Kim Arlich', ID: 'E10001', Salary: 57000, Department: 'D190'],
[Name: 'Timothy Grove', ID: 'E16398', Salary: 29900, Department: 'D190']
]
displayRank(employees, 3) | 115Top rank per group
| 7groovy
| 0e7sh |
use std::collections::VecDeque;
use std::fmt::{Display, Formatter, Result};
fn main() {
println!("Simple incrementer");
let rules_si = vec!(
Rule::new("q0", '1', '1', Direction::Right, "q0"),
Rule::new("q0", 'B', '1', Direction::Stay, "qf")
);
let states_si = vec!("q0", "qf");
let terminating_states_si = vec!("qf");
let permissible_symbols_si = vec!('B', '1');
let mut tm_si = TM::new(states_si, "q0", terminating_states_si, permissible_symbols_si, 'B', rules_si, "111");
while!tm_si.is_done() {
println!("{}", tm_si);
tm_si.step();
}
println!("___________________");
println!("Three-state busy beaver");
let rules_bb3 = vec!(
Rule::new("a", '0', '1', Direction::Right, "b"),
Rule::new("a", '1', '1', Direction::Left, "c"),
Rule::new("b", '0', '1', Direction::Left, "a"),
Rule::new("b", '1', '1', Direction::Right, "b"),
Rule::new("c", '0', '1', Direction::Left, "b"),
Rule::new("c", '1', '1', Direction::Stay, "halt"),
);
let states_bb3 = vec!("a", "b", "c", "halt");
let terminating_states_bb3 = vec!("halt");
let permissible_symbols_bb3 = vec!('0', '1');
let mut tm_bb3 = TM::new(states_bb3 ,"a", terminating_states_bb3, permissible_symbols_bb3, '0', rules_bb3, "0");
while!tm_bb3.is_done() {
println!("{}", tm_bb3);
tm_bb3.step();
}
println!("{}", tm_bb3);
println!("___________________");
println!("Five-state busy beaver");
let rules_bb5 = vec!(
Rule::new("A", '0', '1', Direction::Right, "B"),
Rule::new("A", '1', '1', Direction::Left, "C"),
Rule::new("B", '0', '1', Direction::Right, "C"),
Rule::new("B", '1', '1', Direction::Right, "B"),
Rule::new("C", '0', '1', Direction::Right, "D"),
Rule::new("C", '1', '0', Direction::Left, "E"),
Rule::new("D", '0', '1', Direction::Left, "A"),
Rule::new("D", '1', '1', Direction::Left, "D"),
Rule::new("E", '0', '1', Direction::Stay, "H"),
Rule::new("E", '1', '0', Direction::Left, "A"),
);
let states_bb5 = vec!("A", "B", "C", "D", "E", "H");
let terminating_states_bb5 = vec!("H");
let permissible_symbols_bb5 = vec!('0', '1');
let mut tm_bb5 = TM::new(states_bb5 ,"A", terminating_states_bb5, permissible_symbols_bb5, '0', rules_bb5, "0");
let mut steps = 0;
while!tm_bb5.is_done() {
tm_bb5.step();
steps += 1;
}
println!("Steps: {}", steps);
println!("Band lenght: {}", tm_bb5.band.len());
}
struct TM<'a> {
state: &'a str,
terminating_states: Vec<&'a str>,
rules: Vec<Rule<'a>>,
band: VecDeque<char>,
head: usize,
blank: char,
}
struct Rule<'a> {
state: &'a str,
read: char,
write: char,
dir: Direction,
new_state: &'a str,
}
enum Direction{
Left,
Right,
Stay,
}
impl<'a> TM<'a> {
fn new(_states: Vec<&'a str>, initial_state: &'a str, terminating_states: Vec<&'a str>, _permissible_symbols: Vec<char>, blank: char, rules: Vec<Rule<'a>>, input: &str) -> Self {
Self { state: initial_state, terminating_states, rules, band: input.chars().collect::<VecDeque<_>>(), head: 0, blank }
}
fn is_done(&self) -> bool {
self.terminating_states.contains(&self.state)
}
fn step(&mut self) {
let field = self.band.get(self.head).unwrap();
let rule = self.rules.iter().find(|rule| rule.state == self.state && &rule.read == field).unwrap();
let field = self.band.get_mut(self.head).unwrap();
*field = rule.write;
self.state = rule.new_state;
match rule.dir {
Direction::Left => {
if self.head == 0 {
self.band.push_front(self.blank)
} else {
self.head -= 1;
}
},
Direction::Right => {
if self.head == self.band.len() - 1 {
self.band.push_back(self.blank)
}
self.head += 1;
},
Direction::Stay => {},
}
}
}
impl<'a> Display for TM<'a> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
let band = self.band.iter().enumerate().map(|(i, c)| {
if i == self.head {
format!("[{}]", c)
} else {
format!(" {} ", c)
}
}).fold(String::new(), |acc, val| acc + &val);
write!(f, "{}\t{}", self.state, band)
}
}
impl<'a> Rule<'a> {
fn new(state: &'a str, read: char, write: char, dir: Direction, new_state: &'a str) -> Self {
Self { state, read, write, dir, new_state }
}
} | 103Universal Turing machine
| 15rust
| titfd |
@tailrec
def gcd(a: Int, b: Int): Int = if(b == 0) a else gcd(b, a%b)
def totientLaz(num: Int): Int = LazyList.range(2, num).count(gcd(num, _) == 1) + 1 | 108Totient function
| 16scala
| iqxox |
null | 111Trigonometric functions
| 11kotlin
| 0ebsf |
import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;
public class TimeIt {
public static void main(String[] args) {
final ThreadMXBean threadMX = ManagementFactory.getThreadMXBean();
assert threadMX.isCurrentThreadCpuTimeSupported();
threadMX.setThreadCpuTimeEnabled(true);
long start, end;
start = threadMX.getCurrentThreadCpuTime();
countTo(100000000);
end = threadMX.getCurrentThreadCpuTime();
System.out.println("Counting to 100000000 takes "+(end-start)/1000000+"ms");
start = threadMX.getCurrentThreadCpuTime();
countTo(1000000000L);
end = threadMX.getCurrentThreadCpuTime();
System.out.println("Counting to 1000000000 takes "+(end-start)/1000000+"ms");
}
public static void countTo(long x){
System.out.println("Counting...");
for(long i=0;i<x;i++);
System.out.println("Done!");
}
} | 118Time a function
| 9java
| ekla5 |
import Data.List (sortBy, groupBy)
import Text.Printf (printf)
import Data.Ord (comparing)
import Data.Function (on)
type ID = Int
type DEP = String
type NAME = String
type SALARY = Double
data Employee = Employee
{ nr :: ID
, dep :: DEP
, name :: NAME
, sal :: SALARY
}
employees :: [Employee]
employees =
fmap
(\(i, d, n, s) -> Employee i d n s)
[ (1001, "AB", "Janssen A.H.", 41000)
, (101, "KA", "'t Woud B.", 45000)
, (1013, "AB", "de Bont C.A.", 65000)
, (1101, "CC", "Modaal A.M.J.", 30000)
, (1203, "AB", "Anders H.", 50000)
, (100, "KA", "Ezelbips P.J.", 52000)
, (1102, "CC", "Zagt A.", 33000)
, (1103, "CC", "Ternood T.R.", 21000)
, (1104, "CC", "Lageln M.", 23000)
, (1105, "CC", "Amperwat A.", 19000)
, (1106, "CC", "Boon T.J.", 25000)
, (1107, "CC", "Beloop L.O.", 31000)
, (1009, "CD", "Janszoon A.", 38665)
, (1026, "CD", "Janszen H.P.", 41000)
, (1011, "CC", "de Goeij J.", 39000)
, (106, "KA", "Pragtweik J.M.V.", 42300)
, (111, "KA", "Bakeuro S.", 31000)
, (105, "KA", "Clubdrager C.", 39800)
, (104, "KA", "Karendijk F.", 23000)
, (107, "KA", "Centjes R.M.", 34000)
, (119, "KA", "Tegenstroom H.L.", 39000)
, (1111, "CD", "Telmans R.M.", 55500)
, (1093, "AB", "de Slegte S.", 46987)
, (1199, "CC", "Uitlaat G.A.S.", 44500)
]
firstN :: Int
-> (Employee -> DEP)
-> (Employee -> SALARY)
-> [Employee]
-> [[Employee]]
firstN n o1 o2 x =
fmap
(take n . sortBy (comparingDown o2))
(groupBy (groupingOn o1) (sortBy (comparing o1) x))
groupingOn
:: Eq a1
=> (a -> a1) -> a -> a -> Bool
groupingOn = ((==) `on`)
comparingDown
:: Ord a
=> (b -> a) -> b -> b -> Ordering
comparingDown = flip . comparing
main :: IO ()
main = do
printf "%-16s%3s%10s\n" "NAME" "DEP" "TIP"
putStrLn $ replicate 31 '='
mapM_ (traverse ((printf "%-16s%3s%10.2g\n" . name) <*> dep <*> sal)) $
firstN 3 dep sal employees | 115Top rank per group
| 8haskell
| 5cfug |
puts s =
6.times{puts s << s.tr(,)} | 114Thue-Morse
| 14ruby
| rv6gs |
const ITERATIONS: usize = 8;
fn neg(sequence: &String) -> String {
sequence.chars()
.map(|ch| {
(1 - ch.to_digit(2).unwrap()).to_string()
})
.collect::<String>()
}
fn main() {
let mut sequence: String = String::from("0");
for i in 0..ITERATIONS {
println!("{}: {}", i + 1, sequence);
sequence = format!("{}{}", sequence, neg(&sequence));
}
} | 114Thue-Morse
| 15rust
| 7uyrc |
package utm.scala
import scala.annotation.tailrec
import scala.language.implicitConversions
class UniversalTuringMachine[S](
val rules: List[UTMRule[S]],
val initialState: S,
val finalStates: Set[S],
val blankSymbol: String,
val inputTapeVals: Iterable[String],
printEveryIter: Int = 1
) {
private val initialTape = UTMTape( inputTapeVals.toVector, 0, blankSymbol )
@tailrec
private def iterate( state: S, curIteration: Int, tape: UTMTape ): UTMTape = {
if (curIteration % printEveryIter == 0) {
print( s"${curIteration}: ${state}: " )
tape.printTape()
}
if (finalStates.contains( state )) {
println( s"Finished in the final state: ${state}" )
tape.printTape()
tape
} else {
rules.find(rule => rule.state == state && rule.fromSymbol == tape.current() ) match {
case Some( rule ) => {
val updatedTape = tape.updated( rule.toSymbol, rule.action )
iterate( rule.toState, curIteration + 1, updatedTape )
}
case _ => {
println(
s"Finished: no suitable rules found for ${state}/${tape.current()}"
)
tape.printTape()
tape
}
}
}
}
def run(): UTMTape =
iterate( state = initialState, curIteration = 0, tape = initialTape )
}
sealed trait UTMAction
object UTMAction {
case object left extends UTMAction
case object right extends UTMAction
case object stay extends UTMAction
}
case class UTMRule[S]( state: S, fromSymbol: String, toSymbol: String, action: UTMAction, toState: S )
object UTMRule {
implicit def tupleToUTMLRule[S](
tuple: ( S, String, String, UTMAction, S )
): UTMRule[S] =
UTMRule[S]( tuple._1, tuple._2, tuple._3, tuple._4, tuple._5 )
}
case class UTMTape( content: Vector[String], position: Int, blankSymbol: String ) {
private def updateContentAtPos( symbol: String ) = {
if (position >= content.length) {
content :+ symbol
} else if (position < 0) {
symbol +: content
} else if (content( position ) != symbol)
content.updated( position, symbol )
else
content
}
private[scala] def updated( symbol: String, action: UTMAction ): UTMTape = {
val updatedTape =
this.copy( content = updateContentAtPos( symbol ), position = action match {
case UTMAction.left => position - 1
case UTMAction.right => position + 1
case UTMAction.stay => position
} )
if (updatedTape.position < 0) {
updatedTape.copy(
content = blankSymbol +: updatedTape.content,
position = 0
)
} else if (updatedTape.position >= updatedTape.content.length) {
updatedTape.copy( content = updatedTape.content :+ blankSymbol )
} else
updatedTape
}
private[scala] def current(): String = {
if (content.isDefinedAt( position ))
content( position )
else
blankSymbol
}
def printTape(): Unit = {
print( "[" )
if (position < 0)
print( "" )
content.zipWithIndex.foreach {
case ( symbol, index ) =>
if (position == index)
print( "" )
else
print( " " )
print( s"$symbol" )
}
if (position >= content.length)
print( "" )
println( "]" )
}
}
object UniversalTuringMachine extends App {
main()
def main(): Unit = {
import UTMAction._
def createIncrementMachine() = {
sealed trait IncrementStates
case object q0 extends IncrementStates
case object qf extends IncrementStates
new UniversalTuringMachine[IncrementStates](
rules = List( ( q0, "1", "1", right, q0 ), ( q0, "B", "1", stay, qf ) ),
initialState = q0,
finalStates = Set( qf ),
blankSymbol = "B",
inputTapeVals = Seq( "1", "1", "1" )
).run()
}
def createThreeStateBusyBeaver() = {
sealed trait ThreeStateBusyStates
case object a extends ThreeStateBusyStates
case object b extends ThreeStateBusyStates
case object c extends ThreeStateBusyStates
case object halt extends ThreeStateBusyStates
new UniversalTuringMachine[ThreeStateBusyStates](
rules = List(
( a, "0", "1", right, b ),
( a, "1", "1", left, c ),
( b, "0", "1", left, a ),
( b, "1", "1", right, b ),
( c, "0", "1", left, b ),
( c, "1", "1", stay, halt )
),
initialState = a,
finalStates = Set( halt ),
blankSymbol = "0",
inputTapeVals = Seq()
).run()
}
def createFiveState2SymBusyBeaverMachine() = {
sealed trait FiveBeaverStates
case object FA extends FiveBeaverStates
case object FB extends FiveBeaverStates
case object FC extends FiveBeaverStates
case object FD extends FiveBeaverStates
case object FE extends FiveBeaverStates
case object FH extends FiveBeaverStates
new UniversalTuringMachine[FiveBeaverStates](
rules = List(
( FA, "0", "1", right, FB ),
( FA, "1", "1", left, FC ),
( FB, "0", "1", right, FC ),
( FB, "1", "1", right, FB ),
( FC, "0", "1", right, FD ),
( FC, "1", "0", left, FE ),
( FD, "0", "1", left, FA ),
( FD, "1", "1", left, FD ),
( FE, "0", "1", stay, FH ),
( FE, "1", "0", left, FA )
),
initialState = FA,
finalStates = Set( FH ),
blankSymbol = "0",
inputTapeVals = Seq(),
printEveryIter = 100000
).run()
}
createIncrementMachine()
createThreeStateBusyBeaver() | 103Universal Turing machine
| 16scala
| 6f631 |
function test() {
let n = 0
for(let i = 0; i < 1000000; i++){
n += i
}
}
let start = new Date().valueOf()
test()
let end = new Date().valueOf()
console.log('test() took ' + ((end - start) / 1000) + ' seconds') | 118Time a function
| 10javascript
| 0e4sz |
def thueMorse(n: Int): String = {
val (sb0, sb1) = (new StringBuilder("0"), new StringBuilder("1"))
(0 until n).foreach { _ =>
val tmp = sb0.toString()
sb0.append(sb1)
sb1.append(tmp)
}
sb0.toString()
}
(0 to 6).foreach(i => println(s"$i: ${thueMorse(i)}")) | 114Thue-Morse
| 16scala
| kgchk |
extension String {
func tokenize(separator: Character, escape: Character) -> [String] {
var token = ""
var tokens = [String]()
var chars = makeIterator()
while let char = chars.next() {
switch char {
case separator:
tokens.append(token)
token = ""
case escape:
if let next = chars.next() {
token.append(next)
}
case _:
token.append(char)
}
}
tokens.append(token)
return tokens
}
}
print("one^|uno||three^^^^|four^^^|^cuatro|".tokenize(separator: "|", escape: "^")) | 112Tokenize a string with escaping
| 17swift
| c3n9t |
null | 118Time a function
| 11kotlin
| kg6h3 |
package main
import (
"bufio"
"fmt"
"math/rand"
"os"
"strings"
)
var b []byte
func printBoard() {
fmt.Printf("%s\n%s\n%s\n", b[0:3], b[3:6], b[6:9])
}
var pScore, cScore int
var pMark, cMark byte = 'X', 'O'
var in = bufio.NewReader(os.Stdin)
func main() {
b = make([]byte, 9)
fmt.Println("Play by entering a digit.")
for { | 117Tic-tac-toe
| 0go
| u9ivt |
main() {
moveit(from,to) {
print("move ${from} ---> ${to}");
}
hanoi(height,toPole,fromPole,usePole) {
if (height>0) {
hanoi(height-1,usePole,fromPole,toPole);
moveit(fromPole,toPole);
hanoi(height-1,toPole,usePole,fromPole);
}
}
hanoi(3,3,1,2);
} | 119Towers of Hanoi
| 18dart
| h4zjb |
WITH recursive a(a) AS (SELECT '0' UNION ALL SELECT REPLACE(REPLACE(hex(a),'30','01'),'31','10') FROM a) SELECT * FROM a; | 114Thue-Morse
| 19sql
| 1jvpg |
package main
import "fmt"
type node struct {
value int
left, right *node
}
func (n *node) iterPreorder(visit func(int)) {
if n == nil {
return
}
visit(n.value)
n.left.iterPreorder(visit)
n.right.iterPreorder(visit)
}
func (n *node) iterInorder(visit func(int)) {
if n == nil {
return
}
n.left.iterInorder(visit)
visit(n.value)
n.right.iterInorder(visit)
}
func (n *node) iterPostorder(visit func(int)) {
if n == nil {
return
}
n.left.iterPostorder(visit)
n.right.iterPostorder(visit)
visit(n.value)
}
func (n *node) iterLevelorder(visit func(int)) {
if n == nil {
return
}
for queue := []*node{n}; ; {
n = queue[0]
visit(n.value)
copy(queue, queue[1:])
queue = queue[:len(queue)-1]
if n.left != nil {
queue = append(queue, n.left)
}
if n.right != nil {
queue = append(queue, n.right)
}
if len(queue) == 0 {
return
}
}
}
func main() {
tree := &node{1,
&node{2,
&node{4,
&node{7, nil, nil},
nil},
&node{5, nil, nil}},
&node{3,
&node{6,
&node{8, nil, nil},
&node{9, nil, nil}},
nil}}
fmt.Print("preorder: ")
tree.iterPreorder(visitor)
fmt.Println()
fmt.Print("inorder: ")
tree.iterInorder(visitor)
fmt.Println()
fmt.Print("postorder: ")
tree.iterPostorder(visitor)
fmt.Println()
fmt.Print("level-order: ")
tree.iterLevelorder(visitor)
fmt.Println()
}
func visitor(value int) {
fmt.Print(value, " ")
} | 113Tree traversal
| 0go
| p7vbg |
package main
import (
"fmt"
"strings"
)
func main() {
s := "Hello,How,Are,You,Today"
fmt.Println(strings.Join(strings.Split(s, ","), "."))
} | 116Tokenize a string
| 0go
| j567d |
println 'Hello,How,Are,You,Today'.split(',').join('.') | 116Tokenize a string
| 7groovy
| 5cduv |
class Main {
def input = new Scanner(System.in)
static main(args) {
Main main = new Main();
main.play();
}
public void play() {
TicTackToe game = new TicTackToe();
game.init()
def gameOver = false
def player = game.player1
println "Players take turns marking a square. Only squares \n"+
"not already marked can be picked. Once a player has \n"+
"marked three squares in a row, column or diagonal, they win! If all squares \n"+
"are marked and no three squares are the same, a tied game is declared.\n"+
"Player 1 is O and Player 2 is X \n"+
"Have Fun! \n\n"
println "${game.drawBoard()}"
while (!gameOver && game.plays < 9) {
player = game.currentPlayer == 1 ? game.player1:game.player2
def validPick = false;
while (!validPick) {
def square
println "Next $player, enter move by selecting square's number:"
try {
square = input.nextLine();
} catch (Exception ex) { }
if (square.length() == 1 && Character.isDigit(square.toCharArray()[0])) { validPick = game.placeMarker(square) }
if (!validPick) { println "Select another Square" }
}
(game.checkWinner(player))? gameOver = true : game.switchPlayers()
println(game.drawBoard());
}
println "Game Over, " + ((gameOver == true)? "$player Wins": "Draw")
}
}
public class TicTackToe {
def board = new Object[3][3]
def final player1 = "player 1"
def final player2 = "player 2"
def final marker1 = 'X'
def final marker2 = 'O'
int currentPlayer
int plays
public TicTacToe(){
}
def init() {
int counter = 0;
(0..2).each { row ->
(0..2).each { col ->
board[row][col] = (++counter).toString();
}
}
plays = 0
currentPlayer =1
}
def switchPlayers() {
currentPlayer = (currentPlayer == 1) ? 2:1
plays++
}
def placeMarker(play) {
def result = false
(0..2).each { row ->
(0..2).each { col ->
if (board[row][col].toString()==play.toString()){
board[row][col] = (currentPlayer == 1) ? marker2: marker1;
result = true;
}
}
}
return result;
}
def checkWinner(player) {
char current = (player == player1)? marker2: marker1 | 117Tic-tac-toe
| 7groovy
| 9zqm4 |
def preorder;
preorder = { Node node ->
([node] + node.children().collect { preorder(it) }).flatten()
}
def postorder;
postorder = { Node node ->
(node.children().collect { postorder(it) } + [node]).flatten()
}
def inorder;
inorder = { Node node ->
def kids = node.children()
if (kids.empty) [node]
else if (kids.size() == 1 && kids[0].'@right') [node] + inorder(kids[0])
else inorder(kids[0]) + [node] + (kids.size()>1 ? inorder(kids[1]): [])
}
def levelorder = { Node node ->
def nodeList = []
def level = [node]
while (!level.empty) {
nodeList += level
def nextLevel = level.collect { it.children() }.flatten()
level = nextLevel
}
nodeList
}
class BinaryNodeBuilder extends NodeBuilder {
protected Object postNodeCompletion(Object parent, Object node) {
assert node.children().size() < 3
node
}
} | 113Tree traversal
| 7groovy
| 7umrz |
import Data.Text (splitOn,intercalate)
import qualified Data.Text.IO as T (putStrLn)
main = T.putStrLn . intercalate "." $ splitOn "," "Hello,How,Are,You,Today" | 116Tokenize a string
| 8haskell
| oxj8p |
function Test_Function()
for i = 1, 10000000 do
local s = math.log( i )
s = math.sqrt( s )
end
end
t1 = os.clock()
Test_Function()
t2 = os.clock()
print( os.difftime( t2, t1 ) ) | 118Time a function
| 1lua
| bryka |
module Main where
import System.Random
import Data.List (intercalate, find, minimumBy)
import System.Environment (getArgs)
import Data.Char (digitToInt)
import Data.Maybe (listToMaybe, mapMaybe)
import Control.Monad (guard)
import Data.Ord (comparing)
tictactoe :: String -> Bool
tictactoe a = tictactoeFor 'X' a /= tictactoeFor 'O' a
tictactoeFor :: Char -> String -> Bool
tictactoeFor n [a,b,c,d,e,f,g,h,i] =
[n,n,n] `elem` [[a,b,c],[d,e,f],[g,h,i],[a,d,g],
[b,e,h],[c,f,i],[a,e,i],[c,e,g]]
start :: String
start = " "
isPossible :: Int -> String -> Bool
isPossible n game = (game !! n) `notElem` "XO"
place :: Int -> Char -> String -> Either String String
place i c game =
if isPossible i game
then Right $ take i game ++ [c] ++ drop (i + 1) game
else Left game
developGame :: Bool -> Int -> Int -> Char -> String -> (Int, Char, String)
developGame iterateMore moves i player game
| i > 8 =
if iterateMore
then developGame False moves 0 player game
else (moves, player, game)
| moves == 9 || tictactoeFor player game = (moves, player, game)
| otherwise = case place i otherPlayer game of
Left _ -> developGame iterateMore moves (i + 1)
otherPlayer game
Right newGame -> developGame iterateMore (moves + 1) 0
otherPlayer newGame
where
otherPlayer = changePlayer player
bestMoveFor :: Char -> String -> Int
bestMoveFor player game = bestMove
where
continuations = [ (x, developGame True 0 x player game) |
x <- [0..8] ]
move (_, (m, _, _)) = m
(bestMove, _) = minimumBy (comparing move) continuations
canBlock :: Char -> String -> Maybe Int
canBlock p [a,b,c,d,e,f,g,h,i] =
listToMaybe $ mapMaybe blockable [[a,b,c],[d,e,f],[g,h,i],[a,d,g],
[b,e,h],[c,f,i],[a,e,i],[c,e,g]]
where
blockable xs = do
guard $ length (filter (== otherPlayer) xs) == 2
x <- find (`elem` "123456789") xs
return $ digitToInt x
otherPlayer = changePlayer p
showGame :: String -> String
showGame [a,b,c,d,e,f,g,h,i] =
topBottom ++
"| | 1 | 2 | 3 |\n" ++
topBottom ++
row "0" [[a],[b],[c]] ++
row "3" [[d],[e],[f]] ++
row "6" [[g],[h],[i]]
where
topBottom = "+
row n x = "| " ++ n ++ "+ | " ++
intercalate " | " x ++ " |\n" ++ topBottom
enterNumber :: IO Int
enterNumber = do
c <- getChar
if c `elem` "123456789"
then do
putStrLn ""
return $ digitToInt c
else do
putStrLn "\nPlease enter a digit!"
enterNumber
turn :: (Int, Char, String) -> IO (Int, Char, String)
turn (count, player, game) = do
putStr $ "Please tell me where you want to put an " ++
[player] ++ ": "
pos <- enterNumber
case place (pos - 1) player game of
Left oldGame -> do
putStrLn "That place is already taken!\n"
turn (count, player, oldGame)
Right newGame ->
return (count + 1, changePlayer player, newGame)
changePlayer :: Char -> Char
changePlayer 'O' = 'X'
changePlayer 'X' = 'O'
autoTurn :: Bool -> (Int, Char, String) -> IO (Int, Char, String)
autoTurn forceRandom (count, player, game) = do
i <- if count == 0 || forceRandom
then randomRIO (0,8)
else return $
case canBlock player game of
Nothing -> bestMoveFor player game
Just blockPos -> blockPos
case place i player game of
Left oldGame -> autoTurn True (count, player, oldGame)
Right newGame -> do
putStrLn $ "It's player " ++ [player] ++ "'s turn."
return (count + 1, changePlayer player, newGame)
play :: Int -> (Int, Char, String) -> IO ()
play auto cpg@(_, player, game) = do
newcpg@(newCount, newPlayer, newGame) <- case auto of
0 -> turn cpg
1 -> autoTurn False cpg
2 -> if player == 'X' then autoTurn False cpg else turn cpg
3 -> if player == 'O' then autoTurn False cpg else turn cpg
putStrLn $ "\n" ++ showGame newGame
if tictactoe newGame
then putStrLn $ "Player " ++ [changePlayer newPlayer] ++ " wins!\n"
else
if newCount == 9
then putStrLn "Draw!\n"
else play auto newcpg
main :: IO ()
main = do
a <- getArgs
if null a
then usage
else do
let option = head a
if option `elem` ["0","1","2","3"]
then do
putStrLn $ "\n" ++ showGame start
let m = read option :: Int
play m (0, 'X', start)
else usage
usage :: IO ()
usage = do
putStrLn "TIC-TAC-TOE GAME\n================\n"
putStrLn "How do you want to play?"
putStrLn "Run the program with one of the following options."
putStrLn "0: both players are human"
putStrLn "1: both players are computer"
putStrLn "2: player X is computer and player O is human"
putStrLn "3: player X is human and player O is computer"
putStrLn "Player X always begins." | 117Tic-tac-toe
| 8haskell
| wbved |
sub print_topo_sort {
my %deps = @_;
my %ba;
while ( my ( $before, $afters_aref ) = each %deps ) {
for my $after ( @{ $afters_aref } ) {
$ba{$before}{$after} = 1 if $before ne $after;
$ba{$after} ||= {};
}
}
while ( my @afters = sort grep { ! %{ $ba{$_} } } keys %ba ) {
print "@afters\n";
delete @ba{@afters};
delete @{$_}{@afters} for values %ba;
}
print !!%ba ? "Cycle found! ". join( ' ', sort keys %ba ). "\n" : "---\n";
}
my %deps = (
des_system_lib => [qw( std synopsys std_cell_lib des_system_lib dw02
dw01 ramlib ieee )],
dw01 => [qw( ieee dw01 dware gtech )],
dw02 => [qw( ieee dw02 dware )],
dw03 => [qw( std synopsys dware dw03 dw02 dw01 ieee gtech )],
dw04 => [qw( dw04 ieee dw01 dware gtech )],
dw05 => [qw( dw05 ieee dware )],
dw06 => [qw( dw06 ieee dware )],
dw07 => [qw( ieee dware )],
dware => [qw( ieee dware )],
gtech => [qw( ieee gtech )],
ramlib => [qw( std ieee )],
std_cell_lib => [qw( ieee std_cell_lib )],
synopsys => [qw( )],
);
print_topo_sort(%deps);
push @{ $deps{'dw01'} }, 'dw04';
print_topo_sort(%deps); | 110Topological sort
| 2perl
| u96vr |
print(math.cos(1), math.sin(1), math.tan(1), math.atan(1), math.atan2(3, 4)) | 111Trigonometric functions
| 1lua
| 8wp0e |
data Tree a
= Empty
| Node
{ value :: a,
left :: Tree a,
right :: Tree a
}
preorder, inorder, postorder, levelorder :: Tree a -> [a]
preorder Empty = []
preorder (Node v l r) = v: preorder l <> preorder r
inorder Empty = []
inorder (Node v l r) = inorder l <> (v: inorder r)
postorder Empty = []
postorder (Node v l r) = postorder l <> postorder r <> [v]
levelorder x = loop [x]
where
loop [] = []
loop (Empty: xs) = loop xs
loop (Node v l r: xs) = v: loop (xs <> [l, r])
tree :: Tree Int
tree =
Node
1
( Node
2
(Node 4 (Node 7 Empty Empty) Empty)
(Node 5 Empty Empty)
)
( Node
3
(Node 6 (Node 8 Empty Empty) (Node 9 Empty Empty))
Empty
)
asciiTree :: String
asciiTree =
unlines
[ " 1",
" / \\",
" / \\",
" / \\",
" 2 3",
" / \\ /",
" 4 5 6",
" / / \\",
" 7 8 9"
]
main :: IO ()
main = do
putStrLn asciiTree
mapM_ putStrLn $
zipWith
( \s xs ->
justifyLeft 14 ' ' (s <> ":")
<> unwords (show <$> xs)
)
["preorder", "inorder", "postorder", "level-order"]
([preorder, inorder, postorder, levelorder] <*> [tree])
where
justifyLeft n c s = take n (s <> replicate n c) | 113Tree traversal
| 8haskell
| f8ed1 |
import java.io.File;
import java.util.*;
public class TopRankPerGroup {
private static class Employee {
final String name;
final String id;
final String department;
final int salary;
Employee(String[] rec) {
name = rec[0];
id = rec[1];
salary = Integer.parseInt(rec[2]);
department = rec[3];
}
@Override
public String toString() {
return String.format("%s%s%d%s", id, name, salary, department);
}
}
public static void main(String[] args) throws Exception {
int N = args.length > 0 ? Integer.parseInt(args[0]) : 3;
Map<String, List<Employee>> records = new TreeMap<>();
try (Scanner sc = new Scanner(new File("data.txt"))) {
while (sc.hasNextLine()) {
String[] rec = sc.nextLine().trim().split(", ");
List<Employee> lst = records.get(rec[3]);
if (lst == null) {
lst = new ArrayList<>();
records.put(rec[3], lst);
}
lst.add(new Employee(rec));
}
}
records.forEach((key, val) -> {
System.out.printf("%nDepartment%s%n", key);
val.stream()
.sorted((a, b) -> Integer.compare(b.salary, a.salary))
.limit(N).forEach(System.out::println);
});
}
} | 115Top rank per group
| 9java
| 9z0mu |
var data = [
{name: "Tyler Bennett", id: "E10297", salary: 32000, dept: "D101"},
{name: "John Rappl", id: "E21437", salary: 47000, dept: "D050"},
{name: "George Woltman", id: "E00127", salary: 53500, dept: "D101"},
{name: "Adam Smith", id: "E63535", salary: 18000, dept: "D202"},
{name: "Claire Buckman", id: "E39876", salary: 27800, dept: "D202"},
{name: "David McClellan", id: "E04242", salary: 41500, dept: "D101"},
{name: "Rich Holcomb", id: "E01234", salary: 49500, dept: "D202"},
{name: "Nathan Adams", id: "E41298", salary: 21900, dept: "D050"},
{name: "Richard Potter", id: "E43128", salary: 15900, dept: "D101"},
{name: "David Motsinger", id: "E27002", salary: 19250, dept: "D202"},
{name: "Tim Sampair", id: "E03033", salary: 27000, dept: "D101"},
{name: "Kim Arlich", id: "E10001", salary: 57000, dept: "D190"},
{name: "Timothy Grove", id: "E16398", salary: 29900, dept: "D190"},
];
function top_rank(n) {
var by_dept = group_by_dept(data);
for (var dept in by_dept) {
output(dept);
for (var i = 0; i < n && i < by_dept[dept].length; i++) {
var emp = by_dept[dept][i];
output(emp.name + ", id=" + emp.id + ", salary=" + emp.salary);
}
output("");
}
} | 115Top rank per group
| 10javascript
| u9dvb |
String toTokenize = "Hello,How,Are,You,Today";
System.out.println(String.join(".", toTokenize.split(","))); | 116Tokenize a string
| 9java
| wbuej |
alert( "Hello,How,Are,You,Today".split(",").join(".") ); | 116Tokenize a string
| 10javascript
| 8w70l |
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Hashtable;
public class TicTacToe
{
public static void main(String[] args)
{
TicTacToe now=new TicTacToe();
now.startMatch();
}
private int[][] marks;
private int[][] wins;
private int[] weights;
private char[][] grid;
private final int knotcount=3;
private final int crosscount=4;
private final int totalcount=5;
private final int playerid=0;
private final int compid=1;
private final int truceid=2;
private final int playingid=3;
private String movesPlayer;
private byte override;
private char[][] overridegrid={{'o','o','o'},{'o','o','o'},{'o','o','o'}};
private char[][] numpad={{'7','8','9'},{'4','5','6'},{'1','2','3'}};
private Hashtable<Integer,Integer> crossbank;
private Hashtable<Integer,Integer> knotbank;
public void startMatch()
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Start?(y/n):");
char choice='y';
try
{
choice=br.readLine().charAt(0);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
if(choice=='n'||choice=='N')
{
return;
}
System.out.println("Use a standard numpad as an entry grid, as so:\n ");
display(numpad);
System.out.println("Begin");
int playerscore=0;
int compscore=0;
do
{
int result=startGame();
if(result==playerid)
playerscore++;
else if(result==compid)
compscore++;
System.out.println("Score: Player-"+playerscore+" AI-"+compscore);
System.out.print("Another?(y/n):");
try
{
choice=br.readLine().charAt(0);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}while(choice!='n'||choice=='N');
System.out.println("Game over.");
}
private void put(int cell,int player)
{
int i=-1,j=-1;;
switch(cell)
{
case 1:i=2;j=0;break;
case 2:i=2;j=1;break;
case 3:i=2;j=2;break;
case 4:i=1;j=0;break;
case 5:i=1;j=1;break;
case 6:i=1;j=2;break;
case 7:i=0;j=0;break;
case 8:i=0;j=1;break;
case 9:i=0;j=2;break;
default:display(overridegrid);return;
}
char mark='x';
if(player==0)
mark='o';
grid[i][j]=mark;
display(grid);
}
private int startGame()
{
init();
display(grid);
int status=playingid;
while(status==playingid)
{
put(playerMove(),0);
if(override==1)
{
System.out.println("O wins.");
return playerid;
}
status=checkForWin();
if(status!=playingid)
break;
try{Thread.sleep(1000);}catch(Exception e){System.out.print(e.getMessage());}
put(compMove(),1);
status=checkForWin();
}
return status;
}
private void init()
{
movesPlayer="";
override=0;
marks=new int[8][6];
wins=new int[][] | 117Tic-tac-toe
| 9java
| kgyhm |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>TicTacToe</title>
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<script> | 117Tic-tac-toe
| 10javascript
| ek2ao |
import java.util.*;
public class TreeTraversal {
static class Node<T> {
T value;
Node<T> left;
Node<T> right;
Node(T value) {
this.value = value;
}
void visit() {
System.out.print(this.value + " ");
}
}
static enum ORDER {
PREORDER, INORDER, POSTORDER, LEVEL
}
static <T> void traverse(Node<T> node, ORDER order) {
if (node == null) {
return;
}
switch (order) {
case PREORDER:
node.visit();
traverse(node.left, order);
traverse(node.right, order);
break;
case INORDER:
traverse(node.left, order);
node.visit();
traverse(node.right, order);
break;
case POSTORDER:
traverse(node.left, order);
traverse(node.right, order);
node.visit();
break;
case LEVEL:
Queue<Node<T>> queue = new LinkedList<>();
queue.add(node);
while(!queue.isEmpty()){
Node<T> next = queue.remove();
next.visit();
if(next.left!=null)
queue.add(next.left);
if(next.right!=null)
queue.add(next.right);
}
}
}
public static void main(String[] args) {
Node<Integer> one = new Node<Integer>(1);
Node<Integer> two = new Node<Integer>(2);
Node<Integer> three = new Node<Integer>(3);
Node<Integer> four = new Node<Integer>(4);
Node<Integer> five = new Node<Integer>(5);
Node<Integer> six = new Node<Integer>(6);
Node<Integer> seven = new Node<Integer>(7);
Node<Integer> eight = new Node<Integer>(8);
Node<Integer> nine = new Node<Integer>(9);
one.left = two;
one.right = three;
two.left = four;
two.right = five;
three.left = six;
four.left = seven;
six.left = eight;
six.right = nine;
traverse(one, ORDER.PREORDER);
System.out.println();
traverse(one, ORDER.INORDER);
System.out.println();
traverse(one, ORDER.POSTORDER);
System.out.println();
traverse(one, ORDER.LEVEL);
}
} | 113Tree traversal
| 9java
| 0ehse |
use Benchmark;
use Memoize;
sub fac1 {
my $n = shift;
return $n == 0 ? 1 : $n * fac1($n - 1);
}
sub fac2 {
my $n = shift;
return $n == 0 ? 1 : $n * fac2($n - 1);
}
memoize('fac2');
my $result = timethese(100000, {
'fac1' => sub { fac1(50) },
'fac2' => sub { fac2(50) },
});
Benchmark::cmpthese($result); | 118Time a function
| 2perl
| 3n1zs |
function BinaryTree(value, left, right) {
this.value = value;
this.left = left;
this.right = right;
}
BinaryTree.prototype.preorder = function(f) {this.walk(f,['this','left','right'])}
BinaryTree.prototype.inorder = function(f) {this.walk(f,['left','this','right'])}
BinaryTree.prototype.postorder = function(f) {this.walk(f,['left','right','this'])}
BinaryTree.prototype.walk = function(func, order) {
for (var i in order)
switch (order[i]) {
case "this": func(this.value); break;
case "left": if (this.left) this.left.walk(func, order); break;
case "right": if (this.right) this.right.walk(func, order); break;
}
}
BinaryTree.prototype.levelorder = function(func) {
var queue = [this];
while (queue.length != 0) {
var node = queue.shift();
func(node.value);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
} | 113Tree traversal
| 10javascript
| d0anu |
fun main(args: Array<String>) {
val input = "Hello,How,Are,You,Today"
println(input.split(',').joinToString("."))
} | 116Tokenize a string
| 11kotlin
| br9kb |
null | 115Top rank per group
| 11kotlin
| ziets |
null | 117Tic-tac-toe
| 11kotlin
| g2f4d |
try:
from functools import reduce
except:
pass
data = {
'des_system_lib': set('std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee'.split()),
'dw01': set('ieee dw01 dware gtech'.split()),
'dw02': set('ieee dw02 dware'.split()),
'dw03': set('std synopsys dware dw03 dw02 dw01 ieee gtech'.split()),
'dw04': set('dw04 ieee dw01 dware gtech'.split()),
'dw05': set('dw05 ieee dware'.split()),
'dw06': set('dw06 ieee dware'.split()),
'dw07': set('ieee dware'.split()),
'dware': set('ieee dware'.split()),
'gtech': set('ieee gtech'.split()),
'ramlib': set('std ieee'.split()),
'std_cell_lib': set('ieee std_cell_lib'.split()),
'synopsys': set(),
}
def toposort2(data):
for k, v in data.items():
v.discard(k)
extra_items_in_deps = reduce(set.union, data.values()) - set(data.keys())
data.update({item:set() for item in extra_items_in_deps})
while True:
ordered = set(item for item,dep in data.items() if not dep)
if not ordered:
break
yield ' '.join(sorted(ordered))
data = {item: (dep - ordered) for item,dep in data.items()
if item not in ordered}
assert not data, % data
print ('\n'.join( toposort2(data) )) | 110Topological sort
| 3python
| 5cyux |
deps <- list(
"des_system_lib" = c("std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"),
"dw01" = c("ieee", "dw01", "dware", "gtech", "dw04"),
"dw02" = c("ieee", "dw02", "dware"),
"dw03" = c("std", "synopsys", "dware", "dw03", "dw02", "dw01", "ieee", "gtech"),
"dw04" = c("dw04", "ieee", "dw01", "dware", "gtech"),
"dw05" = c("dw05", "ieee", "dware"),
"dw06" = c("dw06", "ieee", "dware"),
"dw07" = c("ieee", "dware"),
"dware" = c("ieee", "dware"),
"gtech" = c("ieee", "gtech"),
"ramlib" = c("std", "ieee"),
"std_cell_lib" = c("ieee", "std_cell_lib"),
"synopsys" = c()) | 110Topological sort
| 13r
| l6tce |
N = 2
lst = { { "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" }
}
dep = {}
for i = 1, #lst do
if dep[ lst[i][4] ] == nil then
dep[ lst[i][4] ] = {}
dep[ lst[i][4] ][1] = lst[i]
else
dep[ lst[i][4] ][#dep[lst[i][4]]+1] = lst[i]
end
end
for i, _ in pairs( dep ) do
table.sort( dep[i], function (a,b) return a[3] > b[3] end )
print( "Department:", dep[i][1][4] )
for l = 1, math.min( N, #dep[i] ) do
print( "", dep[i][l][1], dep[i][l][2], dep[i][l][3] )
end
print ""
end | 115Top rank per group
| 1lua
| 3nwzo |
data class Node(val v: Int, var left: Node? = null, var right: Node? = null) {
override fun toString() = "$v"
}
fun preOrder(n: Node?) {
n?.let {
print("$n ")
preOrder(n.left)
preOrder(n.right)
}
}
fun inorder(n: Node?) {
n?.let {
inorder(n.left)
print("$n ")
inorder(n.right)
}
}
fun postOrder(n: Node?) {
n?.let {
postOrder(n.left)
postOrder(n.right)
print("$n ")
}
}
fun levelOrder(n: Node?) {
n?.let {
val queue = mutableListOf(n)
while (queue.isNotEmpty()) {
val node = queue.removeAt(0)
print("$node ")
node.left?.let { queue.add(it) }
node.right?.let { queue.add(it) }
}
}
}
inline fun exec(name: String, n: Node?, f: (Node?) -> Unit) {
print(name)
f(n)
println()
}
fun main(args: Array<String>) {
val nodes = Array(10) { Node(it) }
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]
exec(" preOrder: ", nodes[1], ::preOrder)
exec(" inorder: ", nodes[1], ::inorder)
exec(" postOrder: ", nodes[1], ::postOrder)
exec("level-order: ", nodes[1], ::levelOrder)
} | 113Tree traversal
| 11kotlin
| ek4a4 |
#!/usr/bin/env luajit
ffi=require"ffi"
local function printf(fmt,...) io.write(string.format(fmt, ...)) end
local board="123456789" | 117Tic-tac-toe
| 1lua
| rvtga |
import sys, timeit
def usec(function, arguments):
modname, funcname = __name__, function.__name__
timer = timeit.Timer(stmt='%(funcname)s(*args)'% vars(),
setup='from%(modname)s import%(funcname)s; args=%(arguments)r'% vars())
try:
t, N = 0, 1
while t < 0.2:
t = min(timer.repeat(repeat=3, number=N))
N *= 10
microseconds = round(10000000 * t / N, 1)
return microseconds
except:
timer.print_exc(file=sys.stderr)
raise
from math import pow
def nothing(): pass
def identity(x): return x | 118Time a function
| 3python
| 6da3w |
foo <- function()
{
for(i in 1:10)
{
mat <- matrix(rnorm(1e6), nrow=1e3)
mat^-0.5
}
}
timer <- system.time(foo())
timer["user.self"] | 118Time a function
| 13r
| f8kdc |
require 'tsort'
class Hash
include TSort
alias tsort_each_node each_key
def tsort_each_child(node, &block)
fetch(node).each(&block)
end
end
depends = {}
DATA.each do |line|
key, *libs = line.split
depends[key] = libs
libs.each {|lib| depends[lib] ||= []}
end
begin
p depends.tsort
depends[] <<
p depends.tsort
rescue TSort::Cyclic => e
puts
end
__END__
des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee
dw01 ieee dw01 dware gtech
dw02 ieee dw02 dware
dw03 std synopsys dware dw03 dw02 dw01 ieee gtech
dw04 dw04 ieee dw01 dware gtech
dw05 dw05 ieee dware
dw06 dw06 ieee dware
dw07 ieee dware
dware ieee dware
gtech ieee gtech
ramlib std ieee
std_cell_lib ieee std_cell_lib
synopsys | 110Topological sort
| 14ruby
| g294q |
function string:split (sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
local str = "Hello,How,Are,You,Today"
print(table.concat(str:split(","), ".")) | 116Tokenize a string
| 1lua
| p7cbw |
use std::boxed::Box;
use std::collections::{HashMap, HashSet};
#[derive(Debug, PartialEq, Eq, Hash)]
struct Library<'a> {
name: &'a str,
children: Vec<&'a str>,
num_parents: usize,
}
fn build_libraries(input: Vec<&str>) -> HashMap<&str, Box<Library>> {
let mut libraries: HashMap<&str, Box<Library>> = HashMap::new();
for input_line in input {
let line_split = input_line.split_whitespace().collect::<Vec<&str>>();
let name = line_split.get(0).unwrap();
let mut num_parents: usize = 0;
for parent in line_split.iter().skip(1) {
if parent == name {
continue;
}
if!libraries.contains_key(parent) {
libraries.insert(
parent,
Box::new(Library {
name: parent,
children: vec![name],
num_parents: 0,
}),
);
} else {
libraries.get_mut(parent).unwrap().children.push(name);
}
num_parents += 1;
}
if!libraries.contains_key(name) {
libraries.insert(
name,
Box::new(Library {
name,
children: Vec::new(),
num_parents,
}),
);
} else {
libraries.get_mut(name).unwrap().num_parents = num_parents;
}
}
libraries
}
fn topological_sort<'a>(
mut libraries: HashMap<&'a str, Box<Library<'a>>>,
) -> Result<Vec<&'a str>, String> {
let mut needs_processing = libraries
.iter()
.map(|(k, _v)| k.clone())
.collect::<HashSet<&str>>();
let mut options: Vec<&str> = libraries
.iter()
.filter(|(_k, v)| v.num_parents == 0)
.map(|(k, _v)| *k)
.collect();
let mut sorted: Vec<&str> = Vec::new();
while!options.is_empty() {
let cur = options.pop().unwrap();
for children in libraries
.get_mut(cur)
.unwrap()
.children
.drain(0..)
.collect::<Vec<&str>>()
{
let child = libraries.get_mut(children).unwrap();
child.num_parents -= 1;
if child.num_parents == 0 {
options.push(child.name)
}
}
sorted.push(cur);
needs_processing.remove(cur);
}
match needs_processing.is_empty() {
true => Ok(sorted),
false => Err(format!("Cycle detected among {:?}", needs_processing)),
}
}
fn main() {
let input: Vec<&str> = vec![
"des_system_lib std synopsys std_cell_lib des_system_lib dw02 dw01 ramlib ieee\n",
"dw01 ieee dw01 dware gtech dw04\n",
"dw02 ieee dw02 dware\n",
"dw03 std synopsys dware dw03 dw02 dw01 ieee gtech\n",
"dw04 dw04 ieee dw01 dware gtech\n",
"dw05 dw05 ieee dware\n",
"dw06 dw06 ieee dware\n",
"dw07 ieee dware\n",
"dware ieee dware\n",
"gtech ieee gtech\n",
"ramlib std ieee\n",
"std_cell_lib ieee std_cell_lib\n",
"synopsys\n",
];
let libraries = build_libraries(input);
match topological_sort(libraries) {
Ok(sorted) => println!("{:?}", sorted),
Err(msg) => println!("{:?}", msg),
}
} | 110Topological sort
| 15rust
| rvcg5 |
require 'benchmark'
Benchmark.bm(8) do |x|
x.report() { }
x.report() { (1..1_000_000).inject(4) {|sum, x| sum + x} }
end | 118Time a function
| 14ruby
| mtwyj |
null | 113Tree traversal
| 1lua
| wbgea |
null | 118Time a function
| 15rust
| 9zxmm |
def time(f: => Unit)={
val s = System.currentTimeMillis
f
System.currentTimeMillis - s
} | 118Time a function
| 16scala
| 2y0lb |
let libs = [
("des_system_lib", ["std", "synopsys", "std_cell_lib", "des_system_lib", "dw02", "dw01", "ramlib", "ieee"]),
("dw01", ["ieee", "dw01", "dware", "gtech"]),
("dw02", ["ieee", "dw02", "dware"]),
("dw03", ["std", "synopsys", "dware", "dw03", "dw02", "dw01", "ieee", "gtech"]),
("dw04", ["dw04", "ieee", "dw01", "dware", "gtech"]),
("dw05", ["dw05", "ieee", "dware"]),
("dw06", ["dw06", "ieee", "dware"]),
("dw07", ["ieee", "dware"]),
("dware", ["ieee", "dware"]),
("gtech", ["ieee", "gtech"]),
("ramlib", ["std", "ieee"]),
("std_cell_lib", ["ieee", "std_cell_lib"]),
("synopsys", [])
]
struct Library {
var name: String
var children: [String]
var numParents: Int
}
func buildLibraries(_ input: [(String, [String])]) -> [String: Library] {
var libraries = [String: Library]()
for (name, parents) in input {
var numParents = 0
for parent in parents where parent!= name {
numParents += 1
libraries[parent, default: Library(name: parent, children: [], numParents: 0)].children.append(name)
}
libraries[name, default: Library(name: name, children: [], numParents: numParents)].numParents = numParents
}
return libraries
}
func topologicalSort(libs: [String: Library]) -> [String]? {
var libs = libs
var needsProcessing = Set(libs.keys)
var options = libs.compactMap({ $0.value.numParents == 0? $0.key: nil })
var sorted = [String]()
while let cur = options.popLast() {
for children in libs[cur]?.children?? [] {
libs[children]?.numParents -= 1
if libs[children]?.numParents == 0 {
options.append(libs[children]!.name)
}
}
libs[cur]?.children.removeAll()
sorted.append(cur)
needsProcessing.remove(cur)
}
guard needsProcessing.isEmpty else {
return nil
}
return sorted
}
print(topologicalSort(libs: buildLibraries(libs))!) | 110Topological sort
| 17swift
| 4lm5g |
import Foundation
public struct TimeResult {
public var seconds: Double
public var nanoSeconds: Double
public var duration: Double { seconds + (nanoSeconds / 1e9) }
@usableFromInline
init(seconds: Double, nanoSeconds: Double) {
self.seconds = seconds
self.nanoSeconds = nanoSeconds
}
}
extension TimeResult: CustomStringConvertible {
public var description: String {
return "TimeResult(seconds: \(seconds); nanoSeconds: \(nanoSeconds); duration: \(duration)s)"
}
}
public struct ClockTimer {
@inlinable @inline(__always)
public static func time<T>(_ f: () throws -> T) rethrows -> (T, TimeResult) {
var tsi = timespec()
var tsf = timespec()
clock_gettime(CLOCK_MONOTONIC_RAW, &tsi)
let res = try f()
clock_gettime(CLOCK_MONOTONIC_RAW, &tsf)
let secondsElapsed = difftime(tsf.tv_sec, tsi.tv_sec)
let nanoSecondsElapsed = Double(tsf.tv_nsec - tsi.tv_nsec)
return (res, TimeResult(seconds: secondsElapsed, nanoSeconds: nanoSecondsElapsed))
}
}
func ackermann(m: Int, n: Int) -> Int {
switch (m, n) {
case (0, _):
return n + 1
case (_, 0):
return ackermann(m: m - 1, n: 1)
case (_, _):
return ackermann(m: m - 1, n: ackermann(m: m, n: n - 1))
}
}
let (n, t) = ClockTimer.time { ackermann(m: 3, n: 11) }
print("Took \(t.duration)s to calculate ackermann(m: 3, n: 11) = \(n)")
let (n2, t2) = ClockTimer.time { ackermann(m: 4, n: 1) }
print("Took \(t2.duration)s to calculate ackermann(m: 4, n: 1) = \(n2)") | 118Time a function
| 17swift
| yfe6e |
sub zip {
my @a = @{shift()};
my @b = @{shift()};
my @l;
push @l, shift @a, shift @b while @a and @b;
return @l;
}
sub uniq {
my %h;
grep {!$h{$_}++} @_;
}
my @data =
map {{ zip [qw(name id salary dept)], [split ','] }}
split "\n",
<<'EOF';
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
my $N = shift || 3;
foreach my $d (uniq sort map {$_->{dept}} @data) {
print "$d\n";
my @es =
sort {$b->{salary} <=> $a->{salary}}
grep {$_->{dept} eq $d}
@data;
foreach (1 .. $N) {
@es or last;
my $e = shift @es;
printf "%-15s |%-6s |%5d\n", @{$e}{qw(name id salary)};
}
print "\n";
} | 115Top rank per group
| 2perl
| brck4 |
use warnings;
use strict;
my $initial = join ",", qw(abc def ghi);
my %reverse = qw(X O O X);
my %cache;
sub best_move {
my ($b, $me) = @_;
if( exists $cache{$b,$me,wantarray} ) {
return $cache{$b,$me,wantarray};
} elsif( my $s = score( $b, $me ) ) {
return $cache{$b,$me,wantarray} = (wantarray ? undef : $s);
}
my $him = $reverse{$me};
my ($best, @best) = (-999);
for my $m (moves($b)) {
(my $with_m = $b) =~ s/$m/$me/ or die;
my $s = -(score($with_m, $him) || best_move($with_m, $him));
if( $s > $best ) {
($best, @best) = ($s, $m);
} elsif( $s == $best ) {
push @best, $m;
}
}
$cache{$b,$me,wantarray} = wantarray ? $best[rand @best] : $best;
}
my $winner = q[([XOxo])(?:\1\1|...\1...\1|..\1..\1|....\1....\1)];
sub score {
my ($b, $me) = @_;
$b =~ m/$winner/o or return 0;
return $1 eq $me ? +1 : -1;
}
sub moves {
my ($b) = @_;
$b =~ /([^xoXO,\n])/g;
}
sub print_board {
my ($b) = @_;
$b =~ s/\B/|/g;
$b =~ s/,/\n-+-+-\n/g;
print $b, "\n";
}
sub prompt {
my ($b, $color) = @_;
my @moves = moves($b);
unless( @moves ) {
return;
}
while( 1 ) {
print "Place your $color on one of [@moves]: ";
defined(my $m = <>) or return;
chomp($m);
return $m if grep $m eq $_, @moves;
}
}
my @players = (
{ whose => "your", name => "You",
verb => "You place", get_move => \&prompt },
{ whose => "the computer's", name => "Computer",
verb => "The computer places", get_move => \&best_move },
);
my $whose_turn = int rand 2;
my $color = "X";
my $b = $initial;
while( 1 ) {
my $p = $players[$whose_turn];
print_board($b);
print "It is $p->{whose} turn.\n";
my ( $m ) = $p->{get_move}->($b, $color);
if( $m ) {
print "$p->{verb} an $color at $m\n";
$b =~ s/$m/$color/;
my $s = score($b, $color) or next;
print_board($b);
print "$p->{name} ", $s > 0 ? "won!\n" : "lost!\n";
} else {
print "$p->{name} cannot move.\n";
}
print "Game over.\nNew Game...\n";
($b, $color, $whose_turn) = ($initial, "X", int rand 2);
redo;
} continue {
$color = $reverse{$color};
$whose_turn = !$whose_turn;
} | 117Tic-tac-toe
| 2perl
| nshiw |
$data = Array(
Array(,,32000,),
Array(,,47000,),
Array(,,53500,),
Array(,,18000,),
Array(,,27800,),
Array(,,41500,),
Array(,,49500,),
Array(,,21900,),
Array(,,15900,),
Array(,,19250,),
Array(,,27000,),
Array(,,57000,),
Array(,,29900,)
);
function top_sal($num){
global $data;
$depts = Array();
foreach($data as $key => $arr){
if(!isset($depts[$arr[3]])) $depts[$arr[3]] = Array();
$depts[$arr[3]][] = $key;
}
function topsalsort($a,$b){
global $data;
if ($data[$a][2] == $data[$b][2]) {
return 0;
}
return ($data[$a][2] < $data[$b][2])? 1 : -1;
}
foreach ($depts as $key => $val){
usort($depts[$key],);
}
ksort($depts);
echo '<pre>';
foreach ($depts as $key => $val){
echo $key . '<br>';
echo 'Name ID Salary<br>';
$count = 0;
foreach($val as $value){
echo $data[$value][0] . ' ' . $data[$value][1] . ' ' . $data[$value][2] . '<br>';
$count++;
if($count>=$num) break;
}
echo '<br>';
}
echo '</pre>';
}
top_sal(3); | 115Top rank per group
| 12php
| 6dx3g |
use Math::Trig;
my $angle_degrees = 45;
my $angle_radians = pi / 4;
print sin($angle_radians), ' ', sin(deg2rad($angle_degrees)), "\n";
print cos($angle_radians), ' ', cos(deg2rad($angle_degrees)), "\n";
print tan($angle_radians), ' ', tan(deg2rad($angle_degrees)), "\n";
print cot($angle_radians), ' ', cot(deg2rad($angle_degrees)), "\n";
my $asin = asin(sin($angle_radians));
print $asin, ' ', rad2deg($asin), "\n";
my $acos = acos(cos($angle_radians));
print $acos, ' ', rad2deg($acos), "\n";
my $atan = atan(tan($angle_radians));
print $atan, ' ', rad2deg($atan), "\n";
my $acot = acot(cot($angle_radians));
print $acot, ' ', rad2deg($acot), "\n"; | 111Trigonometric functions
| 2perl
| 5c6u2 |
<?php
const BOARD_NUM = 9;
const ROW_NUM = 3;
$EMPTY_BOARD_STR = str_repeat('.', BOARD_NUM);
function isGameOver($board, $pin) {
$pat =
'/X{3}|' .
'X..X..X..|' .
'.X..X..X.|' .
'..X..X..X|' .
'..X.X.X..|' .
'X...X...X|' .
'[^\.]{9}/i';
if ($pin == 'O') $pat = str_replace('X', 'O', $pat);
return preg_match($pat, $board);
}
$boardStr = isset($_GET['b'])? $_GET['b'] : $EMPTY_BOARD_STR;
$turn = substr_count($boardStr, '.')%2==0? 'O' : 'X';
$oppTurn = $turn == 'X'? 'O' : 'X';
$gameOver = isGameOver($boardStr, $oppTurn);
echo '<style>';
echo 'td {width: 200px; height: 200px; text-align: center; }';
echo '.pin {font-size:72pt; text-decoration:none; color: black}';
echo '.pin.X {color:red}';
echo '.pin.O {color:blue}';
echo '</style>';
echo '<table border=>';
$p = 0;
for ($r = 0; $r < ROW_NUM; $r++) {
echo '<tr>';
for ($c = 0; $c < ROW_NUM; $c++) {
$pin = $boardStr[$p];
echo '<td>';
if ($gameOver || $pin != '.') echo '<span class=>', $pin, '</span>';
else {
$boardDelta = $boardStr;
$boardDelta[$p] = $turn;
echo '<a class= href=>';
echo $boardStr[$p];
echo '</a>';
}
echo '</td>';
$p++;
}
echo '</tr>';
echo '<input type= name= value=/>';
}
echo '</table>';
echo '<a href=>Reset</a>';
if ($gameOver) echo '<h1>Game Over!</h1>'; | 117Tic-tac-toe
| 12php
| 7uzrp |
$radians = M_PI / 4;
$degrees = 45 * M_PI / 180;
echo sin($radians) . . sin($degrees);
echo cos($radians) . . cos($degrees);
echo tan($radians) . . tan($degrees);
echo asin(sin($radians)) . . asin(sin($radians)) * 180 / M_PI;
echo acos(cos($radians)) . . acos(cos($radians)) * 180 / M_PI;
echo atan(tan($radians)) . . atan(tan($radians)) * 180 / M_PI; | 111Trigonometric functions
| 12php
| ox185 |
package main
import "fmt" | 119Towers of Hanoi
| 0go
| 9zwmt |
'''
Tic-tac-toe game player.
Input the index of where you wish to place your mark at your turn.
'''
import random
board = list('123456789')
wins = ((0,1,2), (3,4,5), (6,7,8),
(0,3,6), (1,4,7), (2,5,8),
(0,4,8), (2,4,6))
def printboard():
print('\n'.join(' '.join(board[x:x+3]) for x in(0,3,6)))
def score():
for w in wins:
b = board[w[0]]
if b in 'XO' and all (board[i] == b for i in w):
return b, [i+1 for i in w]
return None, None
def finished():
return all (b in 'XO' for b in board)
def space():
return [ b for b in board if b not in 'XO']
def my_turn(xo):
options = space()
choice = random.choice(options)
board[int(choice)-1] = xo
return choice
def your_turn(xo):
options = space()
while True:
choice = input(
% (xo, ''.join(options))).strip()
if choice in options:
break
print( )
board[int(choice)-1] = xo
return choice
def me(xo='X'):
printboard()
print('I go at', my_turn(xo))
return score()
assert not s[0], % s
def you(xo='O'):
printboard()
print('You went at', your_turn(xo))
return score()
assert not s[0], % s
print(__doc__)
while not finished():
s = me('X')
if s[0]:
printboard()
print(% s)
break
if not finished():
s = you('O')
if s[0]:
printboard()
print(% s)
break
else:
print('\nA draw') | 117Tic-tac-toe
| 3python
| d0kn1 |
def tail = { list, n -> def m = list.size(); list.subList([m - n, 0].max(),m) }
final STACK = [A:[],B:[],C:[]].asImmutable()
def report = { it -> }
def check = { it -> }
def moveRing = { from, to -> to << from.pop(); report(); check(to) }
def moveStack
moveStack = { from, to, using = STACK.values().find { !(it.is(from) || it.is(to)) } ->
if (!from) return
def n = from.size()
moveStack(tail(from, n-1), using, to)
moveRing(from, to)
moveStack(tail(using, n-1), to, from)
} | 119Towers of Hanoi
| 7groovy
| zibt5 |
sub preorder
{
my $t = shift or return ();
return ($t->[0], preorder($t->[1]), preorder($t->[2]));
}
sub inorder
{
my $t = shift or return ();
return (inorder($t->[1]), $t->[0], inorder($t->[2]));
}
sub postorder
{
my $t = shift or return ();
return (postorder($t->[1]), postorder($t->[2]), $t->[0]);
}
sub depth
{
my @ret;
my @a = ($_[0]);
while (@a) {
my $v = shift @a or next;
push @ret, $v->[0];
push @a, @{$v}[1,2];
}
return @ret;
}
my $x = [1,[2,[4,[7]],[5]],[3,[6,[8],[9]]]];
print "pre: @{[preorder($x)]}\n";
print "in: @{[inorder($x)]}\n";
print "post: @{[postorder($x)]}\n";
print "depth: @{[depth($x)]}\n"; | 113Tree traversal
| 2perl
| c3i9a |
rm(list=ls())
library(RColorBrewer)
tic.tac.toe <- function(name="Name", mode=0, type=0){
place.na <<- matrix(1:9, 3, 3)
value <<- matrix(-3, 3, 3)
k <<- 1; r <<- 0
image(1:3, 1:3, matrix(sample(9), 3, 3), asp=c(1, 1),
xaxt="n", yaxt="n", xlab="", ylab="", frame=F, col=brewer.pal(9, "Set3"))
segments(c(0.5,0.5,1.5,2.5), c(2.5,1.5,0.5,0.5),
c(3.5,3.5,1.5,2.5), c(2.5,1.5,3.5,3.5), lwd=8, col=gray(0.3))
segments(c(0.5,0.5,0.5,3.5), c(0.52,3.47,0.5,0.5),
c(3.5,3.5,0.5,3.5), c(0.52,3.47,3.5,3.5), lwd=8, col=gray(0.3))
if(mode==0) title(list(paste(name, "'s Tic-Tac-Toe!"), cex=2),
"2P: Human v.s. Human", font.sub=2, cex.sub=2)
if(mode==1) title(list(paste(name, "'s Tic-Tac-Toe!"), cex=2),
"1P: Human v.s. AI (Easy)", font.sub=2, cex.sub=2)
if(mode==2) title(list(paste(name, "'s Tic-Tac-Toe!"), cex=2),
"1P: Human v.s. AI (Hard)", font.sub=2, cex.sub=2)
if(type==0){symbol <- "O"; symbol.op <- "X"}
if(type==1){symbol <- "X"; symbol.op <- "O"}
out <- list(name=name, mode=mode, type=type, symbol=symbol, symbol.op=symbol.op)
}
isGameOver <- function(){
for(i in 1:3){
total.1 <- 0; total.2 <- 0
for(j in 1:3){
total.1 <- total.1 + value[i, j]
total.2 <- total.2 + value[j, i]
}
if(total.1==0 | total.2==0 | total.1==3 | total.2==3){
break
}
}
total.3 <- value[1, 1] + value[2, 2] + value[3, 3]
total.4 <- value[1, 3] + value[2, 2] + value[3, 1]
if(total.1==0 | total.2==0 | total.3==0 | total.4==0 | total.1==3 | total.2==3 | total.3==3 | total.4==3){
place.na[!is.na(place.na)] <<- NA
if(total.1==0 | total.2==0 | total.3==0 | total.4==0){
title(sub=list(""You Won?! That's a first!", col="red", font=2, cex=2.5), line=2)
}else{
title(sub=list("You Don't Get Tired of Losing?!", col="darkblue", font=2, cex=2.5), line=2)
}
}
if(all(is.na(place.na))){
if(total.1==0 | total.2==0 | total.3==0 | total.4==0 | total.1==3 | total.2==3 | total.3==3 | total.4==3){
if(total.1==0 | total.2==0 | total.3==0 | total.4==0){
title(sub=list("You Won! Pigs Must Be Flying!", col="orange", font=2, cex=2.5), line=2)
}else{
title(sub=list("You Lost ... Once Again!", col="darkblue", font=2, cex=2.5), line=2)
}
}else{
title(sub=list("A measly tie! Try Again", col="blue", font=2, cex=2.5), line=2)
}
}
}
attack <- function(){
for(i in 1:3){
total.1 <- 0; total.2 <- 0
for(j in 1:3){
total.1 <- total.1 + value[i, j]
total.2 <- total.2 + value[j, i]
}
if(total.1==-1 | total.2==-1){
break
}
}
total.3 <- value[1, 1] + value[2, 2] + value[3, 3]
total.4 <- value[1, 3] + value[2, 2] + value[3, 1]
if(total.1==-1){
text(i, which(value[i,]!=1), symbol.op, cex=6, font=2)
place.na[i, which(value[i,]!=1)] <<- NA
value[i, which(value[i,]!=1)] <<- 1
}else if(total.2==-1){
text(which(value[,i]!=1), i, symbol.op, cex=6, font=2)
place.na[which(value[,i]!=1), i] <<- NA
value[which(value[,i]!=1), i] <<- 1
}else if(total.3==-1){
r.1 <- which(c(value[1, 1], value[2, 2], value[3, 3])!=1)
text(r.1, r.1, symbol.op, cex=6, font=2)
place.na[r.1, r.1] <<- NA
value[r.1, r.1] <<- 1
}else if(total.4==-1){
r.2 <- which(c(value[1, 3], value[2, 2], value[3, 1])!=1)
text(r.2, -r.2+4, symbol.op, cex=6, font=2)
place.na[r.2, -r.2+4] <<- NA
value[r.2, -r.2+4] <<- 1
}
}
defend <- function(){
for(i in 1:3){
total.1 <- 0; total.2 <- 0
for(j in 1:3){
total.1 <- total.1 + value[i, j]
total.2 <- total.2 + value[j, i]
}
if(total.1==-3 | total.2==-3){
break
}
}
total.3 <- value[1, 1] + value[2, 2] + value[3, 3]
total.4 <- value[1, 3] + value[2, 2] + value[3, 1]
if(total.1==-3){
text(i, which(value[i,]!=0), symbol.op, cex=6, font=2)
place.na[i, which(value[i,]!=0)] <<- NA
value[i, which(value[i,]!=0)] <<- 1
}else if(total.2==-3){
text(which(value[,i]!=0), i, symbol.op, cex=6, font=2)
place.na[which(value[,i]!=0), i] <<- NA
value[which(value[,i]!=0), i] <<- 1
}else if(total.3==-3){
r.1 <- which(c(value[1, 1], value[2, 2], value[3, 3])!=0)
text(r.1, r.1, symbol.op, cex=6, font=2)
place.na[r.1, r.1] <<- NA
value[r.1, r.1] <<- 1
}else if(total.4==-3){
r.2 <- which(c(value[1, 3], value[2, 2], value[3, 1])!=0)
text(r.2, -r.2+4, symbol.op, cex=6, font=2)
place.na[r.2, -r.2+4] <<- NA
value[r.2, -r.2+4] <<- 1
}else{
rn <- sample(place.na[!is.na(place.na)], 1)
text(rn-3*rn%/%3.5, rn%/%3.5+1, symbol.op, cex=6, font=2)
place.na[rn-3*rn%/%3.5, rn%/%3.5+1] <<- NA
value[rn-3*rn%/%3.5, rn%/%3.5+1] <<- 1
}
}
aim <- function(x, y, tic.tac.toe=ttt){
mode <- tic.tac.toe$mode
symbol <<- tic.tac.toe$symbol
symbol.op <<- tic.tac.toe$symbol.op
x <<- x; y <<- y
if(mode==0){
turn <- rep(c(0, 1), length.out=9)
if(is.na(place.na[x, y])){
cat("This square is taken!")
}else{
if(turn[k]==0){
text(x, y, symbol, cex=6, font=2)
place.na[x, y] <<- NA
value[x, y] <<- 0
}
if(turn[k]==1){
text(x, y, symbol.op, cex=6, font=2)
place.na[x, y] <<- NA
value[x, y] <<- 1
}
k <<- k + 1
}
}
if(mode==1){
if(is.na(place.na[x, y])){
cat("This square had been chosen!")
}else{
text(x, y, symbol, cex=6, font=2)
place.na[x, y] <<- NA
value[x, y] <<- 0
isGameOver()
for(i in 1:3){
total.1 <- 0; total.2 <- 0
for(j in 1:3){
total.1 <- total.1 + value[i, j]
total.2 <- total.2 + value[j, i]
}
if(total.1==-1 | total.2==-1){
break
}
}
total.3 <- value[1, 1] + value[2, 2] + value[3, 3]
total.4 <- value[1, 3] + value[2, 2] + value[3, 1]
if(all(is.na(place.na))){
isGameOver()
}else if(total.1==-1 | total.2==-1 | total.3==-1 | total.4==-1){
attack()
}else{
defend()
}
}
}
if(mode==2){
if(is.na(place.na[x, y])){
cat("This square is taken!")
}else{
if(sum(is.na(place.na))==0){
text(x, y, symbol, cex=6, font=2)
place.na[x, y] <<- NA
value[x, y] <<- 0
if(is.na(place.na[2, 2])==F){
text(2, 2, symbol.op, cex=6, font=2)
place.na[2, 2] <<- NA
value[2, 2] <<- 1
}else{
corner.1 <- sample(c(1, 3), 1); corner.2 <- sample(c(1, 3), 1)
text(corner.1, corner.2, symbol.op, cex=6, font=2)
place.na[corner.1, corner.2] <<- NA
value[corner.1, corner.2] <<- 1
}
}else if(sum(is.na(place.na))==2){
text(x, y, symbol, cex=6, font=2)
place.na[x, y] <<- NA
value[x, y] <<- 0
for(i in 1:3){
total.1 <- 0; total.2 <- 0
for(j in 1:3){
total.1 <- total.1 + value[i, j]
total.2 <- total.2 + value[j, i]
}
if(total.1==-3 | total.2==-3){
break
}
}
total.3 <- value[1, 1] + value[2, 2] + value[3, 3]
total.4 <- value[1, 3] + value[2, 2] + value[3, 1]
if(total.1==-3 | total.2==-3 | total.3==-3 | total.4==-3){
defend()
}else{
total.1 <- value[2, 1] + value[2, 2] + value[2, 3]
total.2 <- value[1, 2] + value[2, 2] + value[3, 2]
total.3 <- value[1, 1] + value[2, 2] + value[3, 3]
total.4 <- value[1, 3] + value[2, 2] + value[3, 1]
if(total.1==1 | total.2==1 | total.3==1 | total.4==1){
if((value[2, 2]==1 & total.3==1) | (value[2, 2]==1 & total.4==1)){
vector.side <- c(place.na[2, 1], place.na[1, 2], place.na[3, 2], place.na[2, 3])
rn <- sample(vector.side[!is.na(vector.side)], 1)
text(rn-3*rn%/%3.5, rn%/%3.5+1, symbol.op, cex=6, font=2)
place.na[rn-3*rn%/%3.5, rn%/%3.5+1] <<- NA
value[rn-3*rn%/%3.5, rn%/%3.5+1] <<- 1
}else{
matrix.cor <- place.na[c(1, 3), c(1, 3)]
rn <- sample(matrix.cor[!is.na(matrix.cor)], 1)
text(rn-3*rn%/%3.5, rn%/%3.5+1, symbol.op, cex=6, font=2)
place.na[rn-3*rn%/%3.5, rn%/%3.5+1] <<- NA
value[rn-3*rn%/%3.5, rn%/%3.5+1] <<- 1
}
}else{
if((x==1 & y==2) | (x==3 & y==2)){
rn <- sample(c(1, 3), 1)
text(x, rn, symbol.op, cex=6, font=2)
place.na[x, rn] <<- NA
value[x, rn] <<- 1
}else if((x==2 & y==3) | (x==2 & y==1)){
rn <- sample(c(1, 3), 1)
text(rn, y, symbol.op, cex=6, font=2)
place.na[rn, y] <<- NA
value[rn, y] <<- 1
}else if((x==1 & y==1) | (x==1 & y==3) | (x==3 & y==1) | (x==3 & y==3)){
text(-x+4, -y+4, symbol.op, cex=6, font=2)
place.na[-x+4, -y+4] <<- NA
value[-x+4, -y+4] <<- 1
}
}
}
}else{
text(x, y, symbol, cex=6, font=2)
place.na[x, y] <<- NA
value[x, y] <<- 0
isGameOver()
for(i in 1:3){
total.1 <- 0; total.2 <- 0
for(j in 1:3){
total.1 <- total.1 + value[i, j]
total.2 <- total.2 + value[j, i]
}
if(total.1==-1 | total.2==-1){
break
}
}
total.3 <- value[1, 1] + value[2, 2] + value[3, 3]
total.4 <- value[1, 3] + value[2, 2] + value[3, 1]
if(all(is.na(place.na))){
isGameOver()
}else if(total.1==-1 | total.2==-1 | total.3==-1 | total.4==-1){
attack()
}else{
defend()
}
}
}
}
isGameOver()
}
click <- function(tic.tac.toe=ttt){
name <- tic.tac.toe$name
mode <- tic.tac.toe$mode
type <- tic.tac.toe$type
while(length(place.na)==9){
mouse.at <- locator(n = 1, type = "n")
x.at <- round(mouse.at$x)
y.at <- round(mouse.at$y)
if(all(is.na(place.na))){
ttt <<- tic.tac.toe(name, mode, type)
}else if(x.at > 3.5 | x.at < 0.5 | y.at > 3.5 | y.at < 0.5){
r <<- r + 1
title(sub=list("Click outside:Quit / inside:Restart", col="deeppink", font=2, cex=2), line=2)
if(r==2){
dev.off()
break
}
}else{
if(r==1){
ttt <<- tic.tac.toe(name, mode, type)
}else{
aim(x.at, y.at)
}
}
}
}
start <- function(name="Name", mode=0, type=0){
x11()
ttt <<- tic.tac.toe(name, mode, type)
click()
} | 117Tic-tac-toe
| 13r
| 8wr0x |
hanoi :: Integer -> a -> a -> a -> [(a, a)]
hanoi 0 _ _ _ = []
hanoi n a b c = hanoi (n-1) a c b ++ [(a,b)] ++ hanoi (n-1) c b a | 119Towers of Hanoi
| 8haskell
| br6k2 |
class Node {
private $left;
private $right;
private $value;
function __construct($value) {
$this->value = $value;
}
public function getLeft() {
return $this->left;
}
public function getRight() {
return $this->right;
}
public function getValue() {
return $this->value;
}
public function setLeft($value) {
$this->left = $value;
}
public function setRight($value) {
$this->right = $value;
}
public function setValue($value) {
$this->value = $value;
}
}
class TreeTraversal {
public function preOrder(Node $n) {
echo $n->getValue() . ;
if($n->getLeft() != null) {
$this->preOrder($n->getLeft());
}
if($n->getRight() != null){
$this->preOrder($n->getRight());
}
}
public function inOrder(Node $n) {
if($n->getLeft() != null) {
$this->inOrder($n->getLeft());
}
echo $n->getValue() . ;
if($n->getRight() != null){
$this->inOrder($n->getRight());
}
}
public function postOrder(Node $n) {
if($n->getLeft() != null) {
$this->postOrder($n->getLeft());
}
if($n->getRight() != null){
$this->postOrder($n->getRight());
}
echo $n->getValue() . ;
}
public function levelOrder($arg) {
$q[] = $arg;
while (!empty($q)) {
$n = array_shift($q);
echo $n->getValue() . ;
if($n->getLeft() != null) {
$q[] = $n->getLeft();
}
if($n->getRight() != null){
$q[] = $n->getRight();
}
}
}
}
$arr = [];
for ($i=1; $i < 10; $i++) {
$arr[$i] = new Node($i);
}
$arr[6]->setLeft($arr[8]);
$arr[6]->setRight($arr[9]);
$arr[3]->setLeft($arr[6]);
$arr[4]->setLeft($arr[7]);
$arr[2]->setLeft($arr[4]);
$arr[2]->setRight($arr[5]);
$arr[1]->setLeft($arr[2]);
$arr[1]->setRight($arr[3]);
$tree = new TreeTraversal($arr);
echo ;
$tree->preOrder($arr[1]);
echo ;
$tree->inOrder($arr[1]);
echo ;
$tree->postOrder($arr[1]);
echo ;
$tree->levelOrder($arr[1]); | 113Tree traversal
| 12php
| xprw5 |
print join('.', split /,/, 'Hello,How,Are,You,Today'), "\n"; | 116Tokenize a string
| 2perl
| 6dw36 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.