In: Computer Science
Scala: Write and test a program as elegantly as possible
You are given a puzzle like this:
7 __ 10 __ 2
Each blank may be filled with a ‘+’ (plus) or ‘-’ (minus), producing a value k. For all combinations of plus and minus, find the value of k that is closest to 0.
In the above case, there are 4 combinations, each producing a different value:
7 + 10 + 2 = 19 7 + 10 - 2 = 15 7 - 10 + 2 = -1 7 - 10 - 2 = -5
Of all these combinations, the value that is closest to zero is -1. So the answer is - 1. If there are more than one number that is closest, print the absolute value.
Sample Input/Output:
Enter digits: 7,10,2 Value close to zero is -1
Enter digits: 1,2,3,4 Value close to zero is 0
Solution:
import scala.math.abs object Test { def closestToZero(values: Array[Int]): Int = { val possibleVals = List(values(0) + values(1) + values(2), values(0) + values(1) - values(2), values(0) - values(1) - values(2), values(0) - values(1) + values(2)) possibleVals.sortWith((x, y) => (abs(x) < abs(y)))(0) } def main(args: Array[String]) { val scanner = new java.util.Scanner(System.in) print("Enter digits: ") val vals = scanner.nextLine().split(",").map(_.toInt) print("Closest value is: " + closestToZero(vals)) } }