java - 显示 2 个数组的交集
问题描述
我正在尝试找到一种方法来显示我的 2 组包含元素的数组的交集。我找不到显示路口的方法
这是一种查找数组交集的方法
enum Month {
Jan ("Janurary","01"),
Feb ("Feburary","02"),
Mar ("March","03"),
Apr ("April","04"),
May ("May","05"),
Jun ("June","06"),
Jul ("July","07"),
Aug ("August","08"),
Sep ("September","09"),
Oct ("October","10"),
Nov ("November","11"),
Dec ("December","12");
private final String day; //day of the month
private final String date; //name of the date
//enum constructor
Month(String date, String day)
{
this.date=date;
this.day=day;
}
//accessor for field day
public String getDay() {
return day;
}
//accessor fpr field month
public String getDate() {
return date;
}
}
class Set{
...
...
...
public void intersection(Set otherSet)
{
for(int x=0; x< otherSet.s.size(); x++)
{
if(belongTo(otherSet.s.get(x)))
{
addElement(otherSet.s.get(x));
}
}
}
此方法是获取数组中的一组随机元素。2个不同的类,类Set有其他方法来计算其他东西。主要类是显示它
class Test{
...
...
...
private static Set getASet()
{
//Set s=new Set()
Set s=new Set();
int rand=(int)(Math.random()*12);
for(int i=0;i<=rand;i++)
{
s.addElement(getAnElement());
}
return s;
}
}
private static void intersectionExample() {
Set A=getASet();
Set B=getASet();
Set u=new Set();
u= A.intersection(B);
System.out.println("Given sets");
System.out.printf("A={%s}%n", A.toString());
System.out.printf("B={%s}%n",B.toString());
System.out.printf("Intersection of A and B = {%s}", u.toString());
}
解决方案
public class Test {
private static Integer getAnElement() {
return (int) (Math.random() * 10);
}
private static Set getASet() {
//Set s=new Set()
Set<Integer> s = new HashSet();
int rand = (int) (Math.random() * 12);
for (int i = 0; i <= rand; i++) {
s.add(getAnElement());
}
return s;
}
private static Set intersection(Set A , Set B) {
Set<Integer> s = new HashSet();
Iterator<Integer> it = A.iterator();
while(it.hasNext()){
Integer i = it.next();
if(B.contains(i)) s.add(i);
}
return s;
}
public static void main(String[] args) {
Set A = getASet();
Set B = getASet();
Set u = intersection(A, B);
System.out.println("Given sets");
System.out.printf("A={%s}%n", A.toString());
System.out.printf("B={%s}%n", B.toString());
System.out.printf("Intersection of A and B = {%s}%n", u.toString());
}
}
输出:
Given sets
A={[0, 3, 7, 8]}
B={[0, 1, 3, 4, 6, 7, 9]}
Intersection of A and B = {[0, 3, 7]}
推荐阅读
- python - 如何在不收到错误消息的情况下导入 tensorflow?
- powerbi - Power BI - 从同一行中减去值
- python - 'tee' 不是内部或外部命令、可运行程序或批处理文件
- java - Java 将图像附加到 JTextArea
- angular - Angular 9 单元测试业力
- python - 如何使用 matplotlib 让图例显示在图表中
- java - 在文本中搜索 REGEX 值
- c++ - CUDA:让内核将函数指针作为参数
- bezier - Inkscape 自动平滑节点背后的算法
- javascript - 数据方法中的数组在一种方法中得到更新,但在另一种方法中仍然为空