VM Exec(string datafile) { vm0 = new VM(); vm1 = new VM(); var q0to1 = new Queue <long>(); var q1to0 = new Queue <long>(); vm0.send = q0to1; vm0.recv = q1to0; vm1.send = q1to0; vm1.recv = q0to1; vm0.setReg('p', 0); vm1.setReg('p', 1); vm0.prog = vm1.prog = FileIterator.LoadLines <string>(datafile); currentVM = vm1; while (true) { ExecInstruction(currentVM); if (currentVM.IsDone) { break; } if (vm0.IsWaitingForInput && vm1.IsWaitingForInput) { break; } } return(vm1); }
public void Problem1() { FileIterator.Lines("Data/Day05.txt") .Select(ParseSeatId) .Max() .Should().Be(911); }
protected override void onIteratorClosed(FileIterator iterator) { JobFileIterator ftiterator = (JobFileIterator)iterator; lock (dictionaryLock) { long fileLength = new System.IO.FileInfo(ftiterator.filePath).Length; int count; if (openedFiles.TryGetValue(ftiterator.filePath, out count)) { count -= 1; if (count == 0) { openedFiles.TryRemove(ftiterator.filePath, out count); File.Delete(ftiterator.filePath); //if (ftiterator.Job.Task.Info.Count != 1) if (Path.GetDirectoryName(ftiterator.filePath) != zipTempFolder) { Directory.Delete(Path.GetDirectoryName(ftiterator.filePath)); } } else { openedFiles.TryUpdate(ftiterator.filePath, count, count + 1); } } } }
static int CalcJolts(string input) { var prevJolt = 0; var jump1 = 0; var jump3 = 1; // Include the final 3 jolt jump up front foreach (var jolt in FileIterator.Lines <int>(input).OrderBy((v) => v)) { switch (jolt - prevJolt) { case 1: jump1++; break; case 2: break; case 3: jump3++; break; default: Oh.Bugger(); break; } prevJolt = jolt; } return(jump1 * jump3); }
static void Main(string[] args) { int checksum = 0; foreach (string line in FileIterator.Create("./input.txt")) { int[] values = line.Split('\t', StringSplitOptions.RemoveEmptyEntries).Select(int.Parse) .ToArray(); for (int i = 0; i < values.Length; i++) { List <int> temp = new List <int>(values); temp.RemoveAt(i); List <int> mods = temp.Select(v => values[i] % v).ToList(); int idx = mods.IndexOf(0); if (idx >= 0) { int otherNumber = temp[idx]; checksum += values[i] / otherNumber; break; } } } Console.WriteLine($"The checksum is {checksum}"); Console.ReadKey(true); }
static (int[] counts, int threshold) ParseCountsThreshold(string inputFilename) { int[] counts = null; var threshold = 0; FileIterator.ForEachLine <string>(inputFilename, line => { if (counts == null) { counts = new int[line.Length]; } for (var i = 0; i < line.Length; i++) { if (line[i] == '1') { counts[i]++; } } threshold++; }); threshold /= 2; return(counts, threshold); }
static Graph LoadBags(string input) { var graph = new Graph(); foreach (var line in FileIterator.Lines(input)) { var groups = line.Groups("^(.+) bags contain (.+)\\.$"); var bagType = groups[0]; var bagNode = graph.GetOrCreate(bagType, () => (new(), new())); if (groups[1] != "no other bags") { var children = groups[1].Split(','); foreach (var child in children) { groups = child.Groups("(\\d+) (.+) bag"); bagNode.Item2.Add((int.Parse(groups[0]), groups[1])); var childNode = graph.GetOrCreate(groups[1], () => (new(), new())); childNode.Item1.Add(bagType); } } } return(graph); }
public override Result Process(string path, bool trackReports = false) { var result = new Result { Name = Path.GetFileName(path), Path = path }; FileIterator it = null; try { it = new FileIterator(path); foreach (var content in it.Iterate("expr", "supexpr")) { result.MethodCount += this.Occurs("PROCEDURE", content); this.InspectLines(content, result); } } catch (Exception e) { result.IsError = true; result.ErrorMessage = e.Message; result.Exception = e; } finally { if (it != null) { it.Dispose(); } } return(result); }
public void Part1(string input, string answer) { var lines = FileIterator.LoadLines <string>(input); var tree = BuildTree(lines); tree.Name.Should().Be(answer); }
static int CountValid(string input, Func <PasswordEntry, bool> validator) { return(FileIterator.Lines(input) .Select((e) => new PasswordEntry(e)) .Where(validator) .Count()); }
static List <Answers> LoadAnswers(string input) { var answers = new List <Answers>(); var currentGroup = new Answers(); answers.Add(currentGroup); FileIterator.ForEachLine(input, (string line) => { if (line == "") { currentGroup = new Answers(); answers.Add(currentGroup); return; } currentGroup.Increment(GROUP_SIZE); foreach (var c in line) { currentGroup.Increment(c); } }); return(answers); }
static void Main(string[] args) { Regex reg = new Regex(@"p=<(?<px>[^,]+),(?<py>[^,]+),(?<pz>[^>]+)>, v=<(?<vx>[^,]+),(?<vy>[^,]+),(?<vz>[^>]+)>, a=<(?<ax>[^,]+),(?<ay>[^,]+),(?<az>[^>]+)>"); List <Particle> particles = new List <Particle>(); foreach (string line in FileIterator.Create("./input.txt")) { Match m = reg.Match(line); Vector3 pos = new Vector3(float.Parse(m.Groups["px"].Value), float.Parse(m.Groups["py"].Value), float.Parse(m.Groups["pz"].Value)); Vector3 vel = new Vector3(float.Parse(m.Groups["vx"].Value), float.Parse(m.Groups["vy"].Value), float.Parse(m.Groups["vz"].Value)); Vector3 acc = new Vector3(float.Parse(m.Groups["ax"].Value), float.Parse(m.Groups["ay"].Value), float.Parse(m.Groups["az"].Value)); particles.Add(new Particle(pos, vel, acc)); } RemoveColisions(particles); for (int i = 0; i < 10000; i++) { particles.AsParallel().ForAll(p => p.MoveParticle()); RemoveColisions(particles); } Console.WriteLine($"particle count is {particles.Count}"); Console.ReadKey(true); }
static Fields LoadFields(string input) { Fields fields = new(); foreach (var line in FileIterator.Lines(input)) { if (line == "") { break; } var groups = line.Groups("^(.+): (.+)$"); var set = fields.GetOrCreate(groups[0], () => new()); groups = groups[1].Split(" or "); foreach (var range in groups) { var fromTo = range.Split('-'); foreach (var i in Range(int.Parse(fromTo[0]), int.Parse(fromTo[1]))) { set.Add(i); } } } return(fields); }
void Solve(string filename, string starting, string ending, ulong times) { var moves = FileIterator.LoadCSV <string>(filename); var result = starting; var cache = new Dictionary <string, CacheData>(); var foundCycle = false; for (ulong i = 0; i < times; i++) { CacheData cacheHit; if (cache.TryGetValue(result, out cacheHit) == false) { var current = result.ToCharArray(); for (var step = 0; step < moves.Length; step++) { current = NextPos(moves[step], current); } cacheHit = new CacheData(new string(current), i); cache[result] = cacheHit; } else if (!foundCycle) { cacheHit.FirstSeen.Should().Be(0); times = times % i; i = 0; foundCycle = true; } result = cacheHit.Result; } result.Should().Be(ending); }
private void WriteScheduledList(FileIterator fileIterator, ICollection <PeptideSchedule> listSchedules) { if (listSchedules.Count == 0) { return; } fileIterator.NextFile(); foreach (var schedule in PeptideSchedule.GetPrecursorSchedules(listSchedules)) { var nodePepGroup = schedule.PeptideGroup; var nodePep = schedule.Peptide; var nodeGroup = schedule.TransitionGroup; var nodeGroupPrimary = schedule.TransitionGroupPrimary; // Write required peptides at the end, like unscheduled methods if (RequiredPeptides.IsRequired(nodePep)) { continue; } // Skip percursors with too few transitions. int groupTransitions = nodeGroup.Children.Count; if (groupTransitions < MinTransitions) { continue; } WriteTransitions(fileIterator, nodePepGroup, nodePep, nodeGroup, nodeGroupPrimary); } fileIterator.WriteRequiredTransitions(this, RequiredPeptides); }
public void Part2(string input, int answer) { var lines = FileIterator.LoadLines <string>(input); var tree = BuildTree(lines); FindFixedWeight(tree).Should().Be(answer); }
private void WriteTransitions(FileIterator fileIterator, PeptideGroupDocNode nodePepGroup, PeptideDocNode nodePep, TransitionGroupDocNode nodeGroup, TransitionGroupDocNode nodeGroupPrimary) { // Allow derived classes a chance to reorder the transitions. Currently only used by AB SCIEX. var reorderedTransitions = GetTransitionsInBestOrder(nodeGroup, nodeGroupPrimary); foreach (TransitionDocNode nodeTran in reorderedTransitions) { if (OptimizeType == null) { fileIterator.WriteTransition(this, nodePepGroup, nodePep, nodeGroup, nodeGroupPrimary, nodeTran, 0); } else if (!SkipTransition(nodePepGroup, nodePep, nodeGroup, nodeGroupPrimary, nodeTran)) { // -step through step bool transitionWritten = false; for (int i = -OptimizeStepCount; i <= OptimizeStepCount; i++) { // But avoid writing zero or negative CE values, which will just mess up actuisition // Always write the highest CE if no other transition has been written, even if it is // negative, since not doing so makes it a lot harder to understand why a particular // transition did not get written at all. if (Equals(OptimizeType, ExportOptimize.CE) && GetCollisionEnergy(nodePep, nodeGroup, nodeTran, i) <= 0) { if (transitionWritten || i < OptimizeStepCount) { continue; } } fileIterator.WriteTransition(this, nodePepGroup, nodePep, nodeGroup, nodeGroupPrimary, nodeTran, i); transitionWritten = true; } } } }
static List <Passport> LoadPassports(string input) { var passports = new List <Passport>(); var currentPassport = new Passport(); passports.Add(currentPassport); FileIterator.ForEachLine(input, (string details) => { if (details == "") { currentPassport = new(); passports.Add(currentPassport); return; } var fields = details.Split(' '); foreach (var field in fields) { StoreField(currentPassport, field); } }); return(passports); }
static void Main(string[] args) { Emulator em0 = new Emulator(0); Emulator em1 = new Emulator(1); em1.ReceiveQueue = em0.SendQueue; em0.ReceiveQueue = em1.SendQueue; foreach (string line in FileIterator.Create("./input.txt")) { em0.LoadInstruction(line); em1.LoadInstruction(line); } Task tsk0 = Task.Run(async() => { while (!em0.Terminated) { await em0.NextInst().ConfigureAwait(false); } }); Task tsk1 = Task.Run(async() => { while (!em1.Terminated) { await em1.NextInst().ConfigureAwait(false); } }); Task.WhenAll(tsk0, tsk1).GetAwaiter().GetResult(); Console.WriteLine($"Recovered value is {em1.SendCount}"); Console.ReadKey(true); }
public void Part1_Example() { var lines = FileIterator.LoadLines <string>("Data/Day17_Test.txt"); var grid = Grid(lines); Alignment(grid).Should().Be(76); }
static long CountRoutes(string input) { var adapters = FileIterator.Lines <int>(input); var pathTotals = new long[adapters.Max() + 1]; // All path start at 0 which has an implicit single path. pathTotals[0] = 1; // Loop through the adapters in order, cascading up the total number of paths to reach each adapter. // An adapter's total path value is the sum of the path values of all the adapters that link to the current adapter. // We traverse the adapters in order and then back track to find the incoming totals. foreach (var adapter in adapters.OrderBy((v) => v)) { var total = 0L; for (var i = 1; i < 4; i++) { if (adapter - i < 0) { break; } // As we're not using a sparse array and the array is zero-initialised, it's safe to sum up all three previous elements. // Because we traverse in order, we are guaranteed to have calculated the previous values if they have non-zero total path count. total += pathTotals[adapter - i]; } pathTotals[adapter] = total; } // The answer should have cascaded up into the last element of the graph array. return(pathTotals.Last()); }
int Solve2(string datafile) { var particles = new Dictionary <int, Particle>(); int id = 0; FileIterator.ForEachLine <string>(datafile, line => { particles[id] = ParseParticle(id, line); id++; }); for (var i = 0; i < 39; i++) { var ccache = CreateCollisionCache(); foreach (var part in particles.Values) { part.Update(); ccache.GetOrCreate(part.PositionId, CreateParticleList).Add(part.Id); } foreach (var collisions in ccache.Values) { if (collisions.Count >= 2) { foreach (var partId in collisions) { particles.Remove(partId); } } } } return(particles.Count); }
private static void LoadTree(Dictionary <string, TreeNode> nodes) { Dictionary <TreeNode, string> supports = new Dictionary <TreeNode, string>(); Regex inputRegex = new Regex(@"(?<name>[^ ]+) \((?<weight>\d+)\)(?: -> ){0,1}(?<supporting>.*)"); foreach (string line in FileIterator.Create("input.txt")) { Match m = inputRegex.Match(line); string name = m.Groups["name"].Captures[0].Value; int weight = int.Parse(m.Groups["weight"].Captures[0].Value); string supporters = m.Groups["supporting"].Captures[0].Value; TreeNode node = new TreeNode(name, weight); nodes.Add(name, node); if (!string.IsNullOrEmpty(supporters)) { supports.Add(node, supporters); } } foreach (KeyValuePair <TreeNode, string> pair in supports) { TreeNode node = pair.Key; foreach (string supported in pair.Value.Split(',', StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim())) { TreeNode other = nodes[supported]; other.Parents.Add(node); node.Children.Add(other); } } }
Dictionary <int, List <Connector> > LoadConnectors(string datafile) { var id = 0; var connectors = new Dictionary <int, List <Connector> >(); FileIterator.ForEachLine(datafile, (string line) => { var sockets = line.Split('/'); var input = int.Parse(sockets[0]); var output = int.Parse(sockets[1]); id++; var connector = new Connector(id, input, output); var outputs = connectors.GetOrCreate(input, () => new List <Connector>()); outputs.Add(connector); if (connector.Input != connector.Output) { connector = new Connector(id, output, input); outputs = connectors.GetOrCreate(output, () => new List <Connector>()); outputs.Add(connector); } }); return(connectors); }
public void Part2(string input, int answer) { long max = 0; var prog = FileIterator.LoadCSV <int>(input); foreach (var perm in Permutations(5, 6, 7, 8, 9)) { var vms = new List <Executor <IntCode.VmState, int, (long, long, long)> >(); foreach (var p in perm) { var vm = IntCode.CreateVM(prog); vm.State.InputQueue.Enqueue(p); vms.Add(vm); } long output = 0; foreach (var vm in vms.Cycle()) { vm.State.InputQueue.Enqueue(output); if (!vm.ExecuteUntilOutput(ref output)) { if (max < output) { max = output; } break; } } } max.Should().Be(answer); }
static bool[,] LoadPaper(string filename) { var width = 0; var height = 0; var reader = FileIterator.CreateLineReader(filename); for (var line = reader(); line != ""; line = reader()) { var parts = line.Split(","); var x = int.Parse(parts[0]); var y = int.Parse(parts[1]); if (width < x) { width = x; } if (height < y) { height = y; } } var paper = new bool[width + 1, height + 1]; reader = FileIterator.CreateLineReader(filename); for (var line = reader(); line != ""; line = reader()) { var parts = line.Split(","); var x = int.Parse(parts[0]); var y = int.Parse(parts[1]); paper[x, y] = true; } return(paper); }
static void Main(string[] args) { List <int> jumps = new List <int>(); foreach (string line in FileIterator.Create("./input.txt")) { jumps.Add(int.Parse(line)); } int index = 0; int count = 0; while (index >= 0 && index < jumps.Count) { int inst = jumps[index]; if (inst >= 3) { jumps[index] = jumps[index] - 1; } else { jumps[index] = jumps[index] + 1; } index += inst; count++; } Console.WriteLine($"Escaping took {count} jumps"); Console.ReadKey(true); }
/// <summary> /// Export to a transition list to a file or to memory. /// </summary> /// <param name="fileName">A file on disk to export to, or null to export to memory.</param> public void Export(string fileName) { bool single = (Strategy == ExportStrategy.Single); RequiredPeptides = GetRequiredPeptides(single); if (MaxTransitions.HasValue && RequiredPeptides.TransitionCount > MaxTransitions) { throw new IOException(string.Format(Resources.AbstractMassListExporter_Export_The_number_of_required_transitions__0__exceeds_the_maximum__1__, RequiredPeptides.TransitionCount, MaxTransitions)); } using (var fileIterator = new FileIterator(fileName, single, IsPrecursorLimited, WriteHeaders)) { MemoryOutput = fileIterator.MemoryOutput; fileIterator.Init(); if (MethodType != ExportMethodType.Standard && Strategy == ExportStrategy.Buckets) { ExportScheduledBuckets(fileIterator); } else { ExportNormal(fileIterator, single); } fileIterator.Commit(); } }
Dictionary <ulong, NodeState> LoadGrid(string datafile, out int startX, out int startY) { var grid = new Dictionary <ulong, NodeState>(); var x = 0; var y = 0; FileIterator.ForEachLine <string>(datafile, line => { x = 0; foreach (var c in line) { if (c == '#') { grid[EncodeCoords(x, y)] = NodeState.Infected; } x++; } y++; }); startX = x / 2; startY = y / 2; return(grid); }
private void ToolStripButtonGoClick(object sender, EventArgs e) { IsRunning = true; string path = FolderTree.SelectedPath; Language language = ByLanguageFactory.GetLanguageFromString(toolStripComboBoxLanguage.Text); FileIterator fileIterator = ByLanguageFactory.GetFileIterator(language); IBlacklist blacklist = ByLanguageFactory.GetBlacklist(language); IWordStemmer stemmer = ByLanguageFactory.GetStemmer(language); SetCaptionText("Estimating ..."); string[] files = fileIterator .GetFiles(path) .ToArray(); ToolStripProgressBar.Maximum = files.Length; m_CloudControl.WeightedWords = new List <IWord>(); //Note do not dispose m_CancelSource it will be disposed by task //TODO need to find correct way to work with CancelationToken //http://stackoverflow.com/questions/6960520/when-to-dispose-cancellationtokensource m_CancelSource = new CancellationTokenSource(); Task.Factory .StartNew( () => GetWordsParallely(files, language, blacklist, stemmer), m_CancelSource.Token) .ContinueWith( ApplyResults); }