Home Puzzles logical deduction – Java set a property of all objects in a List when no less than one object satisfies a standards utilizing a single loop

logical deduction – Java set a property of all objects in a List when no less than one object satisfies a standards utilizing a single loop

0
logical deduction – Java set a property of all objects in a List when no less than one object satisfies a standards utilizing a single loop

[ad_1]

Here is the puzzle I used to be requested in an interview

There’s a List of Employee objects. Update all of the objects within the checklist to be eligibleForHike if no less than one worker exists whose wage is lower than x; in any other case replace all of them in-eligibleForHike in a single iteration/loop

Requirements/Restrictions:

  1. Streams shouldn’t be used
  2. Only one go/iteration/loop
  3. Not allowed to used two loops (although not nested and although the time complexity would nonetheless be O(n)). Not certain why, however could also be as a result of it is a puzzle

Employee class

public class Employee {
   non-public String title;
   non-public Double wage;
   non-public Boolean eligibleForHike;
   //all getters and setters outlined
}

My resolution (not elegant) due to house complexity

public List<Employee> checkEligibility(List<Employee> staff, Double wage) {
   List<Employee> eligible = new ArrayList<>();
   List<Employee> inEligible = new ArrayList<>();
   boolean isEligibleForHike = false;
   staff.forEach(worker -> {
      Employee e1 = worker.clone();
      e1.setEligibleForHike(true);
      Employee e2 = worker.clone();
      e2.setEligibleForHike(false);
      eligible.add(e1);
      inEligible.add(e2);
      if(!isEligibleForHike && worker.getSalary() < wage) {
         isEligibleForHike = true;
      }
   });
   return isEligibleForHike ? eligible : inEligible;
}

Posting right here to discover a higher resolution to this downside, the place the identical List of objects may be up to date in place and nonetheless use just one loop

[ad_2]

LEAVE A REPLY

Please enter your comment!
Please enter your name here