0

I want to assign a part of an array to a part of another array in Scala. For example, I want to do the Scala or Java equivalent of the following Python code.

x[i:j] = y[k:l]

How can I do that in Scala or even Java?

1
  • Assume that not all Scala coders know python. Be more specific in your description. You may want to remove the python tag as well. This isn't a python question. Commented Feb 2, 2017 at 19:54

1 Answer 1

1

You can use a combination of .patch and .slice:

scala> val a = Array.range(1, 20)
a: Array[Int] = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)

scala> val b = Array.range(30, 50)
b: Array[Int] = Array(30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49)

scala> a.patch(5, b.slice(5, 10), 5)
res5: Array[Int] = Array(1, 2, 3, 4, 5, 35, 36, 37, 38, 39, 11, 12, 13, 14, 15, 16, 17, 18, 19)

The parameters of .slice are:

  • the element to start from (i in your python exemple)
  • the array to insert (y[k:l], here using .slice to select from k to l)

  • the number of element to replace in the array (unclear about what happens in your exemple when i:j is smaller than k:l, but I would guess it would be j-i here)

Sign up to request clarification or add additional context in comments.

2 Comments

Would this be as efficient as System.arraycopy?
the first index is not 0, so the 19 is the 18th index in your first array?

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.