Skip to content

Instantly share code, notes, and snippets.

@reimai
Last active October 30, 2016 00:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reimai/7269592ab4e705f990428ac21819f2d3 to your computer and use it in GitHub Desktop.
Save reimai/7269592ab4e705f990428ac21819f2d3 to your computer and use it in GitHub Desktop.
comparing haskell with scala on a hackerrank quiz (not only haskell is better looking, it's much faster, yes, I've used List in scala to make it haskell-like); quiz: https://www.hackerrank.com/challenges/john-and-fences
module Main where
main :: IO()
main = getContents >>= putStrLn. show. maxFence 0. map (read:: String -> Int). words. last. lines
type Fence = [Int]
maxFence :: Int -> Fence -> Int
maxFence base [] = base
maxFence base [spike] = base + spike
maxFence base fence = foldl max ((base+toCut)*(length fence)) $ map (maxFence $ base+toCut) $ cutBottom fence toCut
where toCut = foldl1 min fence
cutBottom :: Fence -> Int -> [Fence]
cutBottom fence toCut = lastFence:fences
where (fences, lastFence) = foldl cut ([[]],[]) fence
cut (acc, fnc) board | board == toCut = (fnc:acc, [])
| otherwise = (acc, board-toCut:fnc)
package rei
import scala.io.StdIn.readLine
object Fences {
def main(args: Array[String]) {
readLine()
val fence = readLine().split(" ").map(_.toInt).toList
println(maxFence(0)(fence))
}
type Fence = List[Int]
def maxFence(base: Int)(fence: Fence): Int = fence match {
case Nil => base
case spike :: Nil => base + spike
case _ =>
val toCut = fence.min
cutBottom(fence, toCut).map(maxFence(base+toCut)).foldLeft((base + toCut) * fence.length)(Math.max)
}
def cutBottom(fence: Fence, toCut: Int): List[Fence] = {
val (fences, lastFence) = fence.foldLeft((List[Fence](), List[Int]())) { case ((acc, fnc), board) => board - toCut match {
case 0 => (fnc :: acc, Nil)
case x => (acc, x :: fnc)
}}
lastFence::fences
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment