Posted By

smundall on 02/07/16


Tagged


Versions (?)

Shortest Path


 / Published in: Java
 

Simple function for finding shortest path given A and B variables. Each 'turn' the user can move 2 blocks horizontal and one block vertical or two blocks vertical and one block horizontal. Get to 0.0.

  1. public static int countTurns(int A, int B){
  2.  
  3. //check a and b. If either a or b is at 0, we know we're stuck.
  4. if(A == 0 && B == 0)
  5. return 0;
  6. else if(A == 0 || B == 0)
  7. return -1;
  8.  
  9. //declare some variables.
  10. int turns = 0;
  11.  
  12. //now convert them to their positive form.
  13. int a = Math.abs(A);
  14. int b = Math.abs(B);
  15.  
  16. //now make our loop.
  17. while(a != 0 && b != 0){
  18.  
  19. //check who to move first.
  20. if(a > b){
  21. //move a 2 and b 1.
  22. a -=2;
  23. b -=1;
  24. } else {
  25. a -=1;
  26. b -=2;
  27. }
  28.  
  29. //now add our turn.
  30. turns += 1;
  31.  
  32. //check for our 100,000,000
  33. if(turns > 100000000)
  34. return -2;
  35.  
  36. }
  37.  
  38. //now a bit more logic.
  39. if(a == 0 && b == 0)
  40. return turns;
  41. else
  42. return -1;
  43.  
  44. // thats it!
  45. }

Report this snippet  

You need to login to post a comment.