0

I'm new to Scala and not sure how to return an array containing the square of each number. Can someone help me and let me know what I'm doing wrong please?

Here's my code:

def squareFunction(as:Array[Int]): Array[Int] = {

for(i <- as){
  as(i) = i * i
 }
return as

}
HenryDev
  • 4,685
  • 5
  • 27
  • 64

2 Answers2

3

In (i <- as) i is an element of Array for each iteration(not an index). You should do something like:

def squareFunction(as:Array[Int]): Array[Int] = for(i <- as) yield(i * i)

or

def squareFunction(as:Array[Int]): Array[Int] = as.map(i => i*i)
ulas
  • 463
  • 5
  • 10
  • thanks a lot! can you describe the use of yield real quick please? – HenryDev Feb 04 '16 at 00:44
  • also what will be the function for returning an array containing the cube of each number? something like : for(i <- as) yield(i * i * i) is there a better way to do it? – HenryDev Feb 04 '16 at 00:46
  • When you use yield, it adds up all the given inputs to a collection. For a more accurate explanation you can look at [here](http://stackoverflow.com/a/1052510/3671697) – ulas Feb 04 '16 at 00:49
  • I think `for(i <- as) yield(i * i * i)` is correct for calculating cubes of elements with a for comprehension. – ulas Feb 04 '16 at 00:51
  • If you mean multiplying elements of two array with same indexes you can use a normal for loop and do `as(i) * bs(i)` to achieve it. – ulas Feb 04 '16 at 01:02
  • Or without using for: `as.zip(bs).map(t => t._1 * t._2)` – ulas Feb 04 '16 at 01:09
  • You are welcome, you can use `zip` with for comprehension by the way: `for ((x,y) <- as zip bs) yield x*y` – ulas Feb 04 '16 at 01:16
0

The value of using math.pow() is that you can square, cube, etc...

val x = Array.range(1,9)
val y = x.map(math.pow(_,2))

y: Array[Double] = Array(1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0, 64.0, 81.0)

If you don't need to remain in an Array, then:

(1 to 10).map(math.pow(_,2))

res4: IndexedSeq[Double] = Vector(1.0, 4.0, 9.0, 16.0, 25.0, 36.0, 49.0, 64.0, 81.0, 100.0)

If you're going to redundantly use the squaring capability, then use functional programming:

def square(x: Int) = x * x
(1 to 10).map(square)

res6: IndexedSeq[Int] = Vector(1, 4, 9, 16, 25, 36, 49, 64, 81, 100)
kevin_theinfinityfund
  • 1,631
  • 17
  • 18