// Exercise 1 // // usage example: // scala hw1ex1 56 2 75 10 89 88 35 0 // object hw1ex1 { // // selectionSort // // Sorts an array of integers using selection sort. // def selectionSort(a:Array[Int]):Unit = { val n:Int = a length; for (i <- 0 to (n-1)) { var min = a(i); var pos = i; for (j <- (i+1) to (n-1)) { if (a(j) < min) { min = a(j); pos = j; } } val tmp = a(i); a(i) = a(pos); a(pos) = tmp; } } // // main // // Tests selection sort. // def main(args:Array[String]):Unit = { val ints:Array[Int] = for (s <- args) yield {s toInt}; for (i <- ints) { print(i + " "); } println(); selectionSort(ints); for (i <- ints) { print(i + " "); } println(); } } // Exercise 2 // // usage: // scala hw1ex2 // object hw1ex2 { def highLow:Unit = { val number:Int = ((math.random * 100) toInt) + 1; println("I've chosen a number from 1 to 100, try to guess it!"); println("Enter your guess: "); var guess:Int = readLine() toInt; while (guess != number) { if (guess > number) { println("Too high! Try again."); } else { println("Too low! Try again."); } println("Enter your guess: "); guess = readLine() toInt; } println("You got it right!"); } // // main // // Tests the highLow procedure. // def main(args:Array[String]) { highLow; } } // Exercise 3 // // IntStack // // Implementation of a stack of integers using a fixed-capacity // array. // class IntStack(capacity:Int) { // instance variables var size:Int = 0; val elements:Array[Int] = new Array(capacity); // methods // isEmpty // // returns whether the stack is empty // def isEmpty:Boolean = { return (size == 0) } // push // // puts value onto the top of the stack // def push(x:Int):Unit = { elements(size) = x; size = size + 1; } // pop // // removes and returns the value at the top of the stack // // assumes that the stack is not empty // def pop:Int = { size = size - 1; return elements(size); } // top // // returns the value at the top of the stack // // assumes that the stack is not empty // def top:Int = { return elements(size-1); } // toString // // creates a readable representation of the stack // override def toString:String = { var s:String = "" if (!(this isEmpty)) { s = s + "(" + (this top)+ ")"; } for (i <- (size-2) to 0 by -1) { s = s + ":" + (elements(i) toString); } return s + "]"; } } // // example usage: // // scala hw1ex3 "push 1" "push 2" "push 3" pop "push 4" pop pop // object hw1ex3 { // // main // // Tests the IntStack class. // def main(cmds:Array[String]) { // Build a new IntStack instance. val bigEnough:Int = 100; val S:IntStack = new IntStack(bigEnough); // Run through the command-line strings, executing each. for (c <- cmds) { println(); // If the command is to "pop"... if (c == "pop") { val v = S pop; println("pop... => " + (v toString)); // If the command is to "push v"... } else { val v:Int = (c substring(5,c length)) toInt; S push(v); println(c+"..."); } // Output the current contents. println(S); } } }