Como comparar itens de arrays de strings
// program to compare two arrays function compareArrays(arr1, arr2) { // compare arrays const result = JSON.stringify(arr1) == JSON.stringify(arr2) // if result is true if(result) { console.log('The arrays have the same elements.'); } else { console.log('The arrays have different elements.'); } } const array1 = [1, 3, 5, 8]; const array2 = [1, 3, 5, 8]; compareArrays(array1, array2); Output The arrays have the same elements.The JSON.stringify() method converts an array into JSON string. JSON.stringify([1, 3, 5, 8]); // "[1,3,5,8]"Then, the two array strings are compared using ==. Example 2: Compare Arrays using for Loop// program to extract value as an array from an array of objects function compareArrays(arr1, arr2) { // check the length if(arr1.length != arr2.length) { return false; } else { let result = false; // comparing each element of array for(let i=0; iIn the above program, The length of the array elements are compared using the length property. If both arrays have different lengths, false is returned. Else,
Note: The above program does not work if the array element contains objects. For example, array1 = [1, {a : 2}, 3, 5];
General Usage Performance
Le’t have 2 arrays (of String, but it doesn’t really matter). I need to compare them, but the order is irrelevant, just that they contain the same Strings/items (and are of the same length, obviously). i.e. comparison of x1 = [“a”, “b”, “c”] should return true (equality). What would be the fastest, most efficient way to do that? Thank you.
The fastest way is probably to convert them to key => count Dicts and compare those: function counter(it) y = Dict{eltype(it), Int}() for i in it y[i] = get(y, i, 0) + 1 y end length(x1) == length(x2) && counter(x1) == counter(x2)If you need to do this comparison multiple times, you can instead keep the arrays sorted, and compare them directly. 2 Likes
Laco_Kovac: x1 = ["a", "b", "c"] x2 = ["c", "b", "a"] using StatsBase: countmap countmap(x1) == countmap(x2) 2 Likes
If you don’t care about duplicates you can use issetequal: julia> x1 = ["a", "b", "c"]; julia> x2 = ["c", "b", "a"]; julia> x3 = ["a", "b", "c", "a"]; # duplicates julia> issetequal(x1, x2) true julia> issetequal(x1, x3) true4 Likes
fredrikekre:
Laco_Kovac:
i think he cares
Thank you, everyone. I actually don’t envision in my code any possibility of a duplicate in either array. Here are interesting efficiency test results of suggested solutions: @time counter(x1) == counter(x2) 0.000129 seconds (8 allocations: 1.188 KiB) true @time countmap(x1) == countmap(x2) 0.000082 seconds (8 allocations: 1.188 KiB) true @time issetequal(x1, x2) 0.000009 seconds (8 allocations: 960 bytes) true2 Likes
One thing to consider is if you won’t have duplicates and don’t care about order, you should probably be using a set instead of a vector. 2 Likes
As far as I can tell, the most efficient solution, at least for short collections, is: sort(x1) == sort(x2)2 Likes
Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais
Preveja a saída do seguinte programa Java. class Test { public static void main (String[] args) { int arr1[] = {1, 2, 3}; int arr2[] = {1, 2, 3}; if (arr1 == arr2) // Same as arr1.equals(arr2) System.out.println("Same"); else System.out.println("Not same"); } }Saída: Not SameEm Java, os arrays são objetos de primeira classe . No programa acima, arr1 e arr2 são duas referências a dois objetos diferentes. Portanto, quando comparamos arr1 e arr2, duas variáveis de referência são comparadas, portanto, obtemos a saída como “Diferente” (veja isto para mais exemplos). Como comparar o conteúdo do array? Saída: SameComo comparar profundamente o conteúdo do array? Saída: Not SamePortanto, Arrays.equals() não é capaz de fazer uma comparação profunda. Java fornece outro método para este Arrays.deepEquals() que faz uma comparação profunda. import java.util.Arrays; class Test { public static void main (String[] args) { int inarr1[] = {1, 2, 3}; int inarr2[] = {1, 2, 3}; Object[] arr1 = {inarr1}; // arr1 contains only one element Object[] arr2 = {inarr2}; // arr2 also contains only one element if (Arrays.deepEquals(arr1, arr2)) System.out.println("Same"); else System.out.println("Not same"); } }Saída: SameComo funciona Arrays.deepEquals()? Ele compara dois objetos usando qualquer método equals() personalizado que eles possam ter (se eles tiverem um método equals() implementado diferente de Object.equals()). Caso contrário, este método irá então comparar os objetos campo a campo, recursivamente. À medida que cada campo é encontrado, ele tentará usar o equals() derivado se existir, caso contrário, continuará a recursar ainda mais. Este método funciona em um gráfico de objeto cíclico como este: A-> B-> C-> A. Possui detecção de ciclo para que QUALQUER dois objetos possam ser comparados, e nunca entrará em um loop infinito (Fonte: https://code.google.com/p/deep-equals/ ). |