Arrays are of type String. Since It is time consuming to add "", I have written it like Int. Sorry.
I have two arrays say var array1 = [[1,2,3,4,5,6,7,8,9]]
and
var array2 = [[1,2,3,4],
[2,3,4,5],
[2,4,5,6],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8],
[2,3,4,5,6,7,8]]
I have to compare each array element of array2
with array1
and insert '-' where the elements do not match. Like this,
var array2 = [[1,2,3,4,-,-,-,-,-],
[-,2,3,4,5,-,-,-,-],
[-,2,-,4,5,6,-,-,-],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8,-],
[-,2,3,4,5,6,7,8,-]]
I tried to iterate over each array in array2 and compare it with array1, compare the indices and insert '-' to at index position i, but I am getting unexpected results.
UPDATE
for item in array2{
var elementsArray = item
for i in stride(from: 0, to: elementsArray.count, by: 1) {
if elementsArray[i] != array1[i]
{
elementsArray.insert("-", at: i)
}
print("elemnt array.....", elementsArray, "\n\n")
}
}
I had thought of comparing each array of array2 with array1 by count
, find the index of uncommon element and then insert '-' at that index position. Is this approach right? Please help me with this.
You want a new array where each row of array2
is replaced by a variant of array1
, with elements not originally present in the row replaced by "-":
let array1 = [1,2,3,4,5,6,7,8,9]
let array2 = [[1,2,3,4],
[2,3,4,5],
[2,4,5,6],
[1,2,3,4,5,6,7,8,9],
[1,2,3,4,5,6,7,8],
[2,3,4,5,6,7,8]]
let filled = array2.map { row in
array1.map {
row.contains($0) ? String($0) : "-"
}
}
for row in filled { print(row) }
Output:
["1", "2", "3", "4", "-", "-", "-", "-", "-"] ["-", "2", "3", "4", "5", "-", "-", "-", "-"] ["-", "2", "-", "4", "5", "6", "-", "-", "-"] ["1", "2", "3", "4", "5", "6", "7", "8", "9"] ["1", "2", "3", "4", "5", "6", "7", "8", "-"] ["-", "2", "3", "4", "5", "6", "7", "8", "-"]
For large arrays this can be improved by creating a Set(row)
for a faster containment check, or by utilizing that the elements are in increasing order.
Your approach does not work correctly because elementsArray
is modified while iterating over it.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments