Skip to content

Instantly share code, notes, and snippets.

@parzibyte
Created September 3, 2019 04:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parzibyte/0d146253256cf83b1e9cb74bf70d4076 to your computer and use it in GitHub Desktop.
Save parzibyte/0d146253256cf83b1e9cb74bf70d4076 to your computer and use it in GitHub Desktop.
import java.util.Arrays;
// https://parzibyte.me/blog
class Main {
public static void main(String[] args) {
int arreglo[] = { 3, 4, 5, 6, 4, 3, 6, 7, 6, 5, 9, 1 };
int arregloSinRepetidos[] = new int[arreglo.length];
// Esta variable es para el índice de arregloSinRepetidos
int i = 0;
for (int x = 0; x < arreglo.length; x++) {
if (esValorUnico(arreglo[x], arreglo)) {
arregloSinRepetidos[i] = arreglo[x];
i++;
}
}
// Usamos Arrays.toString para imprimir de manera rápida, no
// es necesario para el algoritmo
System.out.println("Arreglo original: " + Arrays.toString(arreglo));
System.out.println("Arreglo con valores únicos: " + Arrays.toString(arregloSinRepetidos));
}
// Cuenta cuántas veces aparece el valor y devuelve true si
// aparece exactamente una vez
public static boolean esValorUnico(int valor, int[] arreglo) {
int contador = 0;
for (int x = 0; x < arreglo.length; x++) {
if (arreglo[x] == valor)
contador++;
}
return contador == 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment