AdventOfCode/AdventOfCode.HelperClasses/IntegerRange.cs

60 lines
1.5 KiB
C#

using System.Collections;
namespace AdventOfCode.HelperClasses;
public record IntegerRange(long start, long end) : IEnumerable<long>
{
public long Count => end - start + 1;
public bool Contains(long number) => start <= number && end >= number;
public bool TryCombine(IntegerRange other, out IntegerRange combined)
{
if (Contains(other.start) || other.start == end + 1)
{
var isEndInRange = Contains(other.end);
combined = isEndInRange ? this : this with {end = other.end};
return true;
}
if (other.Contains(start) || start == other.end + 1)
{
var isEndInRange = other.Contains(end);
combined = isEndInRange ? other : other with {end = end};
return true;
}
combined = this;
return false;
}
public IEnumerator<long> GetEnumerator() => new IntegerRangeEnumerator(start, end);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public record IntegerRangeEnumerator(long start, long end) : IEnumerator<long>
{
private long _current = start - 1;
public bool MoveNext()
{
if(_current >= end) return false;
_current++;
return true;
}
public void Reset()
{
_current = start - 1;
}
long IEnumerator<long>.Current => _current;
object? IEnumerator.Current => _current;
public void Dispose()
{
GC.SuppressFinalize(this);
}
}