[英]How to compare the next value in a array c#
process involves adding toppings to individual pudding that have varying sizes that roll out on a conveyor belt.过程涉及向单个布丁添加浇头,这些布丁具有不同的尺寸,在传送带上铺开。
XXXXXXX XXXXXXX
public class Program
{
static void Main(string[] args)
{
//topping t1 = new topping();
//t1.CalTopping();
topping t1 = new topping();
t1.CalTopping();
}
public class topping
{
public void CalTopping()
{
int[] cupcakes = { 1, 2, 2, 6, 2, 1 };
int tot = 0;
int topping = 0;
//int i=0;
for (int i = 0; i < cupcakes.Length; i++)
{
if (i + 1 < cupcakes.Length)
{
topping = 1;
if (cupcakes[i] == cupcakes[0])
{
topping = 1;
}
else if (cupcakes[i] > cupcakes[i - 1])
{
topping = topping + 1;
}
else
topping = 1;
}
tot = tot + topping;
Console.WriteLine(cupcakes[i] + " = " + topping + "g");
}
Console.WriteLine("total toppings Amount:-" + tot + "g");
}
}
}
} }
You can use the following algorithm to fulfill the requirements:您可以使用以下算法来满足要求:
Processing sequential pairs can be done with a loop like处理顺序对可以通过类似的循环来完成
for (int i = 1; i < cupcakes.Length; i++) {
var current = cupcakes[i];
var previous = cupcakes[i-1];
...
Now, the question specified adjacent and not subsequent .现在,问题指定为相邻而不是后续。 To handle this we also need to do a loop in the reverse order using the same logic, but in this pass we need to take the maximum of the currently assigned topping amount and the new amount.
为了处理这个问题,我们还需要使用相同的逻辑以相反的顺序进行循环,但是在这个过程中,我们需要取当前分配的最高金额和新金额中的最大值。
For example, Cupcakes of size 1, 2, 2, 6, 3, 2, 1
would get toppings of size例如
1, 2, 2, 6, 3, 2, 1
尺寸为 1、2、2、6、3、2、1 的纸杯蛋糕将获得尺寸为
1, 2, 1, 2, 1, 1, 1
1, 2, 1, 2, 1, 1, 1
1, 1, 1, 4, 3, 2, 1
,1, 1, 1, 4, 3, 2, 1
,1, 2, 1, 4, 3, 2, 1
.1, 2, 1, 4, 3, 2, 1
。 This would not fit very well in the conveyor belt analogy since it would require the belt to go backwards and forwards, and require all cupcakes to be placed on the belt.这不太适合传送带的类比,因为它需要将传送带前后移动到 go,并且需要将所有纸杯蛋糕放在传送带上。 But there are real world applications for algorithms like this.
但是有这样的算法在现实世界中的应用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.