Ad
Arrays

This code avoids redundand computations and checks

Code
Diff
  • public class Kata {
        
        public static int speedLimit(int speed, int[] signals) {
          int penalty = 0;
          
          for (int signal : signals) {
            final int diff = speed - signal;
            
            if (diff >= 30) penalty += 500;
            else if (diff >= 20) penalty += 250;
            else if (diff >= 10) penalty += 100;
          }      
          return penalty;
        }
    }
    • public class Kata {
    • public static int speedLimit(int speed, int[] signals) {
    • int penalty = 0;
    • for (int signal : signals){
    • if (speed > signal) {
    • if(speed - signal >= 10 && speed - signal < 20) {
    • penalty += 100;
    • } else if(speed - signal < 30) {
    • penalty += 250;
    • } else if (speed - signal >= 30) {
    • penalty += 500;
    • }
    • }
    • }
    • for (int signal : signals) {
    • final int diff = speed - signal;
    • if (diff >= 30) penalty += 500;
    • else if (diff >= 20) penalty += 250;
    • else if (diff >= 10) penalty += 100;
    • }
    • return penalty;
    • }
    • }