fork download
  1. import java.util.Arrays;
  2. public class Main
  3. {
  4. public static void main(String[] args) {
  5. byte[] example = encodeRle(new byte[] { 15, 15, 15, 4, 4, 4, 4, 4, 4});
  6. System.out.println(Arrays.toString(example));
  7. }
  8. public static byte[] encodeRle(byte[] flatData) {
  9. byte[] encodedData = new byte[countRuns(flatData)*2]; //the encoded array is twice the size of the number of runs
  10. int runSize = 1;
  11. for (int i = 0; i < encodedData.length; i+=2) { //iterates through the
  12. for (int j = 1; j < flatData.length;j++) { //iterates through the flat data array
  13. if (flatData[j] == flatData[j - 1]) {
  14. runSize++;
  15. if (runSize == 15) { //starts a new run when there are 15 elements in a given run
  16. encodedData[i+1] = flatData[j]; //sets the value of the run in the odd positions of the encoded array
  17. encodedData[i] = (byte) runSize;//sets the number of elements in a run in the even positions of the encoded array
  18. runSize = 1;
  19. }
  20. }
  21. else {
  22. encodedData[i+1] = flatData[j]; //sets the value of the run in the odd positions of the encoded array
  23. encodedData[i] = (byte) runSize; //sets the number of elements in a run in the even positions of the encoded array
  24. }
  25. }
  26. }
  27. return encodedData;
  28. }
  29. public static int countRuns(byte[] flatData) { //counts the number of runs in an array of flat data
  30. int runSize = 1, numRuns = 1;
  31. for (int i = 1; i < flatData.length; i++) {
  32. if (flatData[i] == flatData[i-1]) { //if two adjacent elements are equal, keeps the same run going
  33. runSize++;
  34. if (runSize > 15) { //if there are more than 15 elements in a run, starts a new run
  35. numRuns++;
  36. runSize = 1;
  37. }
  38. }
  39. else { //if two adjacent elements are not equal, starts a new run
  40. numRuns++;
  41. }
  42.  
  43. }
  44. return numRuns;
  45. }
  46.  
  47. }
  48.  
  49.  
Success #stdin #stdout 0.06s 32440KB
stdin
Standard input is empty
stdout
[3, 4, 15, 4]