mercredi 25 novembre 2020

Fill an array with random numbers in correct way with sum of every four equals or higher than two

I need some help or hint. There is a code:

public class RandomInArray {
    public static void main(String[] args) {
        Random random = new Random();
        int[] array = random.ints(8, 0, 2).toArray();
        System.out.println(Arrays.toString(array));
    }
}

example: [1,0,1,0,0,1,0,1]

The Sum of every 4 numbers in an array has to be a minimum of 2. example: [1,0,1,0,0,1,0,1] From first 1+0+1+0 is correct, the sum is >=2. than: 0,1,0,0, the sum is 1. Incorrect. 1,0,0,1, the sum is 2. Correct. 0,1,0,1, the sum is 2. Correct. How to extend method to print out every time correct random mix of elements in array? There are correct examples with 8 elements. If ex. 20 elements, less or more, the result should be the same. Correct examples:

[1,0,0,1,1,1,1,0]
[1,1,0,1,0,0,1,1]
[0,1,1,0,1,0,1,0]
[1,1,1,1,1,1,1,1]



Aucun commentaire:

Enregistrer un commentaire