首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在数组中找出三个连续的正整数

如何在数组中找出三个连续的正整数
EN

Stack Overflow用户
提问于 2022-07-21 10:15:42
回答 3查看 92关注 0票数 -2

我列出了每年的得失之间的区别,有些是正面的,有些是负的,现在我想看看是否有连续三年谁有正的价值作为区别。如果有三年的话,我需要从其中选出最低的数目。

因此,在下面给出的例子中,2022 2023和2024的int值为正,其中59是最低的,所以这应该是答案。

例如:

代码语言:javascript
复制
Year         2021   2022   2023  2024   2025   2026
differences   -20    240    59   120    -34     23
EN

回答 3

Stack Overflow用户

发布于 2022-07-21 10:27:28

代码语言:javascript
复制
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

如果您也想选择相关的三年,您可以这样做:

代码语言:javascript
复制
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年

票数 1
EN

Stack Overflow用户

发布于 2022-07-21 10:23:18

为什么不直接循环

代码语言:javascript
复制
// 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; 

小提琴

票数 0
EN

Stack Overflow用户

发布于 2022-07-21 12:21:13

有了MoreLINQ,它就像:

代码语言:javascript
复制
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))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73064395

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档