0% found this document useful (0 votes)
49 views

Week1 HackerRank

The document discusses Scala code for evaluating mathematical expressions. It defines classes and traits for numbers, binary and unary operators, and methods for parsing an expression string, evaluating subexpressions, and calculating the final result. FastReader and Solution classes are used to read input and solve expressions recursively. Haskell code is provided for mapping operations to numbers in a list and evaluating exponential functions. Ruby code uses lazy evaluation to find the first palindrome prime number. Lambda calculus and functions are also briefly covered.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
49 views

Week1 HackerRank

The document discusses Scala code for evaluating mathematical expressions. It defines classes and traits for numbers, binary and unary operators, and methods for parsing an expression string, evaluating subexpressions, and calculating the final result. FastReader and Solution classes are used to read input and solve expressions recursively. Haskell code is provided for mapping operations to numbers in a list and evaluating exponential functions. Ruby code uses lazy evaluation to find the first palindrome prime number. Lambda calculus and functions are also briefly covered.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

#Scala- Expressions V2

import java.io.{BufferedReader, IOException, InputStreamReader}


import java.util.StringTokenizer

class FastReader() {
val br: BufferedReader = new BufferedReader(new InputStreamReader(System.in))
var st: StringTokenizer = _

def nextInt: Int = next.toInt

def nextLong: Long = next.toLong

def nextDouble: Double = next.toDouble

def next: String = {


while (st == null || !st.hasMoreElements)
try
st = new StringTokenizer(br.readLine)
catch {
case e: IOException =>
e.printStackTrace()
}
st.nextToken
}

def nextLine: String = {


var str = ""
try
str = br.readLine
catch {
case e: IOException =>
e.printStackTrace()
}
str
}
}

trait Expression

object Expression {
val modulo = 1000000007
}

case class Number(value: Int) extends Expression

trait Binary extends Expression {


def eval(a: Int, b: Int): Int
}

trait Additive extends Binary

trait Multiplicative extends Binary

trait Unary extends Expression {


def eval(v: Int): Int
}

case object UnaryAddition extends Unary {


override def eval(v: Int): Int = v
}

case object UnarySubtraction extends Unary {


override def eval(v: Int): Int = -v
}

case object BinaryAddition extends Additive {


override def eval(a: Int, b: Int): Int = Math.floorMod(a.toLong + b,
Expression.modulo).toInt
}

case object BinarySubtraction extends Additive {


override def eval(a: Int, b: Int): Int = Math.floorMod(a.toLong - b,
Expression.modulo).toInt
}

case object Multiplication extends Multiplicative {


override def eval(a: Int, b: Int): Int = Math.floorMod(a.toLong * b,
Expression.modulo).toInt
}

case object Division extends Multiplicative {


override def eval(a: Int, b: Int): Int = {
val bb = BigInt(b).modPow(Expression.modulo - 2, Expression.modulo).toLong
Math.floorMod(a * bb, Expression.modulo).toInt
}
}

object Solution {
def main(args: Array[String]): Unit = {
val sc = new FastReader

val s = sc.nextLine
println(solve(s))
}

def solve(s: String): Int = {


case class State(index: Int = 0, expressions: List[Expression] = Nil,
subexpressions: List[List[Expression]] = Nil)

@scala.annotation.tailrec
def parseNumber(index: Int, number: Int = 0): (Int, Int) = if (index <
s.length) {
val c = s(index)
if (c.isDigit) parseNumber(index + 1, 10 * number + c - '0') else (index,
number)
} else (index, number)

@scala.annotation.tailrec
def eval(expressions: List[Expression]): Int = expressions match {
case Number(b) :: Nil => b
case Number(b) :: (op: Binary) :: Number(a) :: exs => eval(Number(op.eval(a,
b)) :: exs)
case _ => throw new Exception("Wrong expression")
}

@scala.annotation.tailrec
def simplify(expressions: List[Expression]): List[Expression] = expressions
match {
case Number(b) :: (op: Unary) :: exs => simplify(Number(op.eval(b)) :: exs)
case (nextOp: Additive) :: Number(b) :: (op: Multiplicative) :: Number(a) ::
exs =>
simplify(nextOp :: Number(op.eval(a, b)) :: exs)
case exs@_ => exs
}

@scala.annotation.tailrec
def inner(state: State): State = {
def withExpression(expression: Expression): State =
State(state.index + 1, expression :: state.expressions,
state.subexpressions)

if (state.index < s.length) {


val c = s(state.index)
val nextState = c match {
case '(' => State(state.index + 1, Nil, state.expressions ::
state.subexpressions)
case ')' => State(state.index + 1, Number(eval(state.expressions)) ::
state.subexpressions.head, state.subexpressions.tail)
case '+' => withExpression(state.expressions match {
case (_: Number) :: _ => BinaryAddition
case _ => UnaryAddition
})
case '-' => withExpression(state.expressions match {
case (_: Number) :: _ => BinarySubtraction
case _ => UnarySubtraction
})
case '*' => withExpression(Multiplication)
case '/' => withExpression(Division)

case d: Char if d.isDigit =>


val (nextIndex, number) = parseNumber(state.index)
State(nextIndex, Number(number) :: state.expressions,
state.subexpressions)
case _ => state.copy(index = state.index + 1)
}

val nextExpressions = simplify(nextState.expressions)

inner(nextState.copy(expressions = nextExpressions))
} else state
}

eval(inner(State()).expressions)
}
}

#Map and Lambda Functions PYTHON

cube = lambda x: pow(x,3)# complete the lambda function


def fibonacci(n):
# return a list of fibonacci numbers
lis = [0,1]
for i in range(2,n):
lis.append(lis[i-2] + lis[i-1])
return(lis[0:n])

#HASKELL - Expressions

{-# LANGUAGE BangPatterns #-}

import Control.Applicative
import qualified Data.Map as M
import Data.List

main :: IO ()
main = do
n <- readLn :: IO Int
ns <- map read . words <$> getLine
let result = foldl' f (M.fromList [(head ns, "")]) (tail ns)
f !m n = M.fromList $
concatMap (\(val, ops) ->
[ ((val+n)`mod`101, '+':ops)
, ((val-n)`mod`101, '-':ops)
, ((val*n)`mod`101, '*':ops)
]) $
M.toList m
ans = reverse $ result M.! 0
putStrLn $ unwords $ concat $ zipWith (\a b -> [a, b]) (map show ns) (map (\op
-> [op]) $ ans ++ " ")

#HASKELL - Eval e^x


import Control.Applicative
import Control.Monad
import System.IO

eee :: Double -> Double -> Double


eee 1 x = x + 1
eee n x = ((x**n) / (product [1..n])) + (eee (n-1) x)

main :: IO ()
main = do
n_temp <- getLine
let n = read n_temp :: Int
forM_ [1..n] $ \a0 -> do
x_temp <- getLine
let x = read x_temp :: Double
print (eee 9 x)

getMultipleLines :: Int -> IO [String]


getMultipleLines n
| n <= 0 = return []
| otherwise = do
x <- getLine
xs <- getMultipleLines (n-1)
let ret = (x:xs)
return ret

#RUBY - Lazy Evaluation


n = gets.to_i
p Prime.each.lazy.select {|i| i.to_s == i.to_s.reverse}.first(n)

#Lambda Calculus

#Yes the answer is single digit '4'


#Read Question Fella

#Map and Lambda Function - PYTHON

cube = lambda x: x ** 3

def fibonacci(n):
List = [0, 1]
for i in range(2, n):
List.append(List[i-1] + List[i-2])

return(List[0:n])

You might also like