Featured post
groupNoAdjacency Recursion Problem in Core Java Programming -
i have below question time have done r&d , arrived @ solution there glitch in solution (one scenario)as well.
q: groupnoadjacent recursion problem :: given array of ints, possible choose group of of ints, such group sums given target additional constraint: if value in array chosen in group, value following in array must not chosen. (no loops needed.)
groupnoadj(0, {2, 5, 10, 4}, 12) => true --> true coz of 2+10 =12,noadjacency groupnoadj(0, {2, 5, 10, 4}, 14) => false -> 10+4=14,numbers adjacent,its false groupnoadj(0, {2, 5, 10, 4}, 7) => false --> 2+5=7,numbers adjacent,its false
my solution below.it works below given scenarios except 1 scenario.
code:
public boolean groupnoadj(int start, int[] numbers, int target) { start=0; boolean[] reached = new boolean[target+1]; reached[0] = true; (int i=0;i<numbers.length;i++){ (int j = + 2; j<numbers.length; j++){ if(numbers[j] + numbers[i] == target){ reached[target]=true; }else if(numbers[j] + numbers[i] < target){ numbers[i] = numbers[j] + numbers[i]; } } } return reached[target]; }
scenarios given below
expected 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
my code not working 1 marked in bold.any ideas or inputs or suggestions give.i have tried analysing code since did not solution exceptional scenario im posting in stackoverflow.
because of line:
i starting @ 0, j initializes 0+2=2, numbers.length 1, code inside loop never executes.
(int j = + 2; j<numbers.length; j++){
because of line, starting @ 0, j initializes 0+2=2, numbers.length 1, code inside loop never executes.
since you're wasting lot of space array of booleans, can explicitly short arrays.
if (numbers.length<1 && target==0){return true;)
at beginning. then, iterate through list while target, work (i think). long ok returning true (0, {1,2}1), based upon test cases looks acceptable.
for (int i=0;i<numbers.length;i++){ (int j=2;j<numbers.length;j++){ if (target-numbers[i]-numbers[j]==0){return true;} } if (target-numbers[i]==0){ return true;} curr+=target[i]; } return false;
- Get link
- X
- Other Apps
Comments
Post a Comment