整数设置交点

时间:2017-03-10 00:57:24

标签: java arrays object set

以下是一个创建整数集的程序,我相信我已经完成了所有工作,除了我的intersectionWith函数无法正常工作。

这是我的IntSet代码:

import java.lang.Math;
import java.util.Random;
public class Program {

    public static void main(String [] args){
        Random rng = new Random();
        rng.setSeed(0);
        IntSet is1, is2, is3, is4;
        is1 = new IntSet(2,4,5);
        is2 = new IntSet(1,2,5);
        is3 = new IntSet();
        is4 = new IntSet(is2);

        is3.setTo(is1.intersectionWith(is2));
        System.out.print("is3 (intersection): ");
        System.out.println(is3.toString()); // should be 2 5
    }
}

我的程序代码:

is3 (intersection): {2, 4, 5, }

除了我的交叉功能外,一切似乎对我有用。

这是我运行代码时输出的内容:

Column PremiumVsPlan = Premium / TotalForcast

但它需要的只是{2,5}

我不确定如何收到此错误。

我的intersectionWith函数应该基于两组创建一个新的集合。如果该元素在两个集合中都存在,它只会向新集合添加一个元素。

2 个答案:

答案 0 :(得分:1)

对不起伙计看起来好像我搞清楚了。我只需要添加一个else语句:

 public IntSet intersectionWith(IntSet other) {
        IntSet newSectionSet = new IntSet(this);
        for(int iteration = 0; iteration < MAXALLOWEDSETVALUE; iteration++) {
            if(newSectionSet.data[iteration] == true && other.data[iteration] == true) {
                newSectionSet.data[iteration] = true;
            } else {
               newSectionSet.data[iteration] = false; // added this
            }
        }
        return newSectionSet;
    }

答案 1 :(得分:1)

我只会发布相关代码,并在我添加更改的位置添加评论:

class IntSet{

    private final int MAXALLOWEDSETVALUE = 5; // modified it to a smaller number - easier to debug
    private boolean [] data = new boolean[MAXALLOWEDSETVALUE+1];

    public static void main(String [] args){
        Random rng = new Random();
        rng.setSeed(0);
        IntSet is1, is2, is3;
        is1 = new IntSet(1,2,3);
        is2 = new IntSet(1,2,5);
        is3 = is1.intersectionWith(is2); // I modified the test cases
        System.out.println(is1); // [false, true, true, true, false, false, false]
        System.out.println(is2); // [false, true, true, false, false, true, false]
        System.out.println(is3); // [false, true, true, false, false, false, false]
    }

    @Override
    public String toString() { // added a toString method for a nicer printing
        return Arrays.toString(data);
    }

    public IntSet(int... elts) {
        for(int iteration = 0; iteration < elts.length; iteration++) {
            if(elts[iteration] <= MAXALLOWEDSETVALUE)
                data[elts[iteration]] = true;
        }
    }

    public IntSet intersectionWith(IntSet other) {
        IntSet newSectionSet = new IntSet(); // instead of copying and modifying the copy - just create an "empty" set and update it
        for(int iteration = 0; iteration < MAXALLOWEDSETVALUE; iteration++) {
            if(data[iteration] && other.data[iteration]) { // now the comparison is done directly against `data`
                newSectionSet.data[iteration] = true;
            }
        }
        return newSectionSet;
    }
}