fork download
  1. import java.util.Random;
  2.  
  3. public class Main {
  4. public static void printIntegerArray(int[] arr) {
  5. if (arr == null)
  6. throw new NullPointerException();
  7. for (int i = 0; i < arr.length; i++) {
  8. System.out.printf("%2d", arr[i]);
  9. }
  10. System.out.println();
  11. }
  12. public static int[] generateRandomIntegerArray(Random random, int size,
  13. int minValue, int maxValue) {
  14. if (random == null || size <= 0 || maxValue < minValue)
  15. return null;
  16. int delta = maxValue - minValue + 1;
  17. int[] arr = new int[size];
  18. for (int i = 0; i < size; i++) {
  19. arr[i] = random.nextInt(delta) + minValue;
  20. }
  21. return arr;
  22. }
  23. public static void printMaxLongZeroGroup(int[] arr) {
  24. if (arr == null)
  25. throw new NullPointerException();
  26. int maxLength = 0, startMaxIndex = -1;
  27. int counter = 0, startIndex = 0;
  28. boolean isZeroStarted = false;
  29. for (int i = 0; i < arr.length; i++) {
  30. if (isZeroStarted) {
  31. if (arr[i] == 0) {
  32. counter++;
  33. } else {
  34. isZeroStarted = false;
  35. if (counter > maxLength) {
  36. maxLength = counter;
  37. startMaxIndex = startIndex;
  38. }
  39. }
  40. } else {
  41. if (arr[i] == 0) {
  42. isZeroStarted = true;
  43. startIndex = i;
  44. counter = 0;
  45. }
  46. }
  47. }
  48. if (counter > maxLength) {
  49. maxLength = counter;
  50. startMaxIndex = startIndex;
  51. }
  52. if (maxLength > 0) {
  53. int endMaxIndex = startMaxIndex + maxLength;
  54. System.out.printf("Max zero sequence length: %d, indexes: %d - %d\n",
  55. maxLength, startMaxIndex, endMaxIndex);
  56. } else {
  57. System.out.println("No zero sequences.");
  58. }
  59. }
  60. public static void main(String[] args) {
  61. final Random random = new Random(System.currentTimeMillis());
  62. for (int i = 0; i < 7; i++) {
  63. int[] a = generateRandomIntegerArray(random, 39, 0, 1);
  64. printIntegerArray(a);
  65. printMaxLongZeroGroup(a);
  66. }
  67. }
  68. }
Success #stdin #stdout 0.15s 320576KB
stdin
Standard input is empty
stdout
 0 1 0 1 0 0 0 1 0 0 0 1 1 1 1 0 0 1 1 0 0 1 1 1 0 1 0 1 0 0 0 1 0 0 0 1 0 0 1
Max zero sequence length: 2, indexes: 4 - 6
 0 1 1 0 1 0 0 1 0 0 0 0 1 0 0 0 0 0 1 0 1 1 1 0 1 1 1 0 0 1 1 0 0 0 0 1 0 1 0
Max zero sequence length: 4, indexes: 13 - 17
 1 1 1 0 1 0 1 0 1 0 0 0 1 1 1 0 0 1 1 1 1 1 1 0 1 1 1 0 0 1 0 1 1 0 1 1 0 0 0
Max zero sequence length: 2, indexes: 9 - 11
 0 0 1 1 1 0 0 0 1 1 1 1 1 0 0 1 1 0 0 1 1 1 1 1 1 1 1 1 0 1 1 1 1 0 0 1 0 0 0
Max zero sequence length: 2, indexes: 5 - 7
 0 1 1 1 1 1 1 1 0 0 0 1 0 1 1 0 1 1 1 0 0 1 1 0 0 0 0 0 1 1 1 1 0 1 1 0 0 0 0
Max zero sequence length: 4, indexes: 23 - 27
 1 0 0 0 1 1 1 0 0 1 1 1 1 1 0 0 0 1 1 1 0 0 0 1 1 0 0 0 0 0 1 1 1 1 0 0 1 0 0
Max zero sequence length: 4, indexes: 25 - 29
 1 1 1 0 1 0 0 1 0 0 0 0 1 1 0 0 0 1 0 0 0 1 1 0 0 1 0 1 0 0 1 1 1 0 0 0 0 0 0
Max zero sequence length: 5, indexes: 33 - 38