Thursday, May 5, 2011

01 Kata [java] - sum of multiples of 3 or 5 less than 1000

public int sum() {
  int sum = 0;

  for (int i = 0; i < 1000; i++) {
    if (i % 3 == 0 || i % 5 == 0) {
      sum += i;
    }
  }

  return sum;
}

public class FirstKataTest {
  @Test
  public void testSum() {
    FirstKata kata = new FirstKata();
    assertEquals(
      kata.sum(),
      233168
    );
  }
}

This is the first shot to solve the problem and we should notice that it is a very specific method that works in this case only.
But what if want to find the sum of multiples for any given number? Well, we'll need to perform a little refactoring.

public class FirstKata {
  public int sum(int upperLimit) {
    int sum = 0;

    for (int i = 0; i < upperLimit; i++) {
      if (i % 3 == 0 || i % 5 == 0) {
        sum += i;
      }
    }

    return sum;
  }
}

@Test
public void testSum() {
  FirstKata kata = new FirstKata();
  assertEquals(
    kata.sum(1000),
    233168
  );

  assertEquals(
    kata.sum(10),
    23
  );
}

As one can see, we add the parameter upperLimit to the sum method and now, we can compute the sum of multiples of any number we feel it's right.
But this solution is not generic enough, since it computes only the multiples of 3 or 5. So, let's perform another refactoring and make the method more generic.

public class FirstKata {
  public int sum(int upperLimit, List<Integer> multiples) {
    int sum = 0;

    for (int i = 0; i < upperLimit; i++) {
      if (isMultiple(i, multiples)) {
        sum += i;
      }
    }

    return sum;
  }

  public boolean isMultiple(int number, List<Integer> multiples) {
    for (int multiple : multiples) {
      if (number % multiple == 0) {
        return true;
      }
    }

    return false;
  }
}

@Test
public void testSum() {
  List<Integer> multiples = new ArrayList<Integer>();
  multiples.add(3);
  multiples.add(5);

  FirstKata kata = new FirstKata();
  assertEquals(
    kata.sum(1000, multiples),
    233168
  );

  assertEquals(
    kata.sum(10, multiples),
    23
  );
}

@Test
public void testIsMultiple() {
  FirstKata kata = new FirstKata();
  List<Integer> multiples = new ArrayList<Integer>();
  multiples.add(3);
  multiples.add(5);

  assertTrue(kata.isMultiple(6, multiples));
  assertTrue(kata.isMultiple(10, multiples));
}

Fair enough. Now we can compute the sum of any multiples for any number.
And that's all for the java solution.

No comments:

Post a Comment