lundi 26 février 2018

Array without repeating of the only number

  • I have to create an array in range [-10: 10];
  • without ZERO;
  • quantity of positive and negative numbers must be equal.

The main issue is that array is not always consist of 50/50 of percent of positive and negatime numbers. If you can show me much simply way to code it you are welcome!

public static void main(String[] args) throws IOException {
        int array[] = new int[12];
        int positiveCounter = 0;
        int negativeCounter = 0;

        for (int i = 0; i < array.length; i++) {
            array[i] = createRandom();
            while (array[i] == 0) {
                array[i] = createRandom();
            }

            if (positiveCounter > array.length / 2) {
                array[i] = -1 * array[i];
                positiveCounter--;
                negativeCounter++;
            }
            if (negativeCounter > array.length / 2) {
                array[i] = -1 * (-array[i]);
                negativeCounter--;
                positiveCounter++;
            }

            if (array[i] > 0) {
                positiveCounter++;
            }
            if (array[i] < 0) {
                negativeCounter++;
            }
        }
        System.out.println(Arrays.toString(array));
        System.out.println("Pos: " + positiveCounter);
        System.out.println("Neg: " + negativeCounter);
    }

    static int createRandom() {
        Random random = new Random();
        int x = -10 + random.nextInt(11 - (-10));
        return x;
    }




Aucun commentaire:

Enregistrer un commentaire