Note that there are some explanatory texts on larger screens.

plurals
  1. POgroupNoAdjacency Recursion Problem in Core Java Programming
    text
    copied!<p>I have the below question as well as this time i have done some R&amp;D and arrived at the solution but there is a glitch in the solution (one scenario)as well.</p> <p>Q: groupNoAdjacent recursion problem :: Given an array of ints, is it possible to choose a group of some of the ints, such that the group sums to the given target with this additional constraint: If a value in the array is chosen to be in the group, the value immediately following it in the array must not be chosen. (No loops needed.) </p> <pre><code>groupNoAdj(0, {2, 5, 10, 4}, 12) =&gt; true --&gt; This is true coz of 2+10 =12,NoAdjacency groupNoAdj(0, {2, 5, 10, 4}, 14) =&gt; false -&gt; 10+4=14,numbers are adjacent,its false groupNoAdj(0, {2, 5, 10, 4}, 7) =&gt; false --&gt; 2+5=7,numbers are adjacent,its false </code></pre> <p>my solution is as below.It works for all the below given scenarios except for one scenario.</p> <hr> <h2>Code:</h2> <pre><code>public boolean groupNoAdj(int start, int[] numbers, int target) { start=0; boolean[] reached = new boolean[target+1]; reached[0] = true; for (int i=0;i&lt;numbers.length;i++){ for (int j = i + 2; j&lt;numbers.length; j++){ if(numbers[j] + numbers[i] == target){ reached[target]=true; }else if(numbers[j] + numbers[i] &lt; target){ numbers[i] = numbers[j] + numbers[i]; } } } return reached[target]; } </code></pre> <p>Scenarios are given below</p> <pre><code> Expected This Run groupNoAdj(0, {2, 5, 10, 4}, 12) → true true OK groupNoAdj(0, {2, 5, 10, 4}, 14) → false false OK groupNoAdj(0, {2, 5, 10, 4}, 7) → false false OK groupNoAdj(0, {2, 5, 10, 4, 2}, 7) → true true OK groupNoAdj(0, {2, 5, 10, 4}, 9) → true true OK groupNoAdj(0, {10, 2, 2, 3, 3}, 15) → true true OK groupNoAdj(0, {10, 2, 2, 3, 3}, 7) → false false OK groupNoAdj(0, {}, 0) → true true OK **groupNoAdj(0, {1}, 1) → true false X** groupNoAdj(0, {9}, 1) → false false OK groupNoAdj(0, {9}, 0) → true true OK groupNoAdj(0, {5, 10, 4, 1}, 11) → true true OK </code></pre> <p>My Code is not working for the one marked in BOLD.any ideas or inputs or suggestions you would like to give.i have tried analysing the code but since i did not get the solution for an exceptional scenario im posting it in Stackoverflow.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload