我列出了每年的得失之间的区别,有些是正面的,有些是负的,现在我想看看是否有连续三年谁有正的价值作为区别。如果有三年的话,我需要从其中选出最低的数目。
因此,在下面给出的例子中,2022 2023和2024的int值为正,其中59是最低的,所以这应该是答案。
例如:
Year 2021 2022 2023 2024 2025 2026
differences -20 240 59 120 -34 23发布于 2022-07-21 10:27:28
int[] differences = new int[] { -20, 240, 59, 120, -34, 23 };
var minScores = Enumerable.Range(0, differences.Length - 2)
.Where(index => differences[index] >= 0 && differences[index + 1] >= 0 && differences[index + 2] >= 0)
.Select(index => new int[] { differences[index], differences[index + 1], differences[index + 2] })
.Select(t => t.Min());上面的代码首先查找正的索引,接下来的两个元素也是正的。然后,它将选择一个包含正数的三个元素的数组。最后,我们将选择最低的数目。
结果:
59
如果您也想选择相关的三年,您可以这样做:
int[] years = new int[] { 2021, 2022, 2023, 2024, 2025, 2026 };
int[] differences = new int[] { -20, 240, 59, 120, -34, 23 };
var consecutiveIndexes = Enumerable.Range(0, differences.Length - 2)
.Where(index => differences[index] >= 0 && differences[index + 1] >= 0 && differences[index + 2] >= 0);
var reports = consecutiveIndexes.Select(index =>
"The score "
+ (new int[] { differences[index], differences[index + 1], differences[index + 2] }).Min()
+ $" is the lowest in these years: {years[index]}, {years[index + 1]}, {years[index + 2]}");结果:
这几年得分最低:2022年,2023年,2024年
发布于 2022-07-21 10:23:18
为什么不直接循环
// let answer be -1, when we don't have three positive consequent numbers
int result = -1;
for (int i = 0, count = 0; i < differences.Length; ++i)
if (differences[i] > 0) {
if (++count >= 3) {
int min =
Math.Min(Math.Min(differences[i - 2], differences[i - 1]), differences[i]);
result = result < 0 ? min : Math.Min(result, min);
}
}
else
count = 0; 发布于 2022-07-21 12:21:13
有了MoreLINQ,它就像:
var values = new (int year, int value)[] {
(2021, -20), (2022, 240), (2023, 59), (2024, 120), (2025, -34), (2026, 23)
};
var minima = values
.Window(3)
.Where(w => w.All(x => x.value > 0))
.Select(w => w.Min(x => x.value))https://stackoverflow.com/questions/73064395
复制相似问题