Esempio n. 1
0
    public Dictionary <TCell, int> Compute(TCell start)
    {
        var dist = new DefaultDict <TCell, int> {
            DefaultValue = int.MaxValue, [start] = 0
        };
        var seen  = new HashSet <TCell>();
        var queue = new PriorityQueue <TCell, int>();

        queue.Enqueue(start, 0);
        while (queue.Count > 0)
        {
            var cell = queue.Dequeue();
            if (seen.Contains(cell))
            {
                continue;
            }
            seen.Add(cell);
            var current = dist[cell];
            foreach (var neighbor in Neighbors(cell))
            {
                var other  = Cell(cell, neighbor);
                var weight = Distance(neighbor);
                if (!seen.Contains(other))
                {
                    queue.Enqueue(other, current + weight);
                }
                if (current + weight < dist[other])
                {
                    dist[other] = current + weight;
                }
            }
        }
        return(dist);
    }
Esempio n. 2
0
    public Dictionary <T, long> Produce(T item, long quantity, out DefaultDict <T, long> extra)
    {
        extra = new DefaultDict <T, long>();
        var count = new DefaultDict <T, long>();

        Produce(item, quantity, count, extra);
        return(count);
    }
Esempio n. 3
0
    // The update function for AI logic.
    public void think()
    {
        if (!Player.humanHasMoved)
        {
            return;
        }
        updateHeatmap();

        DefaultDict <UnitType, int> currentUnitCounts = new DefaultDict <UnitType, int>(0);

        foreach (Unit unit in aiPlayer.units)
        {
            currentUnitCounts[unit.type] += 1;
        }
        aiPlayer.tradeWithNClosest(Mathf.Min(8, 1 + currentUnitCounts[UnitType.MERCHANT]));
        bool isMaxBuild = true;

        foreach (UnitType desiredUnitType in AI_BUILD_ORDER)
        {
            currentUnitCounts[desiredUnitType] -= 1;
            if (currentUnitCounts[desiredUnitType] < 0)
            {
                isMaxBuild = false;
                if (aiPlayer.has(UnitData.getCost(desiredUnitType)))
                {
                    aiPlayer.getBase().trainUnit((int)desiredUnitType);
                }
                else
                {
                    break;
                }
            }
        }
        // Spend excess money on galleys
        if (isMaxBuild && aiPlayer.has(UnitData.getCost(UnitType.GALLEY)))
        {
            aiPlayer.getBase().trainUnit((int)UnitType.GALLEY);
        }

        /* Warship AI:
         * Compute influence heatmap. Move towards threatening enemy warships or weak enemies.
         */
        List <Unit> weakEnemies = findWeakEnemies();

        // TODO: score weak enemies and other objectives based on distance, influence, etc.
        if (weakEnemies.Count > 0)
        {
            foreach (Unit u in aiPlayer.units)
            {
                if (u.capableOfAttack())
                {
                    u.moveTo(weakEnemies[0].getPosition(), u.attackRange);
                }
            }
        }
    }
        public static DefaultDict <TKey, TValue> ToDefaultDict <TKey, TValue> (this IDictionary <TKey, TValue> collection) where TValue : new()
        {
            var d = new DefaultDict <TKey, TValue>();

            foreach (var item in collection)
            {
                d.Add(item.Key, item.Value);
            }
            return(d);
        }
Esempio n. 5
0
        public SumoSender(string host, int port)
        {
            this.Host    = host;
            this.Port    = port;
            this.seq_ids = new DefaultDict <int, int>();
            SumoRemote   = new IPEndPoint(IPAddress.Parse(host), port);
            sumoSocket   = new UdpClient();

            // Initial command (no motion)
            this.cmd = SumoCommandsCustom._pack_frame(SumoCommandsCustom.Move_cmd(0, 0));
        }
Esempio n. 6
0
    public override void PartOne()
    {
        var reg = new DefaultDict <string, int>();

        foreach (var(r, sign, offset, cmp, op, value) in GetInput())
        {
            if (op.Operation(reg[cmp], value))
            {
                reg[r] += sign.Inc ? offset : -offset;
            }
        }
        WriteLn(reg.Values.Max());
    }
Esempio n. 7
0
        /// <summary>
        ///   Construct a basic server such that it is ready to be started, and possibly using the default connect
        ///   behavior.
        /// </summary>
        public BasicServer(IPAddress localaddr, int port, string logFileName = null, bool tailLog = true)
        {
            IsRunning = false;
            _localaddr = localaddr;
            _port = port;

            ClientTable = new BidirectionalDict<string, Client>();
            AuthTable = new DefaultDict<Client, bool>();

            Log = new FileLog(logFileName, Frequency.Burst);
            if (tailLog)
                Log.AddMirror(new ConsoleLog());
            Log.Info("Server initialized: <{0}>::{1}".format(localaddr, port));
        }
