Search code examples
iosarraysfilterswift5xcode10

Make my array zero keeping some indices as it is


I have an array 'board_matrix' with some values in it. And I also have another array 'win' with some indices values. Now I want to make 'board_matrix' go all zero except those indices in 'win' array.

say,

board_matrix = [1,0,2,2,1,0,1,0,1]
win = [0,4,8]

then output should be 
new_array = [1,0,0,0,1,0,0,0,1]

Solution

  • You can iterate over the board_matrix array and overwrite the values if the index is not found in the win array. Something like this:

    for (i=0; i<board_matrix.size; i++) {
        if (!win.contains(i)) board_matrix[i] = 0;
    }