utils.cs

View source code here on GitHub!

Includes

class Utilities
static String GetDataFileText (String name)
static Byte[] GetDataFileBytes (String name)
static object GetAnswer (UInt64 n)
 1using System.Diagnostics;
 2using System.IO;
 3using System.Runtime.InteropServices;
 4
 5namespace Euler
 6{
 7    public static class Utilities
 8    {
 9        private static string GetDataPath(string name)
10        {
11            string? thisFile = new StackTrace(true).GetFrame(0)?.GetFileName();
12            if (thisFile is null)
13                throw new IOException();
14            return Path.Join(thisFile, "..", "..", "..", "..", "_data", name);
15        }
16
17        public static string GetDataFileText(string name)
18        {
19            if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("WEBASSEMBLY")))
20                return WasmIOFallback.GetText(name);
21            return File.ReadAllText(GetDataPath(name));
22        }
23
24        public static byte[] GetDataFileBytes(string name)
25        {
26            if (RuntimeInformation.IsOSPlatform(OSPlatform.Create("WEBASSEMBLY")))
27                return WasmIOFallback.GetBytes(name);
28            return File.ReadAllBytes(GetDataPath(name));
29        }
30
31        public static object GetAnswer(ulong n)
32        {
33            foreach (string line in GetDataFileText("answers.tsv").Split(new[] { '\r', '\n' }))
34            {
35                var arr = line.Split("\t");
36                if (arr[0] != n.ToString()) continue;
37                switch (arr[1])
38                {
39                    case "str":
40                        return arr[3];
41                    case "int":
42                        switch (int.Parse(arr[2]))
43                        {
44                            case 8:
45                                return sbyte.Parse(arr[3]);
46                            case 16:
47                                return short.Parse(arr[3]);
48                            case 32:
49                                return int.Parse(arr[3]);
50                            case 64:
51                                return long.Parse(arr[3]);
52                        }
53                        break;
54                    case "uint":
55                        switch (int.Parse(arr[2]))
56                        {
57                            case 8:
58                                return byte.Parse(arr[3]);
59                            case 16:
60                                return ushort.Parse(arr[3]);
61                            case 32:
62                                return uint.Parse(arr[3]);
63                            case 64:
64                                return ulong.Parse(arr[3]);
65                        }
66                        break;
67                }
68            }
69            throw new IOException();
70        }
71    }
72}

Tags: file-io