Esempio n. 8
0
    private void Produce(T item, long quantity, DefaultDict <T, long> count, DefaultDict <T, long> extra)
    {
        if (!TryGet(item, out var vertex))
        {
            throw new Exception("Cannot produce needed item.");
        }
        long willProduce;
        var  scale = 1L;

        if (vertex.Quantity == 0 && vertex.Count != 0)
        {
            throw new Exception("Only 0 of the item can be made.");
        }
        if (vertex.Quantity == 0)
        {
            willProduce = quantity;
        }
        else
        {
            willProduce = quantity % vertex.Quantity == 0 ? quantity : quantity + (vertex.Quantity - (quantity % vertex.Quantity));
            scale       = willProduce / vertex.Quantity;
        }
        foreach (var(child, amount) in vertex.Produced())
        {
            var want  = amount * scale;
            var piece = child.Value;
            extra.TryGetValue(piece, out var have);
            if (have > want)
            {
                count[piece] += want;
                extra[piece] -= want;
            }
            else if (have == want)
            {
                count[piece] += want;
                extra.Remove(piece);
            }
            else
            {
                count[piece] += have;
                extra.Remove(piece);
                Produce(piece, want - have, count, extra);
            }
        }
        count[item] += quantity;
        if (willProduce > quantity)
        {
            extra[item] += willProduce - quantity;
        }
    }
Esempio n. 9
0
    public override void PartTwo()
    {
        var reg = new DefaultDict <string, int>();
        var max = 0;

        foreach (var(r, sign, offset, cmp, op, value) in GetInput())
        {
            if (op.Operation(reg[cmp], value))
            {
                reg[r] += sign.Inc ? offset : -offset;
                max     = Math.Max(max, reg[r]);
            }
        }
        WriteLn(max);
    }
Esempio n. 10
0
        /// <summary>
        /// Find the node with the lowest F score.
        /// </summary>
        private static Node FindLowestFScore(HashSet <Node> openSet, Node current, DefaultDict fScore)
        {
            var  lowest       = float.MaxValue;
            Node selectedNode = current;

            foreach (var node in openSet)
            {
                if (fScore.Get(node) < lowest)
                {
                    selectedNode = node;
                    lowest       = fScore.Get(node);
                }
            }

            return(selectedNode);
        }
Esempio n. 11
0
    public long ProduceFrom(T item, Dictionary <T, long> have)
    {
        var  made  = new DefaultDict <T, long>();
        var  extra = new DefaultDict <T, long>(have);
        long count = 0;

        while (true)
        {
            Produce(item, 1, made, extra);
            if (have.Any(pair => made[pair.Key] > pair.Value))
            {
                break;
            }
            count++;
        }
        return(count);
    }
Esempio n. 12
0
        public override string Part1()
        {
            var eris = new Eris(ReadAllText(), false, 0);
            var set  = new DefaultDict <int, int>();

            while (true)
            {
                var r = eris.Rating();
                set[r]++;

                if (set[r] > 1)
                {
                    return(r.ToString());
                }
                eris.Tick();
                eris.Swap();
            }
        }
