namespace AdventOfCode.Utils;
public static class Extensions
{
public static int Signal(this int x)
{
return x switch
{
< 0 => -1,
> 0 => 1,
_ => 0
};
}
///
/// Returns a slice of the given list
///
/// The list you pretend to slice
/// The first index of the slice
/// The index after the last index of the slice
///
public static List Sublist(this List list, int startIndex, int endIndex)
{
List result = new List();
for (int i = startIndex; i < endIndex; i++)
result.Add(list[i]);
return result;
}
///
/// Returns a column of a give matrix list
///
/// 2 dimensions list
/// Column index
///
public static List GetColumn(this List> list, int column)
{
List result = new List();
foreach (List row in list) result.AddRange(row.Where((t, i) => i == column));
return result;
}
///
/// Reverses a given list
///
/// The list to reverse
/// The reversed list
public static List Reversed(this List list)
{
List reversed = new List();
for (int i = 0; i < list.Count; i++)
reversed.Add(list[list.Count-1-i]);
return reversed;
}
///
/// Clones a list of elements
///
/// The original list
/// A copy of the original list
public static List Clone(this List original)
{
List ret = new List(original.Count);
foreach (T element in original)
ret.Add(element);
return ret;
}
public static Dictionary Clone
(this Dictionary original)
where TValue : ICloneable
where TKey : notnull
{
Dictionary ret = new Dictionary(original.Count, original.Comparer);
foreach (KeyValuePair entry in original)
ret.Add(entry.Key, (TValue) entry.Value.Clone());
return ret;
}
public static Dictionary> Clone
(this Dictionary> original)
where TKey : notnull
{
Dictionary> ret = new Dictionary>(original.Count, original.Comparer);
foreach (KeyValuePair> entry in original)
ret.Add(entry.Key, entry.Value.Clone());
return ret;
}
public static void Fill(this List list, int count, T element)
where T : ICloneable
{
for (int i = 0; i < count; i++)
list.Add(element);
}
public static void Fill(this List> list, int count, List element)
{
for (int i = 0; i < count; i++)
list.Add(element.Clone());
}
public static void Set(this List list, int index, T element)
{
List backup = list.Clone();
list.Clear();
for (int i = 0; i < list.Count; i++) list.Add(i == index ? element : list[i]);
}
}