Home > OS >  how to find out three consecutive positive integers in an array
how to find out three consecutive positive integers in an array

Time:07-21

i have a list of differences between gain vs loss for every year, some of them are positive and some are negative, now i want to check if there any 3 consecutive years who has positive value as a difference. and if there are any 3 years then i need to select the lowest number out of them.

So in the example given below year 2022 2023 and 2024 has positive int value, among which 59 is the lowest one, so that should be the answer

e.g.

Year         2021   2022   2023  2024   2025   2026
differences   -20    240    59   120    -34     23

CodePudding user response:

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());

The above code first finds the indexes which are positive and their two next elements are also positive. Then it will select an array with three elements containing the positive numbers. At last, we will select the lowest number.
Result:

59

If you want to select the related three years too, you could do something like:

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]}");

Result:

"The score 59 is the lowest in these years: 2022, 2023, 2024"

CodePudding user response:

Why not just loop?

// 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; 

Fiddle

  • Related