array without repeated numbers

0

My program consists of the following:

We generate an array of 10 positions with random numbers from 1 to 20, then with a method called repeated we check that the numbers that have been generated are not in the array, in case they are on and get otherwise they do not get

This is the code:

import java.util.Random;
import java.util.Scanner;

public class pruebaexamen {
public static void main(String[] args) {
    // TODO Auto-generated method stub

    Random rant = new Random();
    Scanner n = new Scanner(System.in);

    // crear un array de numeros aleatoros mas pequeños que el 20 y luego en
    // otro array mostrar los numeros mas pequeños que el 20 que no se hayan
    // generado en el array

    int[] array = new int[10];
    int numero = 0;
    // lo generamos
    for (int i = 0; i < array.length; i++) {
        numero = rant.nextInt(20 - 0);
        if (repetido(array, numero) == false) {
            array[i] = numero;
        }
    }
    // comprovamos que no haya ningun numero repetidos

    // lo mostramos
    for (int i = 0; i < array.length; i++) {
        System.out.print(array[i]);
    }
}

public static boolean repetido(int[] array, int valor) {
    boolean repetido = false;
    for (int i = 0; i < array.length; i++) {
        if (array[i] == valor) {// si el valor generado aleatoriamente esta
                                // dentro del array le marcamos como true y
                                // por lo tanto no lo metera en el array
            repetido = true;
        } else if (array[i] != valor) {

            repetido = false;
        }
    }
    return repetido;
}

}

The situation is as follows: Even having done this, I keep creating the numbers with some repetitions, what have I failed to do? Is there any other way to do it or improve it?

    
asked by david sierra fernandez 17.05.2018 в 11:02
source

3 answers

3

The error is in your conditional in the method repetido

You check that in the current interaction the element exists, if you change the boolean to true and if it does not exist you put it to false and you pass to the next element of the array. If you find the value in the 3rd position of 5 for example you are going to put the boolean to true , but in iteration 4 you will put it back to false and that's where the error lies.

To solve this it would be enough to eliminate the else of the method in the following way:

public static boolean repetido(int[] array, int valor) {
boolean repetido = false;
for (int i = 0; i < array.length && !repetido; i++) {
    if (array[i] == valor) {// si el valor generado aleatoriamente esta
                            // dentro del array le marcamos como true y
                            // por lo tanto no lo metera en el array
                            // al poner en la condicion del bucle que 
                            // repetido sea false, cuando lo ponemos a true
                            // salimos y evitamos iteraciones inecesarias
        repetido = true;
    }
}
   return repetido;
}

since repeated default is false unless in some interaction you find the data inside the array, which repeated would be true.

    
answered by 17.05.2018 в 11:13
1

You can solve it much more easily by using Java 8 streams:

public static void main(String[] args) {
    // TODO Auto-generated method stub

    Random rant = new Random();
    Scanner n = new Scanner(System.in);

    // crear un array de números aleatorios mas pequeños que el 20 y luego en
    // otro array mostrar los números mas pequeños que el 20 que no se hayan
    // generado en el array

    int[] array = new int[10];
    int numero = 0;
    // lo generamos
    for (int i = 0; i < array.length; i++) {
        array[i] = rant.nextInt(20 - 0);
    }
    Arrays.stream(array).forEach(System.out::println);
    // comprobamos que no haya ningún numero repetidos
    System.out.println("Sin repetidos:");
    Arrays.stream(array).distinct().forEach(System.out::println);

}
    
answered by 17.05.2018 в 11:18
1

Your error is clear. When it finds a repeated value, it goes back to true, but then it queries the next value and if it does not match it goes back to false, that's your error.

To solve it, when you find a repeated one, you have to return true and not keep looking at the rest of the positions of the array.

The code would look like this:

public static boolean repetido(int[] array, int valor) {
    for (int i = 0; i < array.length; i++) {
        if (array[i] == valor) {
            return true; //Si está repetido devolvemos true
        }
    }
    return false; //Si ha acabado el bucle quiere decir que no había valores repetidos
                  //así que podemos devolver directamente false
}
    
answered by 17.05.2018 в 12:01