about summary refs log tree commit diff
path: root/lib/Extensions.cs
blob: eb8c3cbb4ce4f0556a3ac90355be05fc0228123d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace aoc2019.lib
{
    public static class Extensions
    {
        public static IEnumerable<IEnumerable<T>> Permute<T>(this IEnumerable<T> list)
        {
            if (list.Count() == 1) return new[] {list};
            return list.SelectMany(t => Permute(list.Where(x => !x.Equals(t))), (v, p) => p.Prepend(v));
        }

        public static IEnumerable<string> Chunk(this string str, int chunkSize)
        {
            for (var i = 0; i < str.Length; i += chunkSize)
                yield return str.Substring(i, chunkSize);
        }

        public static string ToDelimitedString<T>(this IEnumerable<T> enumerable, string delimiter = "")
        {
            return string.Join(delimiter, enumerable);
        }

        public static IEnumerable<T> Repeat<T>(this IEnumerable<T> sequence, int? count = null)
        {
            while (count == null || count-- > 0)
                foreach (var item in sequence)
                    yield return item;
        }

        /// <summary>
        ///     increased accuracy for stopwatch based on frequency.
        ///     <see
        ///         href="http://geekswithblogs.net/BlackRabbitCoder/archive/2012/01/12/c.net-little-pitfalls-stopwatch-ticks-are-not-timespan-ticks.aspx">
        ///         blog
        ///         details here
        ///     </see>
        /// </summary>
        /// <param name="stopwatch"></param>
        /// <returns></returns>
        public static double ScaleMilliseconds(this Stopwatch stopwatch)
        {
            return 1_000 * stopwatch.ElapsedTicks / (double) Stopwatch.Frequency;
        }
    }
}