Duplicates in 2 Dimensional Array

How to remove duplicate values from a multi-dimensional array in PHP

Here is another way. No intermediate variables are saved.

We used this to de-duplicate results from a variety of overlapping queries.

$input = array_map("unserialize", array_unique(array_map("serialize", $input)));

How to find or count the duplicate in multidimensional array in c#

You can try HashSet<int>, e.g.

   int[,] arr = new int[3, 3] {
{1, 2, 6 },
{4, 1, 5 },
{6, 1, 8 }
};

HashSet<int> unique = new HashSet<int>();

foreach (var item in arr)
if (!unique.Add(item))
Console.WriteLine(item); // Not unique, print it out

Outcome:

  1
6
1

If we want to print each duplicate once, we can add another HashSet<int>:

   HashSet<int> unique = new HashSet<int>();
HashSet<int> duplicates = new HashSet<int>();

foreach (var item in arr)
if (!unique.Add(item))
duplicates.Add(item);

foreach (var item in duplicates)
Console.WriteLine(item);

Finally, if you want to count duplicate occurences we can change HashSet<int> duplicates into Dictionary<int, int> duplicates:

   HashSet<int> unique = new HashSet<int>();

Dictionary<int, int> duplicates = new Dictionary<int, int>();

foreach (var item in arr)
if (!unique.Add(item))
if (duplicates.TryGetValue(item, out int count))
duplicates[item] = count + 1;
else
duplicates[item] = 2;

foreach (var item in duplicates)
Console.WriteLine($"{item.Key} appears {item.Value} times");

Edit: you can change foreach loop into nested for ones, e.g:

All duplicates

   for (int i = 0; i < arr.GetLength(0); ++i)
for (int j = 0; j < arr.GetLength(1); ++j)
if (!unique.Add(arr[i, j]))
Console.WriteLine(arr[i, j]);

Distinct duplicates

   HashSet<int> duplicates = new HashSet<int>();

for (int i = 0; i < arr.GetLength(0); ++i)
for (int j = 0; j < arr.GetLength(1); ++j)
if (!unique.Add(arr[i, j]))
if (duplicates.Add(arr[i, j])) // print distinct duplicate only
Console.WriteLine(arr[i, j]);

Check duplicate in rows and columns 2D Array

Go through each value in the row. For every value, check and see if any of the values after that value are the same. If the value is the same, return true (you've found a duplicate). If none of the values are the same, increment your index and do the same for the next row. Every row will take at most n(n+1)/2 comparisions which isn't wonderful. So if n is the number of columns and m in the number of rows, this will run, worst case m(n(n+1)/2) times.

Here is an example of how it would work for the rows:

/**
* Return flag indicating if there are duplicates in the rows of the 2D array
*
* @return true if a row has duplicates, else false
*/
public boolean hasDuplicatesInRows(int[][] inArray)
{
for (int row = 0; row < inArray.length; row++)
{
for (int col = 0; col < inArray[row].length; col++)
{
int num = inArray[row][col];
for (int otherCol = col + 1; otherCol < inArray.length; otherCol++)
{
if (num == inArray[row][otherCol])
{
return true;
}
}
}
}

return false;
}

That would be pretty easy to extend to do columns as well. I will leave that for you to do though.

If you used an efficient sorting method and sorted all the rows, you could just go down the line and see if any value was equal to the value after it. If it is, return true, else return false. This would be more efficient if you had a large data set.

Find duplicate elements in 2d array

Here is the solution to find count of duplicate elements in a 2D matrix without using collection
public class DuplicateElementsCountIn2DMetrixWithoutUsingCollections{

public static void main(String args[]){
String[][] matrix = {{"1","2","1","3",},{"7","6","null","2",},{"5","6","3","null",},{"3","10","9","5",}};
System.out.println(findDuplicate(matrix));
}

public static int findDuplicate(String[][] matrix){
String strArr[] = new String[(matrix.length)*(matrix[0].length)];
int count = 0;
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
for(int k = 0; k < matrix.length; k++){
for(int l = 0; l < matrix[0].length; l++){
if((i!=k || j!=l)){
if(matrix[i][j] == matrix[k][l]){
int x = 0;
boolean flag = false;
while(strArr[x] != null){
if(null != matrix[i][j] && matrix[i][j].equals(strArr[x])){
flag = true;
}
x++;
}
if(flag==false){
strArr[count] = matrix[i][j];
count++;
}
}
}
}
}
}
}
return count;
}

}

Output

6

Note : 1, 2, 3, 6, null are duplicate in matrix, hence count is 6

Remove duplicates from a multi-dimensional array

Are arrays equatable? Can I compare them using ==

Prior to Swift 4.1, Array didn't conform Equatable. There was however an overload of == that compared two arrays with Equatable elements, which is what enabled this to compile:

if ["1", "2"] == ["1", "2"] { // using <T : Equatable>(lhs: [T], rhs: [T]) -> Bool
print("true")
}

However in Swift 4.1 (available with Xcode 9.3), Array<Element> now conforms to Equatable when its Element conforms to Equatable. This change is given in the changelog:

Swift 4.1


[...]

  • SE-0143 The standard library types Optional, Array, ArraySlice, ContiguousArray, and Dictionary now conform to the Equatable protocol when their element types conform to Equatable. This allows the == operator to compose (e.g., one can compare two values of type [Int : [Int?]?] with ==), as well as use various algorithms defined for Equatable element types, such as index(of:).

Your example with multiDimArr.removeDups() compiles and runs as expected in 4.1, yielding the result [[1, 2, 3], [1, 2, 4]].

In Swift 4.0.3, you could hack it by adding another overload of removeDups() for nested arrays:

extension Array {
func removeDups<T : Equatable>() -> [Element] where Element == [T] {

var result = [Element]()

for element in self{
if !result.contains(where: { element == $0 }) {
result.append(element)
}
}

return result
}
}

let multiDimArr = [[1, 2, 3], [1, 2, 3], [1, 2, 4]]
print(multiDimArr.removeDups()) // [[1, 2, 3], [1, 2, 4]]

This does unfortunately lead to some code duplication, but at least you'll be able to get rid of it when updating to 4.1.

The fact that this example doesn't compile in either 4.0.3 or 4.1:

if [1, 2] == [1, 2] { // error: Ambiguous use of operator '=='
print("true")
}

is due to the bug SR-5944 – the compiler is considering it to be ambiguous due to == overloads for IndexSet and IndexPath (both of which are ExpressibleByArrayLiteral). But Swift should default an array literal to Array though, resolving the ambiguity.

Saying either:

if [1, 2] as [Int] == [1, 2] {
print("true")
}

or not importing Foundation resolves the issue.


Finally, it's worth noting that the performance of removeDups() can be improved if the Element type is also Hashable, allowing it to run in linear, rather than quadratic time:

extension Array where Element : Hashable {

func removeDups() -> [Element] {
var uniquedElements = Set<Element>()
return filter { uniquedElements.insert($0).inserted }
}
}

Here we're using a set to store the elements that we've seen, omitting any that we've already inserted into it. This also allows us to use filter(_:), as @Alexander points out.

And in Swift 4.2, Array also conditionally conforms to Hashable when its Element is Hashable:

Swift 4.2


[...]

  • SE-0143 The standard library types Optional, Array, ArraySlice, ContiguousArray, Dictionary, DictionaryLiteral, Range, and ClosedRange now conform to the Hashable protocol when their element or bound types (as the case may be) conform to Hashable. This makes synthesized Hashable implementations available for types that include stored properties of these types.

Remove duplicates in two-dimensional array

You can use a temporary Set for getting unique values.

I would also use the Array.from callback argument to immediately map the HTML elements to their split innerHTML values, and then chain a .map to map those subarrays to the final display strings.

You can form the final HTML output by a simple .join:

var debug = document.getElementById("dbg");
var zlec = document.getElementsByClassName("path");
var arry = Array.from(zlec, elem =>
elem.innerHTML.split("/")
).map(([,,,,cust, ord]) =>
`Customer: ${cust} - Order no.: ${ord}`
);

debug.innerHTML = [...new Set(arry)].join("<br>");
<div class="path">/PSO/Orders/2021/Shell/12345678/grade/thickness/filenamewithextension</div>
<div class="path">/PSO/Orders/2021/NASA/829384751/grade/thickness/filenamewithextension</div>
<div class="path">/PSO/Orders/2021/Wallmart/927465822/grade/thickness/filenamewithextension</div>
<hr>
<div id="dbg"></div>


Related Topics



Leave a reply



Submit