Add tasks for all the new languages

This commit is contained in:
Tina Müller 2016-12-05 23:44:36 +01:00
parent 9dc3c2bb62
commit bba7bfd280
13208 changed files with 134745 additions and 0 deletions

View file

@ -0,0 +1,44 @@
import ceylon.collection {
ArrayList
}
shared void run() {
value ops = map {
"+" -> plus<Float>,
"*" -> times<Float>,
"-" -> ((Float a, Float b) => a - b),
"/" -> ((Float a, Float b) => a / b),
"^" -> ((Float a, Float b) => a ^ b)
};
void printTableRow(String|Float token, String description, {Float*} stack) {
print("``token.string.padTrailing(8)````description.padTrailing(30)````stack``");
}
function calculate(String input) {
value stack = ArrayList<Float>();
value tokens = input.split().map((String element)
=> if(ops.keys.contains(element)) then element else parseFloat(element));
print("Token Operation Stack");
for(token in tokens.coalesced) {
if(is Float token) {
stack.push(token);
printTableRow(token, "push", stack);
} else if(exists op = ops[token], exists first = stack.pop(), exists second = stack.pop()) {
value result = op(second, first);
stack.push(result);
printTableRow(token, "perform ``token`` on ``formatFloat(second, 1, 1)`` and ``formatFloat(first, 1, 1)``", stack);
} else {
throw Exception("bad syntax");
}
}
return stack.pop();
}
print(calculate("3 4 2 * 1 5 - 2 3 ^ ^ / +"));
}

View file

