Here are two ways to answer the following question. I'm trying to confirm what I believe their time complexity to be:
If I had a snake game with a x,y matrix of spaces, some of which were occupied the snake, how would I best find an available space to place an apple?
- I could run through the existing matrix and store a new list of coords which are free, then pick a random element from that array.
- I could pick a random x,y and, if it's taken, pick another random coord (repeating as necessary)
It seems like the first one is O(N) time, since it always checks each space in the playfield once
The second one seems like O(N) amortized, since if the snake is at 50% of the playfield then on average it will take N checks to find an open space. Yet if the snake is smaller than 50%, the random approach will be better, and if it's more than 50%, it will be worse.
Is this thinking correct? I'm not sure I'm using the term "amortized" correctly, since I have only had a very brief introduction to the concept in the context of dynamic arrays in ruby.
O(snake)solution by taking a random integer from[0, N-snake[and then test each element of the snake whether it's smaller than your integer and needs to be skipped when translating the integer to a position.