0

I'm creating all possible combinations of 1D array to 2D array, but it seems my code is too slow to execute. I have a feeling that I could still speed it up.

let arr = [2, 2, 1]
let k = 5
var tempArray = [[Int]]()
for i in 0..<arr.count {
    for j in 0..<arr.count {
        tempArray.append([arr[i], arr[j]])
    }
}

let sortedArray = tempArray.sorted {
    $0[0] == $1[0] ? $0[1] < $1[1] : $0[0] < $1[0]
}

print(sortedArray[k-1])
Ken White
  • 123,280
  • 14
  • 225
  • 444
pacifistazero
  • 87
  • 2
  • 6
  • Look at [this answer](https://stackoverflow.com/a/59343883/335858) for hints on improving the speed of 2D array by (1) mapping it to a 1D array with some index translation, and (2) by pre-filling the matrix with rows of zeros to avoid calls to `append`. – Sergey Kalinichenko Jun 13 '22 at 03:51
  • 1
    Consider using tuples (pairs of values) instead of nested arrays (with fixed number of items in your case anyway). You can also try to maintain order on inserting (insert pairs into correct position instead of sorting the result later). – lazarevzubov Jun 13 '22 at 05:02
  • 1
    Where does this problem come from? Is only the value for a certain index `k` needed? Is this related to some programming contest? – Martin R Jun 13 '22 at 07:08
  • @SergeyKalinichenko I understood with just filling up 2D array from 1D but what I'm still confused is how to apply that here? – pacifistazero Jun 13 '22 at 15:19
  • @lazarevzubov that is actually a good idea, any idea how to do it? – pacifistazero Jun 13 '22 at 15:20
  • @pacifistazero You know the sizes upfront, so you create a 1D array of `arr.count*arr.count` elements, and then apply the technique from the answer to fill it. There's another answer to the same question that gives you a generic wrapper for a 1D array presenting itself as a 2D array. – Sergey Kalinichenko Jun 13 '22 at 15:37
  • @pacifistazero Binary search for inserting. But nah, forget it. I measured and sorting afterwards beats binary search inside two loops on larger sets of data. However, switching to array of tuples improves performance a bit, about 20% on average on my machine. – lazarevzubov Jun 13 '22 at 16:19
  • 1
    @SergeyKalinichenko i tried your suggestions, it seems improved a lot (of course) – pacifistazero Jun 14 '22 at 16:09
  • @lazarevzubov I exactly have the same thought to use BST but it is too complex for simple case like this :P. Array of tuples? You mean some kind of dictionary? – pacifistazero Jun 14 '22 at 16:09
  • @pacifistazero No, just [(Int, Int)] instead of [[Int]]. – lazarevzubov Jun 15 '22 at 05:53

0 Answers0