iiitl / snake-game-js

0 stars 43 forks source link

Added check for food spawning on snake, issue #9 #14

Closed Karanagarwal12 closed 5 months ago

Karanagarwal12 commented 5 months ago

Solved the bug mentioned in the issue #9, by adding a check for the food to not spawn on the snake, but still the code time complexity can reach very high at some point as we are checking for every random number to not be on any point of snake and this can to lead to needing much more time. If you have a better approach please share it with me.

ANKITy102 commented 5 months ago

@Karanagarwal12, good work! Yes there exist better approach. Before that can you reduce the time complexity of the checkFoodOnSnake() function. Now, if you try to implement some better approach for given task then I can give you 10 points for this issue.

Karanagarwal12 commented 5 months ago

@ANKITy102 , can you tell a hint how should I do that, and if we check the time complexity of the function is O(n) where n is length of snake which in the worst case will get to 19*19, which is not a problem, and how can I check without iterating through all points of snake?

ANKITy102 commented 5 months ago

@Karanagarwal12 , the time complexity depends on the number of pixels. And also it get added by the number of while loop run i.e X x 19 x 19. You can create hash for each pixel which can updated in O(1) and accessed in O(1).

Karanagarwal12 commented 5 months ago

@ANKITy102, Thanks for the help, I've optimised the code complexity by using a 2d boolean array which is updating itself in O(1) time and also checking for the food on it with again O(1) time. Thanks again!

ANKITy102 commented 5 months ago

@Karanagarwal12, Nice work.