@ -0,0 +1,28 @@
;; RPN (postfix) evaluator
(lib 'hash)
(define OPS (make-hash))
(hash-set OPS "^" expt)
(hash-set OPS "*" *)
(hash-set OPS "/" //) ;; float divide
(hash-set OPS "+" +)
(hash-set OPS "-" -)
(define (op? op) (hash-ref OPS op))
;; algorithm : https://en.wikipedia.org/wiki/Reverse_Polish_notation#Postfix_algorithm
(define (calculator rpn S)
(for ((token rpn))
(if (op? token)
(let [(op2 (pop S)) (op1 (pop S))]
(unless (and op1 op2) (error "cannot calculate expression at:" token))
(push S ((op? token) op1 op2))
(writeln op1 token op2 "→" (stack-top S)))
(push S (string->number token))))
(pop S))
(define (task rpn)
(define S (stack 'S))
(calculator (text-parse rpn) S ))

View file

@ -0,0 +1,19 @@
def evaluate( expr ) =
stack = []
for token <- expr.split( '''\s+''' )
case number( token )
Some( n ) ->
stack = n : stack
println( "push $token: ${stack.reversed()}" )
None ->
case {'+': (+), '-': (-), '*': (*), '/': (/), '^': (^)}.>get( token )
Some( op ) ->
stack = op( stack.tail().head(), stack.head() ) : stack.tail().tail()
println( "perform $token: ${stack.reversed()}" )
None -> error( "unrecognized operator '$token'" )
stack.head()
res = evaluate( '3 4 2 * 1 5 - 2 3 ^ ^ / +' )
println( res + (if res is Integer then '' else " or ${float(res)}") )

View file

@ -0,0 +1,72 @@
import math, rdstdin, strutils, tables
type Stack = seq[float]
proc lalign(s, x): string =
s & repeatChar(x - s.len, ' ')
proc opPow(s: var Stack) =
let b = s.pop
let a = s.pop
s.add a.pow b
proc opMul(s: var Stack) =
let b = s.pop
let a = s.pop
s.add a * b
proc opDiv(s: var Stack) =
let b = s.pop
let a = s.pop
s.add a / b
proc opAdd(s: var Stack) =
let b = s.pop
let a = s.pop
s.add a + b
proc opSub(s: var Stack) =
let b = s.pop
let a = s.pop
s.add a - b
proc opNum(s: var Stack, num) = s.add num
let ops = toTable({"^": opPow,
"*": opMul,
"/": opDiv,
"+": opAdd,
"-": opSub})
proc getInput(inp = ""): seq[string] =
var inp = inp
if inp.len == 0:
inp = readLineFromStdin "Expression: "
result = inp.strip.split
proc rpnCalc(tokens): auto =
var s: Stack = @[]
result = @[@["TOKEN","ACTION","STACK"]]
for token in tokens:
var action = ""
if ops.hasKey token:
action = "Apply op to top of stack"
ops[token](s)
else:
action = "Push num onto top of stack"
s.opNum token.parseFloat
result.add(@[token, action, s.map(proc (x: float): string = $x).join(" ")])
let rpn = "3 4 2 * 1 5 - 2 3 ^ ^ / +"
echo "For RPN expression: ", rpn
let rp = rpnCalc rpn.getInput
var maxColWidths = newSeq[int](rp[0].len)
for i in 0 .. rp[0].high:
for x in rp:
maxColWidths[i] = max(maxColWidths[i], x[i].len)
for x in rp:
for i, y in x:
stdout.write y.lalign(maxColWidths[i]), " "
echo ""

View file

@ -0,0 +1 @@
"3 4 2 * 1 5 - 2 3 ^ ^ / +" eval println

View file

@ -0,0 +1,3 @@
: rpn(s) { s words apply(#[ eval .l ]) }
rpn("3 4 2 * 1 5 - 2 3 ^ ^ / +")

View file

@ -0,0 +1,17 @@
procedure evalRPN(string s)
sequence stack = {}
sequence ops = split(s)
for i=1 to length(ops) do
string op = ops[i]
switch op
case "+": stack[-2] = stack[-2]+stack[-1]; stack = stack[1..-2]
case "-": stack[-2] = stack[-2]-stack[-1]; stack = stack[1..-2]
case "*": stack[-2] = stack[-2]*stack[-1]; stack = stack[1..-2]
case "/": stack[-2] = stack[-2]/stack[-1]; stack = stack[1..-2]
case "^": stack[-2] = power(stack[-2],stack[-1]); stack = stack[1..-2]
default : stack = append(stack,scanf(op,"%d")[1][1])
end switch
?{op,stack}
end for
end procedure
evalRPN("3 4 2 * 1 5 - 2 3 ^ ^ / +")

View file

@ -0,0 +1,33 @@
var proggie = '3 4 2 * 1 5 - 2 3 ^ ^ / +';
class RPN(arr=[]) {
method binop(op) {
var x = arr.pop
var y = arr.pop
arr << y.(op)(x)
}
method run(p) {
p.each_word { |w|
say "#{w} (#{arr})";
given (w) {
when (/\d/) {
arr << w.to_f
}
when (<+ - * />) {
self.binop(w)
}
when ('^') {
self.binop('**')
}
default {
die "#{w} is bogus"
}
}
}
say arr[0]
}
}
RPN.new.run(proggie);

View file

@ -0,0 +1,58 @@
let opa = [
"^": (prec: 4, rAssoc: true),
"*": (prec: 3, rAssoc: false),
"/": (prec: 3, rAssoc: false),
"+": (prec: 2, rAssoc: false),
"-": (prec: 2, rAssoc: false),
]
func rpn(tokens: [String]) -> [String] {
var rpn : [String] = []
var stack : [String] = [] // holds operators and left parenthesis
for tok in tokens {
switch tok {
case "(":
stack += [tok] // push "(" to stack
case ")":
while !stack.isEmpty {
let op = stack.removeLast() // pop item from stack
if op == "(" {
break // discard "("
} else {
rpn += [op] // add operator to result
}
}
default:
if let o1 = opa[tok] { // token is an operator?
for op in stack.reverse() {
if let o2 = opa[op] {
if !(o1.prec > o2.prec || (o1.prec == o2.prec && o1.rAssoc)) {
// top item is an operator that needs to come off
rpn += [stack.removeLast()] // pop and add it to the result
continue
}
}
break
}
stack += [tok] // push operator (the new one) to stack
} else { // token is not an operator
rpn += [tok] // add operand to result
}
}
}
return rpn + stack.reverse()
}
func parseInfix(e: String) -> String {
let tokens = e.characters.split{ $0 == " " }.map(String.init)
return rpn(tokens).joinWithSeparator(" ")
}
var input : String
input = "3 + 4 * 2 / ( 1 - 5 ) ^ 2 ^ 3"
"infix: \(input)"
"postfix: \(parseInfix(input))"