Esempio n. 13
0
    public BigInteger Compute(int times)
    {
        var counts = AllGroups[0][0].Window(2).StrEach().Frequencies().SelectValue(i => (BigInteger)i).ToDictionary();
        var map    = AllGroups[1].ReadKeys("->");

        for (var i = 0; i < times; i++)
        {
            var next = new DefaultDict <string, BigInteger>();
            foreach (var(pair, count) in counts)
            {
                var add = map[pair];
                next[pair[0] + add] += count;
                next[add + pair[1]] += count;
            }
            counts = next;
        }

        var freq = new DefaultDict <char, BigInteger>();

        freq[AllGroups[0][0][^ 1]]++; // Account for possible off-by-one
Esempio n. 14
0
        public PresetTextLesson(string text, int maxLength = 0)
        {
            if (maxLength == 0)
            {
                maxLength = defaultLessonLength;
            }
            text = text.Trim();

            alphabet = text.ToUpper().ToHashSet();
            characterFrequencyCount = new DefaultDict <char, int>();
            foreach (char c in text.ToUpper())
            {
                characterFrequencyCount[c] += 1;
            }


            queuedTexts = new List <string>();

            //TODO:
            //Divide up the text into about to equal chunks, each of which is smaller than maxLength
            int start     = 0;
            int remaining = text.Length;

            do
            {
                double chunks       = Math.Ceiling((double)remaining / maxLength);
                int    targetLength = (int)Math.Ceiling(remaining / chunks);

                int chunklength = text.Substring(start, targetLength).LastIndexOf(" ");
                if (chunklength == -1) //word is too long; chop it up
                {
                    chunklength = start + maxLength;
                }
                // .Substring complains about going over the length
                queuedTexts.Add(text.Substring(start, Math.Min(chunklength, remaining)));
                start    += chunklength + 1;
                remaining = text.Length - start;
            } while (remaining > 0);
        }
Esempio n. 15
0
        long OreRequired(string what, long count, DefaultDict <string, long> stock)
        {
            if (what == "ORE")
            {
                return(count);
            }

            if (stock[what] > 0)
            {
                var howMuchWeCanUse = Math.Min(count, stock[what]);
                stock[what] -= howMuchWeCanUse;
                count       -= howMuchWeCanUse;
            }

            if (count == 0)
            {
                return(0);
            }

            var item  = ReadInput().Single(x => x.Output.Name == what);
            var react = 1L;

            if (count > item.Output.Count)
            {
                react = (long)Math.Ceiling((double)count / item.Output.Count);
            }
            stock[what] += react * item.Output.Count - count;

            var ore = 0L;

            foreach (var n in item.Input)
            {
                ore += OreRequired(n.Name, react * n.Count, stock);
            }

            return(ore);
        }
Esempio n. 16
0
        /// <param name="dictonary">List of words the generator can use</param>
        /// <param name="maxLength">Exclusive maximum length of each generated text chunk</param>
        public RandomizedLesson(IEnumerable <string> dictonary, int maxLength = 0)
        {
            if (maxLength == 0)
            {
                maxLength = defaultLessonLength;
            }

            dict        = Sanitize(dictonary);
            chunkLength = maxLength;
            random      = NextRandom();
            place       = 0;
            shuffled    = dict.OrderBy(x => random.Next()).ToList();

            //all characters which appear at least 50 times in the dictionary
            alphabet = dict.SelectMany(x => x.ToUpper()).GroupBy(x => x).Where(x => x.Count() > 50).SelectMany(x => x).ToHashSet();

            characterFrequencyCount = new DefaultDict <char, int>();
            foreach (char c in dictonary.SelectMany(w => w.ToUpper().ToCharArray()))
            {
                characterFrequencyCount[c] += 1;
            }

            NextText();
        }
Esempio n. 17
0
        public SeriesData GenerateSeries(IList<ProcessedInfo> infos)
        {
            bool isTrackingExes = Settings.Options.TrackExes;
            infos = infos.OrderBy(i => i.Time).ToList();
            double minTime = infos[0].Time;
            double totalTime = infos[infos.Count - 1].Time - infos[0].Time;
            if (totalTime < 0)
            {
                throw new Exception("backwards sort");
            }
            var allNames = new HashSet<string>();
            var all = new List<IDictionary<string, double>>();

            var next = new DefaultDict<string, double>();
            double time = minTime;
            double timeSpan;// =  totalTime / partitions;
            timeSpan = 60 * 14.4; //one percent hour
            if (timeSpan > updateFrequency)
            {
                timeSpan = updateFrequency;
            }

            foreach (var info in infos)
            {
                if (info.Program.Categories.Count != 0)
                {
                    allNames.Add(info.Program.Categories[categoryIndex]);
                }
            }

            double lastTime = time;
            double lastActiveTime = -1;

            foreach (var info in infos)
            {
                if (info.DidActivity || lastActiveTime < 0)
                {
                    lastActiveTime = lastTime;
                }

                string key;
                if (info.Time - lastActiveTime > Settings.Options.IdleTime)
                {
                    var program = ProgramInfo.Idle;
                    allNames.Add(program.Name);
                    key = program.Name;
                }
                else
                {
                    try
                    {
                        key = info.Program.Categories[categoryIndex];
                    }
                    catch
                    {
                        key = "Neutral";
                    }
                }

                next[key] += info.Time - lastTime;

                lastTime = info.Time;
                if (info.Time - time > timeSpan)
                {
                    time = info.Time;
                    all.Add(next);
                    next = new DefaultDict<string, double>();
                }
            }

            return new SeriesData(all.Select(normalize).ToList(), allNames, timeSpan);
        }
Esempio n. 18
0
        void Network()
        {
            var tasks = new List <Task>();

            using var abort = new ManualResetEvent(false);

            var lan  = new IntCodeComputer[N];
            var hub  = new ConcurrentDictionary <long, List <Packet> >();
            var buf  = new ConcurrentDictionary <long, List <long> >();
            var init = new bool[N];

            for (int i = 0; i < N; i++)
            {
                var ip = i;
                var c  = new IntCodeComputer(ReadAllText().ToIntCode());

                c.SignalOutput += _output =>
                {
                    if (abort.WaitOne(10))
                    {
                        c.Terminate();
                    }

                    buf[ip].Add(_output);
                    if (buf[ip].Count == 3)
                    {
                        var packet = new Packet()
                        {
                            IP    = buf[ip][0],
                            X     = buf[ip][1],
                            Y     = buf[ip][2],
                            SentX = false
                        };

                        if (packet.IP == 255 && _part1 == 0)
                        {
                            _part1 = packet.Y;
                        }

                        lock (this)
                        {
                            hub[packet.IP].Add(packet);
                        }
                        buf[ip].Clear();
                    }
                };
                c.ProvideInput += () =>
                {
                    if (abort.WaitOne(10))
                    {
                        c.Terminate();
                    }

                    if (init[ip])
                    {
                        if (hub[ip].Any())
                        {
                            Packet p;
                            lock (this)
                            {
                                p = hub[ip][0];
                                if (p.SentX)
                                {
                                    hub[ip].RemoveAt(0);
                                }
                            }
                            if (p.SentX)
                            {
                                return(p.Y);
                            }
                            else
                            {
                                p.SentX = true;

                                return(p.X);
                            }
                        }
                        return(-1);
                    }
                    else
                    {
                        init[ip] = true;

                        return(ip);
                    }
                };

                lan[i]   = c;
                buf[i]   = new List <long>();
                hub[i]   = new List <Packet>();
                hub[255] = new List <Packet>();

                tasks.Add(new Task(c.Run));
            }
            tasks.Add(new Task(NAT));

            tasks.ForEach(x => x.Start());
            Task.WhenAll(tasks).ConfigureAwait(false).GetAwaiter().GetResult();

            void NAT()
            {
                while (!init.All(x => x))
                {
                    Thread.Sleep(100);
                }
                var sent = new DefaultDict <long, int>();

                while (true)
                {
                    Thread.Sleep(100);
                    List <(long Key, int Count)> queues;

                    lock (this)
                    {
                        queues = hub.Where(kv => kv.Key != 255).Select(kv => (kv.Key, kv.Value.Count)).ToList();
                    }

                    if (queues.All(item => item.Count == 0) && hub[255].Any())
                    {
                        Packet last;
                        lock (this)
                        {
                            last = hub[255].Last();
                            hub[255].Clear();
                        }
                        sent[last.Y]++;

                        if (sent[last.Y] == 2)
                        {
                            _part2 = last.Y;
                            abort.Set();

                            return;
                        }

                        lock (this)
                        {
                            hub[0].Add(last);
                        }
                    }
                }
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Find the path from start to goal using the A* algorithm. Based on the Wikipedia pseudo code example:
        /// https://en.wikipedia.org/wiki/A*_search_algorithm#Pseudocode
        /// </summary>
        /// <returns><c>true</c>, if path was found, <c>false</c> otherwise.</returns>
        public static bool FindPath(Node start, Node goal)
        {
            var closedSet = new HashSet <Node> ();

            var openSet = new HashSet <Node> ();

            openSet.Add(start);

            var gScore = new DefaultDict();

            gScore.Set(start, 0);

            var fScore = new DefaultDict();

            fScore.Set(start, HeuristicEstimate(start, goal));

            var cameFrom = new Dictionary <Node, Node> ();

            Node current = start;

            while (openSet.Count > 0)
            {
                current = FindLowestFScore(openSet, current, fScore);
                if (current.Type != Node.NodeType.Start && current.Type != Node.NodeType.Goal)
                {
                    current.Type = Node.NodeType.Explored;
                }
                if (current == goal)
                {
                    ReconstructPath(cameFrom, current);
                    return(true);
                }
                openSet.Remove(current);
                closedSet.Add(current);

                foreach (var neighbor in current.Connections.Keys)
                {
                    if (closedSet.Contains(neighbor))
                    {
                        continue;
                    }

                    if (!openSet.Contains(neighbor))
                    {
                        openSet.Add(neighbor);
                    }

                    var tentativeGScore = gScore.Get(current) + current.Connections [neighbor];
                    if (tentativeGScore >= gScore.Get(neighbor))
                    {
                        continue;
                    }

                    cameFrom [neighbor] = current;
                    gScore.Set(neighbor, tentativeGScore);
                    fScore.Set(neighbor, gScore.Get(neighbor) + HeuristicEstimate(neighbor, goal));
                }
            }

            return(false);
        }
Esempio n. 20
0
 private static IDictionary<string, double> normalize(IDictionary<string, double> map)
 {
     var result = new DefaultDict<string, double>();
     var total = map.Values.Sum();
     foreach(var pair in map)
     {
         result[pair.Key] = pair.Value/total;
     }
     return result;
 }