Last active
November 29, 2022 22:14
-
-
Save martinsam16/223e7bc7a9cd0b609ae047d869018f91 to your computer and use it in GitHub Desktop.
Are they the "same"? codewars java 11
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.Map; | |
import java.util.stream.Collectors; | |
public class AreSame { | |
public static boolean comp(int[] a, int[] b) { | |
if (a == null || b == null) return false; | |
int[] arrAlcuadrado = Arrays.stream(a).map(operand -> operand * operand).toArray(); | |
Arrays.sort(arrAlcuadrado); | |
Arrays.sort(b); | |
Map<Integer, Integer> tablaFrecuenciaA = crearMapFrecuenciaElementos(arrAlcuadrado); | |
Map<Integer, Integer> tablaFrecuenciaB = crearMapFrecuenciaElementos(b); | |
if (tablaFrecuenciaA.size() != tablaFrecuenciaB.size()) return false; | |
return tablaFrecuenciaA.equals(tablaFrecuenciaB); | |
} | |
// elemento, freq | |
private static Map<Integer, Integer> crearMapFrecuenciaElementos(int arr[]){ | |
return Arrays.stream(arr).boxed().collect(Collectors.toMap(e -> e, e -> contarElementoEnArray(arr, e), (a, b) -> b)); | |
} | |
private static int contarElementoEnArray(int arrayOrdenado[], int numeroAContar) { | |
int cantidad = 0; | |
for (int e: arrayOrdenado) { | |
if (numeroAContar == e){ | |
cantidad+=1; | |
} | |
} | |
return cantidad; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment