Advertisement
Guest User

Untitled

a guest
Oct 17th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.81 KB | None | 0 0
  1. //Count the minimum number of jumps required for a frog to get to the other side of a river.
  2.  
  3. import java.util.*;
  4.  
  5. //TODO better Performance and Correctness
  6. class Solution {
  7. public int solution(int[] A) {
  8.  
  9. int position = -1;
  10. int end = A.length;
  11. int jumps = 0;
  12. int jumpsFW = Integer.MAX_VALUE;
  13. int jumpsBW = Integer.MAX_VALUE;
  14.  
  15. ArrayList<Integer> fibs = new ArrayList<Integer>();
  16. int n = 1;
  17. int fib = 0;
  18. do{
  19. fib = fibonacci(n);
  20. fibs.add(fib);
  21. n++;
  22. }while(fib < end + 1);
  23.  
  24. final int[] fibArray = fibs.stream().distinct()
  25. .filter(num -> num <= A.length + 1)
  26. .mapToInt(Integer::intValue)
  27. .toArray();
  28.  
  29. for(int i = fibArray.length - 1; i >= 0; i--){
  30.  
  31. //Try to jump to Finish
  32. if(position + fibArray[i] == end){
  33. jumps++;
  34. jumpsFW = jumps;
  35. break;
  36. //It's not allowed to jump beyond the end
  37. }else if(position + fibArray[i] > end){
  38. continue;
  39. //Try to jump as far as possible
  40. }else{
  41. if(A[position + fibArray[i]] == 1){
  42. //System.out.println(position + fibArray[i]);
  43. position = position + fibArray[i];
  44. i = fibArray.length - 1;
  45. jumps++;
  46. }
  47. }
  48. }
  49.  
  50. //Backwards
  51. int start = -1;
  52. position = A.length;
  53. jumps = 0;
  54.  
  55. for(int i = fibArray.length - 1; i >= 0; i--){
  56.  
  57. //Try to jump to the Start
  58. if(position - fibArray[i] == start){
  59. jumps++;
  60. jumpsBW = jumps;
  61. break;
  62. //It's not allowed to jump beyond the start
  63. }else if(position - fibArray[i] < start){
  64. continue;
  65. //Try to jump as far as possible
  66. }else{
  67. if(A[position - fibArray[i]] == 1){
  68. //System.out.println(position - fibArray[i]);
  69. position = position - fibArray[i];
  70. i = fibArray.length - 1;
  71. jumps++;
  72. }
  73. }
  74. }
  75.  
  76. jumps = jumpsFW < jumpsBW ? jumpsFW : jumpsBW;
  77. jumps = jumps < Integer.MAX_VALUE ? jumps : -1;
  78.  
  79. return jumps;
  80. }
  81.  
  82. public int fibonacci(int n){
  83.  
  84. if(n==0){
  85. return 0;
  86. }else if(n==1){
  87. return 1;
  88. }else{
  89. return fibonacci(n-2) + fibonacci(n-1);
  90. }
  91.  
  92. }
  93. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement