Sunday 2 August 2015

Sorted array to element:frequency format

If array has elements {1,1, 2, 3, 4, 4}, you should return a string like "1:2,2:1,3:1,4:2", mean 1 is repeated 2 times, 2 is repeated 1 time, 3 is repeated 1 time and 4 is repeated two times.
import java.util.Objects;

public class ElementFrequency {

 private static final String separator = ":";

 public static String processArray(int arr[]) {
  Objects.nonNull(arr);
  if (arr.length == 0)
   return "";

  StringBuilder builder = new StringBuilder();
  int temp = arr[0];
  int count = 1;

  for (int i = 1; i < arr.length; i++) {
   if (arr[i] == temp) {
    count++;
    continue;
   }
   builder = builder.append(temp).append(separator).append(count)
     .append(",");
   count = 1;
   temp = arr[i];
  }
  builder = builder.append(temp).append(separator).append(count);
  return builder.toString();
 }
}


Following is the junit test case for above program.
import static org.junit.Assert.assertTrue;

import org.junit.Test;

public class ElementFrequencyTest {

 @Test
 public void test1() {
  int arr1[] = { 1, 1, 2, 3, 4, 4 };
  int arr2[] = { 5, 5, 5, 5, 5, 5 };
  int arr3[] = { 4, 5, 6, 6, 6, 6 };

  String actual1 = ElementFrequency.processArray(arr1);
  String actual2 = ElementFrequency.processArray(arr2);
  String actual3 = ElementFrequency.processArray(arr3);

  String expected1 = "1:2,2:1,3:1,4:2";
  String expected2 = "5:6";
  String expected3 = "4:1,5:1,6:4";

  assertTrue(actual1.equals(expected1));
  assertTrue(actual2.equals(expected2));
  assertTrue(actual3.equals(expected3));
 }
}


No comments:

Post a Comment