考虑保留在两个数组中的两个集合。找出两组的并集,相交和差(相对补)。
我设法解决了联合和相交的问题,但是区别让我很难受。有什么提示吗?并且,如果可能的话,请使其尽可能简单,不要使用功能,也不要考虑更复杂的方面,因为我是一个初学者,但是我仍有很多东西要学习。
提前谢谢!
#include <iostream>
using namespace std;
int main()
{
int v1[100], v2[100], u[200], intersection[100], d[100];
unsigned int v1_length, v2_length, i, j, OK = 0, union_length;
cout << "Enter the number of elements of the first array:" << " ";
cin >> v1_length;
cout << "Enter the elements of the first array:" << '\n';
for (i = 0; i < v1_length; i++)
cin >> v1[i];
cout << "Enter the number of elements of the second array:" << " ";
cin >> v2_length;
cout << "Enter the elements of the second array:" << '\n';
for (i = 0; i < v2_length; i++)
cin >> v2[i];
//Union
union_length = v1_length;
for (i = 0; i < v1_length; i++)
u[i] = v1[i];
for (i = 0; i < v2_length; i++)
{
int ok = 0;
for (j = 0; !ok && j < v1_length; j++)
if (v1[j] == v2[i])
ok = 1;
if (!ok)
{
u[union_length] = v2[i];
union_length++;
}
}
cout << "The union of the two sets contained in the arrays is: ";
for (i = 0; i < union_length; i++)
cout << u[i] << " ";
cout << '\n';
//Intersection
unsigned int k = 0;
cout << "The intersection of the two sets contained in the arrays is: ";
for (i = 0; i < v1_length; i++)
for (j = 0; j < v2_length; j++)
if (v1[i] == v2[j])
{
intersection[k] = v1[i];
k++;
}
for (i = 0; i < k; i++)
cout << intersection[i] << " ";
cout << '\n';
//Difference
unsigned int l = 0, OK2 = 0;
cout << "The difference of the two sets contained in the arrays is: ";
for (i = 0; i < v1_length; i++)
{
for (j = 0; j < v2_length; j++)
{
if (v1[i] == v2[j])
OK2 = 1;
if (!OK2)
{
d[l] = v1[i];
l++;
}
}
}
for (i = 0; i < l; i++)
cout << d[i] << " ";
cout << '\n';
return 0;
}
答案 0 :(得分:0)
您在正确的轨道上!
您做错了几件事。您可以尝试以下一些修复:
OK2
设置为0
OK2
重置为0
d
作为一种优化,在将break
设置为OK2
之后,考虑将1
设置为0
,因为您永远不会将当前值设置为var tracks = [
{ id: 0, vibe: "downtempo" },
{ id: 1, vibe: "midtempo" },
{ id: 2, vibe: "uptempo" },
{ id: 3, vibe: "uptempo" },
{ id: 4, vibe: "midtempo" },
{ id: 5, vibe: "downtempo" },
{ id: 6, vibe: "midtempo" },
{ id: 7, vibe: "midtempo" },
{ id: 8, vibe: "uptempo" },
{ id: 9, vibe: "uptempo" },
...
{ id: 100, vibe: "midtempo" },
];
由外循环指向。
答案 1 :(得分:0)
看来交叉路口是最好的起点。您想要只出现在两个数组之一中的项目,对吗?
因此,对于内部循环,您需要比较所有元素。然后,如果找不到匹配项,则您具有唯一元素。
您需要将花括号{}添加到for循环中。我知道花括号有时会分散注意力,但是随着时间的推移,您可能会发现几乎总是包含花括号会更安全,以免造成混淆。
for (i = 0; i < v1_length; i++)
for (j = 0; j < v2_length; j++) {
if (v1[i] == v2[j]){
break; // this item is not unique
} else if(j == v2_length - 1){
d[l] = v1[i]; // This is the unique one, add it to the answer array
l++;
}
}
for (i = 0; i < l; i++)
cout << intersection[l] << " ";
cout << '\n';