我不是在寻找直接的答案,而是某种指导。如果您要发布整理的代码,请解释一下所有内容,因为我想学习更多。
我正在尝试计算和输出两个数组之间的重叠。到目前为止,这是我的代码。
class Tester
{
static void Main(string[] args)
{
Box[] boxArray1 = {
new Box(4, 3, 2, "white"),
new Box(9, 5, 6, "red"),
new Box(3, 6, 12, "purple"),
new Box(15, 10, 4, "orange"),
new Box(4, 14, 10, "black"),
};
Box[] boxArray2 = {
new Box(3, 4, 2, "pink"),
new Box(10, 2, 4, "red"),
new Box(8, 5, 7, "white"),
new Box(14, 4, 10, "blue"),
new Box(10, 15, 4, "bindle"),
};
}//end of static main
static void calculate1(Box[] box1) // <== Here's my attempt at calculating the overlaps.
{
string[] name = box1[i].Split(' ');
int gr1 = box1.Length;
int[] gg1 = new int[gr1];
for (int i = 0; i < box1.Length; i++)
{
gg1[i] = int.Parse(box1[i]);
}
}
}//end of class Tester
class Container
{
public string Colour { get; set; }
public Container(string co)
{
Colour = co;
}
public virtual string GetContainerType()
{
return "Unknown";
}
}//end of class Container
class Box : Container
{
public double Length { get; set; }
public double Height { get; set; }
public double Width { get; set; }
public Box(double Le, double He, double Wi, string co)
: base(co)
{
Length = Le;
Height = He;
Width = Wi;
}
public override string GetContainerType()
{
return "Box";
}
public double GetVolume()
{
return Length * Height * Width;
}
}//end of class Box
如顶部所示,有盒子的尺寸和颜色。我想找到这两个数组之间的重叠,例如在两个数组中都显示了“白色”和“红色”。然后我要计算然后输出“两个数组之间有重叠颜色的2个Box对象。”,然后对Dimensions执行相同的操作。
谢谢。
最佳答案
回答问题中的最后一条评论,进行检查以创建一个双循环并检查属性:
List<string> duplicatedColors = new List<string>();
for (int i = 0; i < boxArray1.Length; i++) //Loop through the first array
{
for (int j= 0; j < boxArray2.Length; j++) //Loop through the second array
{
if(boxArray1[i].Color == boxArray2[j].Color) //Do element at array 1 have the same color that the item at array 2?
{
//Yes, store color and break inner loop
duplicatedColors.Add(boxArray1[i].Color);
break;
}
//No, continue loop
}
}
//Here now you have all the duplicated colors in duplicatedColors
//You can use duplicatedColors.Count to get the number of items dupicated.
好了,现在为卷:
List<double> duplicatedVolumes = new List<double>();
for (int i = 0; i < boxArray1.Length; i++) //Loop through the first array
{
for (int j= 0; j < boxArray2.Length; j++) //Loop through the second array
{
var volumeA = boxArray1[i].Length * boxArray1[i].Width * boxArray1[i].Height; //Compute box A volume
var volumeB = boxArray2[j].Length * boxArray2[j].Width * boxArray2[j].Height; //Compute box B volume
if(volumeA - double.Epsilon < volumeB && volumeA + double.Epsilon > volumeB)
{
//Check if the volumes are equal, note the use of the Epsilon, that's because
//double values aren't exact and we must have that into account. double.Epsilon
//is the smallest (not lowest) value a double can store so it's very
//thightened, you can increase this value if you have errors.
duplicatedVolumes.Add(volumeA);
break;
}
//No, continue loop
}
}
关于c# - C#计算数组之间的重叠,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43794572/