Skip to content

Instantly share code, notes, and snippets.

@zidarsk8
Created April 16, 2013 16:59
Show Gist options
  • Save zidarsk8/5397588 to your computer and use it in GitHub Desktop.
Save zidarsk8/5397588 to your computer and use it in GitHub Desktop.
ugly code
object Tree {
private var current = 0
def inc = { current += 1; current }
def elements = current
}
class Tree {
var root: Node = new Node(Tree.inc)
def inc() {
root.addLast(Tree.inc)
}
def cost() = {
root.cost
}
override def toString() = {
val s = root.toList.map(x => "**" * (root.height - x._1 ) + (Tree.elements - x._2 +1))
s filter { _.nonEmpty } mkString "\n"
}
}
object Node{
private var last:Node = null
}
class Node(var left: Node, var right: Node, var value: Int) {
if (Node.last == null) Node.last = this
def this(el: Int) = this(null, null, el)
def depth():Int = {
if (left != null){
left.depth + 1
}else {
if(right != null) 0 else 1
}
}
def addLast(el: Int) {
if (Node.last.right == null) {
Node.last.right = new Node(Node.last.value)
Node.last.value = el
} else {
Node.last.left = new Node(el)
Node.last = Node.last.left
}
}
def toList(): List[(Int, Int)] = {
toList(0)
}
def rotatedCost(): Int = {
val realVal = Tree.elements - value + 1
val leftside = if (left != null) left.cost + realVal else 0
val rightside= if (right != null) right.cost + realVal else 0
Math.max(leftside, rightside)
}
def cost(): Int = {
val realVal = Tree.elements - value + 1
val leftside = if (left != null) left.cost + realVal else 0
val rightside= if (right != null) right.cost + realVal else 0
Math.max(leftside, rightside)
}
def toList(depth: Int): List[(Int, Int)] = {
val leftside = if (left != null) left.toList(depth + 1) else List()
val rightside = if (right != null) right.toList(depth + 1) else List()
leftside ++ List((depth, value)) ++ rightside
}
def height(): Int ={
val leftside = if (left != null) left.height else 0
val rightside= if (right != null) right.height else 0
Math.max(leftside, rightside)+1
}
def rotateRight() {
if (left != null && left.right != null){
val curl = left
val curval = value
value = left.value
left = left.left
right = new Node(curl.right,right,curval)
}
}
def rotateLeft() {
if (right != null && right.left != null){
val curr = right
val curval = value
value = right.value
right = right.right
left = new Node(left,curr.left,curval)
}
}
override def toString() = {
"val: "+value+" realVal: "+(Tree.elements - value + 1)+" depth: "+depth+" height: "+height+" left:"+(left != null)+" right:"+(right != null)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment