从2D整数数组中删除重复行

时间:2015-01-02 05:53:13

标签: java arrays duplicates 2d rows

我知道之前已经问过这个问题,但是我真的找不到一种工作方法我在以下链接How to construct ArrayList from 2D int array?中尝试了该方法,我认为这与我的情况最相关我应用了以下代码:

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class MonteCarloSim {

    private int[] ints;

    public MonteCarloSim(int[] ints) {
        this.ints = ints.clone();
        Arrays.sort(this.ints);
    }

    @Override
    public int hashCode() {
        return Arrays.hashCode(ints);
    }

    @Override
    public boolean equals(Object obj) {

        if(obj instanceof MonteCarloSim) {
            MonteCarloSim another = (MonteCarloSim) obj;
            int[] original = Arrays.copyOf(another.ints, another.ints.length);
            return Arrays.equals(ints, original);
        } else {
            return false;
        }
    }

    @Override
    public String toString() {
        return Arrays.toString(ints);
    }

    public static void main(String arg[]){

然后我确定了一个零整数数组,一个大小为1000 * 20的元素名为IncProb1我应用以下代码来删除dublicate行:

int[][] arrays = IncProb1;
        Set<MonteCarloSim> rows = new HashSet<MonteCarloSim>();
        for(int[] a: arrays) {
            rows.add(new MonteCarloSim(a));
        }
        for(MonteCarloSim row: rows) {
            System.out.println(row);
        }

但这不起作用我只得到一行,即[0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1 ,1,1,1],这不是解决方案,应该至少有300行不重复。我不知道什么是错的任何帮助都非常感谢 提前致谢

1 个答案:

答案 0 :(得分:0)

以下方法将解决您的问题

public static int[][] removeDuplicateRow(int[][] testArr)
    {
        /**
         * This method will remove the duplicate ROW from 2-D array and replace with {0,0,0}
         * However i assume array rows  =5 and coloums =3 ;) You can have the solution for that I assume
         */

        HashSet<String> hashSet = new HashSet<String>();
        int[][] result = new int[5][3];
        int i = 0;
        for(int[] a : testArr)
        {
            System.out.println(Arrays.toString(a));
            System.out.println(hashSet.contains(a));
            if(!hashSet.contains(Arrays.toString(a))){
                hashSet.add(Arrays.toString(a));
                result[i] = a;
            }
            i++;
        }

        System.out.println("old array : "+Arrays.deepToString(testArr));
        System.out.println("new array : "+Arrays.deepToString(result));

        return result;
    }

希望这有帮助。