Skip to content

Instantly share code, notes, and snippets.

@salzig
Created April 3, 2012 13:59
Show Gist options
  • Save salzig/2292241 to your computer and use it in GitHub Desktop.
Save salzig/2292241 to your computer and use it in GitHub Desktop.
HAW WP 2012 Scala - Aufgabe 2
package aufgabe2
object App {
def sort[T <% Ordered[T]](arg1:T, arg2:T, args:T*) = (arg1 +: arg2 +: args).sortWith(_<_)
case class PointI(x:Int, y:Int) extends Ordered[PointI] {
def compare(that:PointI):Int = x compare that.x match {
case i if i == 0 => y compare that.y
case i => i
}
}
case class PointD(x:Double, y:Double) extends Ordered[PointD] {
def compare(that:PointD):Int = x compare that.x match {
case i if i == 0 => y compare that.y
case i => i
}
}
def test01 {
println(sort(1,2,-1,0,3,2))
// println(sort(PointI(1,2))) // <-- Mag der Compiler nicht
println(sort(PointD(1,2), PointD(1,3),PointD(1,2),PointD(0,10),PointD(4,-10)))
}
def test02 {
val sLst = List("Hallo","Welt")
println(sLst.flatten)
}
def rle1(bytes:Array[Byte]):List[(Byte,Int)] = {
// Wenn item == letztem item -> letztes tuple neu bauen.
//
// Head can leer sein, ein Problem. -> Umkehren
//bytes.foldLeft(List[(Byte,Int)]())((accu, item) => item match {
// case b if b == accu.head._1 => (b,accu.head._2 +1) +: accu.tail
// case b => accu
//})
if (bytes != null) {
bytes.foldLeft(List[(Byte,Int)]())((accu, item) => accu match {
// gegeben der Accu besteht aus (l,c)::tail und last == item
case (last,count)::tail if item == last => (item,count +1)::tail
case _ => (item,1)::accu
}).reverse
}
else {
List[(Byte,Int)]()
}
}
def rle2(array:Array[Byte]):List[Int] = {
rle1(array) match {
case (byte,count)::tail => byte.toInt +: count +: tail.map(_._2)
case r => List()
}
}
def test03 {
val bArr1= Array[Byte](0,0,0,1,1,0,1)
val bArr2= Array[Byte](1,1,0,1,0,0,0,0,1,1,0,1,1,1,1,1)
println(rle1(bArr1)) // → List((0,3), (1,2), (0,1), (1,1))
println(rle2(bArr1)) // → List(0, 3, 2, 1, 1)
println(rle1(bArr2)) // → List((1,2), (0,1), (1,1), (0,4), (1,2), (0,1), (1,5))
println(rle2(bArr2)) // → List(1, 2, 1, 1, 4, 2, 1, 5)
// die folgenden Ausgaben sind alle: List()
println(rle1(Array[Byte]()))
println(rle2(Array[Byte]()))
println(rle1(null))
println(rle2(null))
}
case class Position(x:Int=0,y:Int=0) {
require(x >= 0 && y >= 0, "x und y müssen größer/gleich Null sein!")
}
def test04 {
println(Position(3,4))
val p1= Position()
println(p1.x +","+p1.y)
val p2= Position(3)
println(p2.x +","+p2.y)
// println(Position(-1,4)) // -> Java.lang.IllegalArgumentException: requirement failed: x und y muessen groeer/gleich Null sein!
}
def main(args:Array[String]) {
test01
test02
test03
test04
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment