madCode
madCode

Reputation: 3903

Iterating an immutable Array and updating every element in the array, based on other elements

I have an array: Array[[List[Int]]](81) ( this is a val )

I want to break it down say row-wise and if any of the elements in that particular row has only one element in the list, say b.size = 1, then I want to remove that element in 'b', from every other list in that particular row of the Array.

I'm not sure, how to go about considering just the first 9 elements, then the next 9 elements from the Array, given the constraint that I don't use mutable variables. ( so just vals and not vars ).

So far: I have a function that accepts the list and the element to be removed from it. But, how do I go about iterating through every row in the above array or every column in the array, and go back to the starting of the row, if I find a list with just one element, to update the other elements in the list, is my question.

Upvotes: 1

Views: 203

Answers (1)

Kristian Domagala
Kristian Domagala

Reputation: 3696

Assuming you mean you have an Array[Array[List[Int]]], this sounds like it'll do what you're after:

scala> def filterRow(arr:Array[List[Int]]):Array[List[Int]] = {
     |   val found:Option[Int] = arr.collectFirst{case List(x) => x};
     |   found.map(f =>
     |     arr.map(l =>
     |       if (l.size == 1) l else l.filterNot(_ == f)
     |     )
     |   ).getOrElse(arr)
     | }
filterRow: (arr: Array[List[Int]])Array[List[Int]]
scala> val a = Array(Array(List(1),List(1,2),List(1,2,3)),Array(List(2),List(1,2),List(1,2,3)))
a: Array[Array[List[Int]]] = Array(Array(List(1), List(1, 2), List(1, 2, 3)), Array(List(2), List(1, 2), List(1, 2, 3)))
scala> a.map(filterRow)
res0: Array[Array[List[Int]]] = Array(Array(List(1), List(2), List(2, 3)), Array(List(2), List(1), List(1, 3)))

If not, hopefully it gives you enough of a lead to work it out. Otherwise, you might need to clarify your question a bit more.

Upvotes: 1

Related Questions