Last active
August 29, 2015 14:27
-
-
Save paulosuzart/0d153740ffd97b0f211a to your computer and use it in GitHub Desktop.
Hacker Rank Goodnode challenge
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.example | |
| import scala.collection.mutable.HashMap | |
| class Node(idx : Int) { | |
| val index = idx | |
| var pointsTo : Option[Node] = None | |
| var walked = false | |
| override def toString() = s"Node - idx: ${this.index}, points to ${this.pointsTo.get.index}." | |
| } | |
| object EndsInBadNode { | |
| def apply(node : Node) = node | |
| def unapply(node : Node) : Option[Node] = { | |
| //println(s"Deep in $node") | |
| if (node.pointsTo.get.index == 0) return None | |
| if (node.index == node.pointsTo.get.index) { | |
| node.walked = false | |
| return Some(node) | |
| } | |
| if (node.pointsTo.get.walked) { | |
| return Some(node) | |
| } | |
| node.walked = true // protects agains dead lock | |
| val bad = node.pointsTo.get match { | |
| case EndsInBadNode(n) => Some(n) | |
| case _ => None | |
| } | |
| node.walked = false | |
| return bad | |
| } | |
| } | |
| object Solution { | |
| var pool = HashMap[Int, Node]() | |
| def init(size : Int) { | |
| // simple clean up | |
| this.moves = 0 | |
| this pool = this.pool.empty | |
| // | |
| for (i <- 0 until size) { | |
| this.pool += (i -> new Node(i)) | |
| } | |
| } | |
| def connect(index : Int, targetIndex : Int) { | |
| this.pool.get(index).map { _.pointsTo = this.pool.get(targetIndex) } | |
| } | |
| var moves : Int = 0 | |
| def solve(n : Node) : Unit = { | |
| n match { | |
| case EndsInBadNode(n) => { | |
| //println(s"Node ${n.index} is dead. Reconnecting...") | |
| this.connect(n.index, 0) | |
| this.moves += 1 | |
| } | |
| case _ => Unit | |
| } | |
| } | |
| def run(values : List[Int]) { | |
| val length = values.length | |
| this.init(length) | |
| values.zipWithIndex foreach { | |
| case (v, i) => this.connect(i, v) | |
| } | |
| for (n <- 0 until length) { | |
| //println(s"Testing : $n") | |
| solve(this.pool(n)) | |
| } | |
| } | |
| def main(args: Array[String]): Unit = { | |
| // my tail node is 0 instead of 1 | |
| run(List(1,2,1)) // -> prints 1 | |
| println(s"Total moves: ${this.moves}") | |
| run(List(1,2,3,2)) // -> prints 1 | |
| println(s"Total moves: ${this.moves}") | |
| run(List(3,0,2,2,4)) //-> prints 2 | |
| println(s"Total moves: ${this.moves}") | |
| run(List(4,4,4,4,4)) //-> prints 1 | |
| println(s"Total moves: ${this.moves}") | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment