chore(CSharp): add minima maxima (#730)

Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com>
pull/737/head
Mohammadreza Heidari 2022-04-07 17:27:12 +03:00 committed by GitHub
parent 158d8c0d49
commit 2c22117eb2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 126 additions and 0 deletions

View File

@ -26,6 +26,7 @@ For running the `.cs` file please using [.Net Finddle](https://dotnetfiddle.net/
## Search
- [Binary Search](src/Search/binary-search.cs)
- [Linear Search](src/Search/linear-search.cs)
- [Minima Maxima](src/Search/minima-maxima.cs)
## Maths
- [Abundant Number](src/Maths/abundant-number.cs)

View File

@ -0,0 +1,100 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace Algorithms.Search
{
public class MinimaMaxima
{
public static void Main()
{
var numbers = new List<int>
{
3,1,2,5,6,7,4,6,9,10
};
var minimas = FindMinimas(numbers);
var maximas = FindMaximas(numbers);
foreach (var minima in minimas)
{
Console.WriteLine($"Local Minima: {minima}");
}
foreach (var maxima in maximas)
{
Console.WriteLine($"Local Maxima: {maxima}");
}
}
public static List<int> FindMinimas(List<int> numbers)
{
var result = new List<int>();
if (numbers.Count < 3)
{
result.Add(numbers.Min());
}
else
{
// Check first element
if (numbers[0] < numbers[1])
{
result.Add(numbers[0]);
}
//Loop middle elements
for (int i = 1; i < numbers.Count - 1; i++)
{
if (numbers[i - 1] >= numbers[i] && numbers[i] <= numbers[i + 1])
{
result.Add(numbers[i]);
}
}
//Check last elements
if (numbers[^1] < numbers[^2])
{
result.Add(numbers[^1]);
}
}
return result;
}
public static List<int> FindMaximas(List<int> numbers)
{
var result = new List<int>();
if (numbers.Count < 3)
{
result.Add(numbers.Max());
}
else
{
// Check first element
if (numbers[0] > numbers[1])
{
result.Add(numbers[0]);
}
//Loop middle elements
for (int i = 1; i < numbers.Count - 1; i++)
{
if (numbers[i - 1] <= numbers[i] && numbers[i] >= numbers[i + 1])
{
result.Add(numbers[i]);
}
}
//Check last elements
if (numbers[^1] > numbers[^2])
{
result.Add(numbers[^1]);
}
}
return result;
}
}
}

View File

@ -0,0 +1,25 @@
using Algorithms.Search;
using NUnit.Framework;
using System.Linq;
namespace Algorithms.Tests.Search
{
[TestFixture]
public class MinimaMaximaTest
{
[TestCase(new int[] { 3, 1, 2, 5, 6, 7, 4, 6, 9, 10 }, new int[] { 1, 4 })]
public void PassIntegerList_ShouldGetExpectedMinimas(int[] input, int[] result)
{
var expected1 = MinimaMaxima.FindMinimas(input.ToList());
Assert.AreEqual(expected1, result);
}
[TestCase(new int[] { 3, 1, 2, 5, 6, 7, 4, 6, 9, 10 }, new int[] { 3, 7, 10 })]
public void PassIntegerList_ShouldGetExpectedMaximas(int[] input, int[] result)
{
var expected1 = MinimaMaxima.FindMaximas(input.ToList());
Assert.AreEqual(expected1, result);
}
}
}