0

I am having two arrays. Size of first array is larger than second one.

 var first  = (1 to 20).toArray
 var second = (1 to 5).toArray

I want to Replace first n elements of first array with the elements of second array. Where n is length of second array. Using For loop I can easily do this in following way

 var n = second.length
 for(i <- 0 until n)
 {
  first(i) = second(i)
 }

I want to ask is there any other way to perform same operation in Scala in more functional way?

5
  • What do you mean by "more functional way"? Are you looking for a solution without mutating the first array? Commented Aug 14, 2019 at 10:22
  • @k0pernikus yes. I am looking for alternative of For loop. Commented Aug 14, 2019 at 10:28
  • You could use copyToArray like, second.copyToArray(first). Also, for what you need you could replace var with val. Commented Aug 14, 2019 at 10:37
  • 1
    In the end, even a functional approach will loop the data. Furthermore, a functional approach will create another array consisting of the result and therefore have a larger memory consumption. Commented Aug 14, 2019 at 10:39
  • If you want to write in a functional way, you should begin by avoiding ever using Array in the first place, just sayin'... Commented Aug 14, 2019 at 14:44

1 Answer 1

5

You can do this:

var first  = (1 to 20).toArray
var second = (1 to 5).toArray

val third = second ++ first.drop(second.length)

result:

third: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
Sign up to request clarification or add additional context in comments.

3 Comments

This IIRC either returns a vector or IndexedSeq[Int], so toArray may be necessary.
first = second ++ first.drop(second.length) This will return first array with updated elements
@yari yes, but since you asked a more functional way, it is better to use val´s instead of vars, if you really want to replace and keep vars, then it is exactly how you wrote.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.