Пример #1
0
        public void Test_PermutateV4_GenerateIndices()
        {
            var input = new List <List <Slot> >
            {
                new List <Slot> {
                    new Slot()
                },
                new List <Slot> {
                    new Slot(), new Slot()
                },
                new List <Slot> {
                    new Slot(), new Slot(), new Slot()
                }
            };

            var actual   = Permutator.GenerateIndices(input);
            var expected = new List <BoundedInt>
            {
                new BoundedInt(0, 0),
                new BoundedInt(1, 0),
                new BoundedInt(2, 0)
            };

            for (var i = 0; i < 3; i++)
            {
                if (!actual[i].Equals(expected[i]))
                {
                    Assert.Fail();
                }
            }
            Assert.Pass();
        }
Пример #2
0
        public void Test_PermutateV4_Increment_4()
        {
            var input = new List <BoundedInt>
            {
                new BoundedInt(1, 0),
                new BoundedInt(0, 0),
                new BoundedInt(0, 0)
            };

            var expected = new List <BoundedInt>
            {
                new BoundedInt(1, 1),
                new BoundedInt(0, 0),
                new BoundedInt(0, 0)
            };
            var actual = Permutator.Increment(input);

            for (var i = 0; i < 3; i++)
            {
                if (!actual[i].Equals(expected[i]))
                {
                    Assert.Fail();
                }
            }
            // TODO: Add your test code here
            Assert.Pass("Your first passing test");
        }
        public void GenerateTimetables(SlotList slotList)
        {
            var result = Permutator.Run_v2_WithConsideringWeekNumber(slotList.ToArray());

            _timetableList = new TimetableList(result);
            NotifyObserver();
        }
Пример #4
0
        static void Main()
        {
            BigInteger      answer = 0;
            int             search = 10;
            BigInteger      max    = 0;
            EAsContFraction e;

            for (int a = 1; a < search; ++a)
            {
                e = new EAsContFraction(a);
                e.print();
                Console.WriteLine();

                Pair p;
                p = e.toRational();
                Console.WriteLine(p.a + "/" + p.b);
                Console.WriteLine(Permutator.sumOfDigits(p.a));
            }

            e = new EAsContFraction(99);
            Pair p2 = e.toRational();

            answer = Permutator.sumOfDigits(p2.a);

            Console.WriteLine("Answer: " + answer);

            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Пример #5
0
        public void Test_StateTable_GetStateOfDefinitelyOccupied_2()
        {
            var input = Permutator.Run_v2_withoutConsideringWeekNumber(TestData
                                                                       .GetSlotsByName(TestData.Subjects.HighwayAndTransportation).ToArray());
            var expected = StateTable.ParseString_AsStateOfDefinitelyOccupied(
                "00000000000000000000001100000000~" +
                "00000000000000000000000000000000~" +
                "00000011110000000000000000000000~" +
                "00000000000000000000000000000000~" +
                "00000000000000000000000000000000~" +
                "00000000000000000000000000000000~" +
                "00000000000000000000000000000000"
                );
            var actual = StateTable.GetStateOfDefinitelyOccupied(input);

            for (int i = 0; i < 7; i++)
            {
                if (expected[i] != actual[i])
                {
                    string errorMessage = "Error at day = " + i + "\n";
                    errorMessage += "Expected = " + Convert.ToString(expected[i], 2) + "\n";
                    errorMessage += "Actual   = " + Convert.ToString(actual[i], 2);
                    Assert.Fail(errorMessage);
                }
            }
            Assert.Pass();
        }
Пример #6
0
        public void Permutator_CanPermutate()
        {
            Permutator idx = new Permutator(10);

            for (int i = 0; i < 10; i++)
                Console.WriteLine("{0}", idx[i]);
        }
        public NetworkTrainer(BackPropagationNetwork BPN, DataSet DS)
        {
            Network     = BPN; DataSet = DS;
            _idx        = new Permutator(DataSet.Size);
            _iterations = 0;

            _errorHistory = new List <double>();
        }
Пример #8
0
        static void Main()
        {
            // We're going to create a permutation dictionary of all
            // cubic values up to a certain point. The purpose here is to
            // be able to attach a list of all discovered cubic permutations
            // to any particular cubic value that when sorted acts as a key
            // to this dictionary
            BigInteger answer = 0;
            Dictionary <BigInteger, List <BigInteger> > cubicDict = new Dictionary <BigInteger, List <BigInteger> >();
            int search = 100000;

            for (int i = 0; i < search; ++i)
            {
                // get the cube of the index, convert it to a string,
                // sort it, and use the sorted permutation of it's digits
                BigInteger        it     = BigInteger.Pow(i, 3);
                List <BigInteger> digits = Permutator.getDigits(it);
                digits.Sort();
                BigInteger sorted = 0;
                for (int j = 0; j < digits.Count; ++j)
                {
                    sorted += BigInteger.Pow(10, j) * digits[j];
                }
                List <BigInteger> knownPerms;

                // we want to enforce the rule that associated permutations
                // have the same number of digits
                List <BigInteger> sortedDigits = Permutator.getDigits(sorted);
                if (sortedDigits.Count == digits.Count)
                {
                    if (cubicDict.TryGetValue(sorted, out knownPerms))
                    {
                        knownPerms.Add(it);
                        if (knownPerms.Count == 5)
                        {
                            foreach (BigInteger x in knownPerms)
                            {
                                Console.WriteLine(x);
                            }
                            answer = i;
                            break;
                        }
                    }
                    else
                    {
                        knownPerms = new List <BigInteger>();
                        knownPerms.Add(it);
                        cubicDict.Add(sorted, knownPerms);
                    }
                }
            }
            Console.WriteLine("Answer: " + answer);

            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Пример #9
0
        public void CheckingPermutation()
        {
            var list = new List <int>()
            {
                1, 2, 3, 4, 5
            };
            var result = Permutator.Permute(list);

            Assert.True(result.Count == 120);
        }
Пример #10
0
        public void Test_PermutateV4_Increment_5()
        {
            var input = new List <BoundedInt>
            {
                new BoundedInt(1, 1)
            };

            var actual = Permutator.Increment(input);

            Assert.True(actual == null);
        }
 private static IEnumerable <IEnumerable <int> > CreateIndices(int length)
 {
     return((from p in Enumerable.Range(0, length)
             select(
                 from s in Permutator.CreateIndices(length - 1)
                 .DefaultIfEmpty(Enumerable.Empty <int>())
                 select s.Take(p)
                 .Concat(new[] { length - 1 })
                 .Concat(s.Skip(p))
                 ))
            .SelectMany(i => i));
 }
Пример #12
0
        public void Test_ClashFinder_GetTimetableState_1()
        {
            var chosenSubject = TestData.Subjects.HubunganEtnik;
            var input         =
                Permutator.Run_v2_WithConsideringWeekNumber(TestData.GetSlotsByName(chosenSubject)
                                                            .ToArray());
            var result = ClashFinder.GetSubjectState(input);

            foreach (int dayState in result)
            {
                Assert.IsTrue(dayState == 0);
            }
        }
Пример #13
0
        static int nextDigitFactorial(int x)
        {
            int             ret       = 0;
            List <int>      digits    = Permutator.getDigits(x);
            Func <int, int> factorial = null;

            factorial = y => y <= 1 ? 1 : y *factorial(y - 1);

            foreach (int a in digits)
            {
                ret += factorial(a);
            }
            return(ret);
        }
Пример #14
0
        public void CanPermute()
        {
            string str    = "ABC";
            int    n      = str.Length;
            var    result = Permutator.Permute(str);

            Assert.Equal(result, new[] {
                "ABC",
                "ACB",
                "BAC",
                "BCA",
                "CBA",
                "CAB"
            });
        }
Пример #15
0
        public void SandboxTest_3()
        {
            var input  = TestData.GetSlotsByName(TestData.Subjects.Hydrology);
            var input2 = TestData.GetSlotsByName(TestData.Subjects.FluidMechanicsII);
            var input3 = TestData.GetSlotsByName(TestData.Subjects.StructuralAnalysisII);
            var input4 = TestData.GetSlotsByName(TestData.Subjects.HighwayAndTransportation);
            var input5 = TestData.GetSlotsByName(TestData.Subjects.IntroductionToBuildingServices);

            int result1 = Permutator.Run_v2_WithConsideringWeekNumber(input.ToArray()).Count;
            int result2 = Permutator.Run_v2_WithConsideringWeekNumber(input2.ToArray()).Count;
            int result3 = Permutator.Run_v2_WithConsideringWeekNumber(input3.ToArray()).Count;
            int result4 = Permutator.Run_v2_WithConsideringWeekNumber(input4.ToArray()).Count;
            int result5 = Permutator.Run_v2_WithConsideringWeekNumber(input5.ToArray()).Count;

            Console.WriteLine("Total combination is " + result1 * result2 * result3 * result4 * result5);
        }
Пример #16
0
        public void Test_StateTable_GetStateOfDefinitelyOccupied_1()
        {
            var input = Permutator.Run_v2_withoutConsideringWeekNumber(TestData
                                                                       .GetSlotsByName(TestData.Subjects.AdvancedStructuralSteelDesign).ToArray());
            var expected = StateTable.ParseString_AsStateOfDefinitelyOccupied(
                "00000000000000111100000000000000~" +
                "00110000000000000000000000000000~" +
                "00000000000000000000000000000000~" +
                "00000000000000000000000000000000~" +
                "00000000000000000000000000000000~" +
                "00000000000000000000000000000000~" +
                "00000000000000000000000000000000"
                );
            var actual = StateTable.GetStateOfDefinitelyOccupied(input);

            Assert.IsTrue(actual.SequenceEqual(expected));
        }
Пример #17
0
        public void Test_PermutateV4_Runv2_WithoutConsideringWeekNumber()
        {
            int expectedCount = 285696;
            var input         = new List <Slot>();

            input.AddRange(TestData.GetSlotsByName(TestData.Subjects.Hydrology));
            input.AddRange(TestData.GetSlotsByName(TestData.Subjects.StructuralAnalysisII));
            input.AddRange(TestData.GetSlotsByName(TestData.Subjects.HighwayAndTransportation));
            input.AddRange(TestData.GetSlotsByName(TestData.Subjects.FluidMechanicsII));
            input.AddRange(TestData.GetSlotsByName(TestData.Subjects.IntroductionToBuildingServices));
            var timer  = Stopwatch.StartNew();
            var result = Permutator.Run_v2_withoutConsideringWeekNumber(input.ToArray());

            timer.Stop();
            Console.WriteLine("Combination count : " + result.Count);
            Console.WriteLine("Elapsed time : " + timer.Elapsed.TotalSeconds + " s");
            Assert.True(result.Count == expectedCount);
        }
Пример #18
0
        public void Test_PermutateV4_Partitionize_6()
        {
            var input = new[]
            {
                new Slot {
                    Code = "abc", Type = "L", Number = "1"
                },
                new Slot {
                    Code = "abc", Type = "L", Number = "2"
                },
                new Slot {
                    Code = "abc", Type = "L", Number = "3"
                },
                new Slot {
                    Code = "abc", Type = "L", Number = "1"
                },
                new Slot {
                    Code = "abc", Type = "L", Number = "2"
                },
                new Slot {
                    Code = "abc", Type = "L", Number = "3"
                }
            };
            var actual   = Permutator.Partitionize(input);
            var expected = new List <List <Slot> >
            {
                new List <Slot> {
                    input[0], input[1], input[2]
                },
                new List <Slot> {
                    input[3], input[4], input[5]
                }
            };

            if (actual.Count != expected.Count)
            {
                Assert.Fail();
            }
            foreach (var e in expected)
            {
                actual.RemoveAll(x => x.ScrambledEquals(e));
            }
            Assert.True(actual.Count == 0);
        }
Пример #19
0
        /// <summary>
        /// Generates a random set of coefficients. The number of set coefficients is a number drawn from the Robust Soliton Distribution that was initialized in the constructor
        /// </summary>
        /// <param name="symbolId">For Luby Transform, the symbol ID has no bearing on the coefficients</param>
        /// <param name="complexity">The number of operations that had to be performed</param>
        /// <returns></returns>
        public bool[] GenerateCoefficients(long symbolId, ref int complexity)
        {
            // Set up the set of coefficients
            var coefficients = new bool[NumSymbols]; complexity += NumSymbols;
            var degree       = _pmf.Generate();       // This is the number of bits that will be set in the coefficients array. O(log(n))

            complexity += (int)Math.Ceiling(Math.Log(NumSymbols, 2.0));
            for (var i = 0; i < degree; i++)             // O(n)
            {
                complexity++;
                coefficients[i] = true;
            }
            // Mix up the coefficients array
            Permutator <bool> .Permutate(coefficients, _random);           // O(n)

            complexity += NumSymbols;

            return(coefficients);
        }
Пример #20
0
        public void Test_StateTable_1()
        {
            var stateTable = new StateTable_v1();
            var data       = new List <Slot>();

            data.AddRange(GetSlotsByName(Subjects.Hydrology));
            data.AddRange(GetSlotsByName(Subjects.IntroductionToBuildingServices));
            data.AddRange(GetSlotsByName(Subjects.HighwayAndTransportation));
            data.AddRange(GetSlotsByName(Subjects.StructuralAnalysisII));

            var result = Permutator.Run_v2_WithConsideringWeekNumber(data.ToArray())[0];

            for (int i = 0; i < result.Count; i++)
            {
                stateTable.Add(new IndexedSlot(result[i]));
            }
            Console.WriteLine(stateTable.ToString());
            Assert.Pass();
        }
Пример #21
0
        public void Test_ClashFinder_GetTimetableState_2()
        {
            var chosenSubject = TestData.Subjects.ArtCraftAndDesign;
            var input         =
                Permutator.Run_v2_WithConsideringWeekNumber(TestData.GetSlotsByName(chosenSubject)
                                                            .ToArray());
            var result = ClashFinder.GetSubjectState(input);

            for (int i = 0; i < Day.NumberOfDaysPerWeek; i++)
            {
                if (i == 0)    //Monday
                {
                    Assert.IsTrue(result[i] == Convert.ToInt32("00000000000000111100000000000000", 2));
                }
                else
                {
                    Assert.IsTrue(result[i] == 0);
                }
            }
        }
Пример #22
0
        private List <IList <ulong> > GenWeightCombos(ulong targetWeight, ulong[] nums)
        {
            List <IList <ulong> > weightCombos = new List <IList <ulong> >();

            for (int i = 2; i < input.Length; i++)
            {
                foreach (var wc in Permutator.Combinations(i, nums))
                {
                    if (Sum(wc) == targetWeight)
                    {
                        weightCombos.Add(wc);
                    }
                }
                if (weightCombos.Count != 0)
                {
                    break;
                }
            }
            return(weightCombos);
        }
Пример #23
0
        public override object Task2()
        {
            thrusters = new IntCode.Emulator[5];
            for (int i = 0; i < 5; i++)
            {
                thrusters[i] = new IntCode.Emulator(thrusterCode);
            }

            int[] phaseSettings = new int[] { 5, 6, 7, 8, 9 };
            long  maxSignal     = 0;

            foreach (int[] arr in Permutator.Permutate(phaseSettings))
            {
                long sig = RunFeedbackLoop(arr);
                if (sig > maxSignal)
                {
                    maxSignal = sig;
                }
            }
            return(maxSignal);
        }
Пример #24
0
            public int FindShortestDistance(bool includePathBack)
            {
                var pathFinder  = new PathFinder();
                var points      = FindAllPoints();
                var permutatios = Permutator.Permute(points.Keys.ToArray());

                permutatios = permutatios.Where(p => p[0] == '0');

                // Remembering all the distances speed things up a bit...
                var knownDistances = new Dictionary <string, int>();

                var shortest = int.MaxValue;

                foreach (var permutation in permutatios)
                {
                    var    sum = 0;
                    char[] currentPermutation = permutation;
                    if (includePathBack)
                    {
                        currentPermutation = permutation.Concat(new[] { '0' }).ToArray();
                    }

                    for (int i = 0; i < currentPermutation.Length - 1; i++)
                    {
                        var key = "" + currentPermutation[i] + currentPermutation[i + 1];
                        if (!knownDistances.ContainsKey(key))
                        {
                            knownDistances.Add(key, pathFinder.FindShortestPath(
                                                   points[currentPermutation[i]],
                                                   points[currentPermutation[i + 1]],
                                                   NodeTypeAtPos));
                        }
                        sum += knownDistances[key];
                    }

                    shortest = Math.Min(shortest, sum);
                }

                return(shortest);
            }
Пример #25
0
        public override object Task1()
        {
            thrusterCode = IntCode.Tools.ParseCode(input[0]);
            IntCode.Emulator ICE       = new IntCode.Emulator(thrusterCode);
            long             maxSignal = 0;

            var response = IntCode.Emulator.ResultTemplate;

            foreach (int[] arr in Permutator.Permutate(new int[] { 0, 1, 2, 3, 4 }))
            {
                response.Item2 = 0;
                foreach (int s in arr)
                {
                    ICE.Reboot();
                    ICE.QueueInput(s, response.Item2);
                    response = ICE.Run();
                }
                if (response.Item2 > maxSignal)
                {
                    maxSignal = response.Item2;
                }
            }
            return(maxSignal);
        }
Пример #26
0
        public void Test_ClashFinder_GetTimetableState_3()
        {
            var chosenSubject = TestData.Subjects.AdvancedStructuralSteelDesign;
            var input         =
                Permutator.Run_v2_WithConsideringWeekNumber(TestData.GetSlotsByName(chosenSubject)
                                                            .ToArray());
            var result = ClashFinder.GetSubjectState(input);

            for (int i = 0; i < Day.NumberOfDaysPerWeek; i++)
            {
                if (i == 0)   //Monday
                {
                    Assert.IsTrue(result[i] == Convert.ToInt32("00000000000000111100000000000000", 2));
                }
                else if (i == 1)   //Tuesday
                {
                    Assert.AreEqual(Convert.ToInt32("00110000000000000000000000000000".Reverse(), 2), result[i]);
                }
                else   //others
                {
                    Assert.IsTrue(result[i] == 0);
                }
            }
        }
Пример #27
0
        /// <summary>
        ///     Produces a hash for the paths of adjacent bnodes for a bnode,
        ///     incorporating all information about its subgraph of bnodes.
        /// </summary>
        /// <remarks>
        ///     Produces a hash for the paths of adjacent bnodes for a bnode,
        ///     incorporating all information about its subgraph of bnodes. This method
        ///     will recursively pick adjacent bnode permutations that produce the
        ///     lexicographically-least 'path' serializations.
        /// </remarks>
        /// <param name="id">the ID of the bnode to hash paths for.</param>
        /// <param name="bnodes">the map of bnode quads.</param>
        /// <param name="namer">the canonical bnode namer.</param>
        /// <param name="pathNamer">the namer used to assign names to adjacent bnodes.</param>
        /// <param name="callback">(err, result) called once the operation completes.</param>
        private static HashResult HashPaths(string id,
                                            IDictionary <string, IDictionary <string, object> > bnodes,
                                            UniqueNamer namer,
                                            UniqueNamer pathNamer)
        {
#if !PORTABLE
            MessageDigest md = null;

            try
            {
                // create SHA-1 digest
                md = MessageDigest.GetInstance("SHA-1");
                var            groups = new JObject();
                IList <string> groupHashes;
                var            quads = (IList <RdfDataset.Quad>)bnodes[id]["quads"];
                for (var hpi = 0;; hpi++)
                {
                    if (hpi == quads.Count)
                    {
                        // done , hash groups
                        groupHashes = new List <string>(groups.GetKeys());
                        ((List <string>)groupHashes).Sort(StringComparer.CurrentCultureIgnoreCase);
                        for (var hgi = 0;; hgi++)
                        {
                            if (hgi == groupHashes.Count)
                            {
                                var res = new HashResult();
                                res.hash      = EncodeHex(md.Digest());
                                res.pathNamer = pathNamer;
                                return(res);
                            }

                            // digest group hash
                            var groupHash = groupHashes[hgi];
                            md.Update(JavaCompat.GetBytesForString(groupHash, "UTF-8"));

                            // choose a path and namer from the permutations
                            string      chosenPath  = null;
                            UniqueNamer chosenNamer = null;
                            var         permutator  = new Permutator((JArray)groups[groupHash]);
                            while (true)
                            {
                                var contPermutation = false;
                                var breakOut        = false;
                                var permutation     = permutator.Next();
                                var pathNamerCopy   = pathNamer.Clone();

                                // build adjacent path
                                var path    = string.Empty;
                                var recurse = new JArray();
                                foreach (string bnode in permutation)
                                {
                                    // use canonical name if available
                                    if (namer.IsNamed(bnode))
                                    {
                                        path += namer.GetName(bnode);
                                    }
                                    else
                                    {
                                        // recurse if bnode isn't named in the path
                                        // yet
                                        if (!pathNamerCopy.IsNamed(bnode))
                                        {
                                            recurse.Add(bnode);
                                        }
                                        path += pathNamerCopy.GetName(bnode);
                                    }

                                    // skip permutation if path is already >= chosen
                                    // path
                                    if (chosenPath != null && path.Length >= chosenPath.Length && string.CompareOrdinal(path, chosenPath) > 0)
                                    {
                                        // return nextPermutation(true);
                                        if (permutator.HasNext())
                                        {
                                            contPermutation = true;
                                        }
                                        else
                                        {
                                            // digest chosen path and update namer
                                            md.Update(JavaCompat.GetBytesForString(chosenPath, "UTF-8"));
                                            pathNamer = chosenNamer;

                                            // hash the nextGroup
                                            breakOut = true;
                                        }

                                        break;
                                    }
                                }

                                // if we should do the next permutation
                                if (contPermutation)
                                {
                                    continue;
                                }

                                // if we should stop processing this group
                                if (breakOut)
                                {
                                    break;
                                }

                                // does the next recursion
                                for (var nrn = 0;; nrn++)
                                {
                                    if (nrn == recurse.Count)
                                    {
                                        // return nextPermutation(false);
                                        if (chosenPath == null || string.CompareOrdinal(path, chosenPath) < 0)
                                        {
                                            chosenPath  = path;
                                            chosenNamer = pathNamerCopy;
                                        }

                                        if (!permutator.HasNext())
                                        {
                                            // digest chosen path and update namer
                                            md.Update(JavaCompat.GetBytesForString(chosenPath, "UTF-8"));
                                            pathNamer = chosenNamer;

                                            // hash the nextGroup
                                            breakOut = true;
                                        }

                                        break;
                                    }

                                    // do recursion
                                    var bnode_1 = (string)recurse[nrn];
                                    var result  = HashPaths(bnode_1, bnodes, namer, pathNamerCopy);
                                    path         += pathNamerCopy.GetName(bnode_1) + "<" + result.hash + ">";
                                    pathNamerCopy = result.pathNamer;

                                    // skip permutation if path is already >= chosen
                                    // path
                                    if (chosenPath != null && path.Length >= chosenPath.Length && string.CompareOrdinal(path, chosenPath) > 0)
                                    {
                                        // return nextPermutation(true);
                                        if (!permutator.HasNext())
                                        {
                                            // digest chosen path and update namer
                                            md.Update(JavaCompat.GetBytesForString(chosenPath, "UTF-8"));
                                            pathNamer = chosenNamer;

                                            // hash the nextGroup
                                            breakOut = true;
                                        }

                                        break;
                                    }
                                }

                                // do next recursion
                                // if we should stop processing this group
                                if (breakOut)
                                {
                                    break;
                                }
                            }
                        }
                    }

                    // get adjacent bnode
                    var quad    = (IDictionary <string, object>)quads[hpi];
                    var bnode_2 = GetAdjacentBlankNodeName((IDictionary <string, object>)quad["subject"
                                                           ],
                                                           id);
                    string direction = null;
                    if (bnode_2 != null)
                    {
                        // normal property
                        direction = "p";
                    }
                    else
                    {
                        bnode_2 = GetAdjacentBlankNodeName((IDictionary <string, object>)quad["object"],
                                                           id
                                                           );
                        if (bnode_2 != null)
                        {
                            direction = "r";
                        }
                    }

                    if (bnode_2 != null)
                    {
                        // get bnode name (try canonical, path, then hash)
                        string name;
                        if (namer.IsNamed(bnode_2))
                        {
                            name = namer.GetName(bnode_2);
                        }
                        else
                        {
                            if (pathNamer.IsNamed(bnode_2))
                            {
                                name = pathNamer.GetName(bnode_2);
                            }
                            else
                            {
                                name = HashQuads(bnode_2, bnodes, namer);
                            }
                        }

                        // hash direction, property, end bnode name/hash
                        using (var md1 = MessageDigest.GetInstance("SHA-1"))
                        {
                            // String toHash = direction + (String) ((Map<String,
                            // Object>) quad.get("predicate")).get("value") + name;
                            md1.Update(JavaCompat.GetBytesForString(direction, "UTF-8"));
                            md1.Update(JavaCompat.GetBytesForString((string)((IDictionary <string, object>)quad["predicate"])["value"], "UTF-8"));
                            md1.Update(JavaCompat.GetBytesForString(name, "UTF-8"));
                            var groupHash = EncodeHex(md1.Digest());
                            if (groups.ContainsKey(groupHash))
                            {
                                ((JArray)groups[groupHash]).Add(bnode_2);
                            }
                            else
                            {
                                var tmp = new JArray();
                                tmp.Add(bnode_2);
                                groups[groupHash] = tmp;
                            }
                        }
                    }
                }
            }
            catch
            {
                // TODO: i don't expect that SHA-1 is even NOT going to be
                // available?
                // look into this further
                throw;
            }
            finally
            {
                md?.Dispose();
            }
#else
            throw new PlatformNotSupportedException();
#endif
        }
        /// <summary>
        /// Returns the Threat Level after assigning <see cref="Force"/> to
        /// <see cref="CityBlock"/>. No work is done here to remember state of any sort,
        /// only the allocated threat level is calculated and returned. It is not the most
        /// optimized thing that can be done, but given the timeframe and problem domain,
        /// this is pretty close to being good enough.
        /// </summary>
        /// <returns></returns>
        private int Allocate()
        {
            //var comparer = new ForceComparer();

            var threatLevel = Blocks.Sum(x => x.ThreatLevel);

            /* Really, really (REALLY) avoid the R# help here: that could
             * be potentially very, very (VERY) expensive. */

            var permutator = new Permutator<Force>(Forces);

            do
            {
                var localForces = (from x in permutator.Values select x.Clone())
                    .OfType<Force>().ToList();

                // ReSharper disable once PossibleMultipleEnumeration
                var localBlocks = (from x in Blocks.ToArray()
                    select (CityBlock) x.Clone()).ToArray();

                // Assign all the possible forces we can to the best possible locations.
                foreach (var force in localForces
                    .TakeWhile(x => x.TryPatrol(localBlocks))
                    .Where(x => localBlocks.All(y => y.IsPatrolled)))
                {
                    break;
                }

                threatLevel = Math.Min(threatLevel,
                    localBlocks.Sum(x => x.ThreatLevel));

                // This is as low as we can go, no point in continuing through the (many) other permutations.
                if (threatLevel == 0) break;

            } while (permutator.Next());

            //// Permute the forces themselves.
            //var forcePermutations = Forces.Permute().ToArray();

            //// ReSharper disable once LoopCanBePartlyConvertedToQuery
            //foreach (var forces in forcePermutations)
            //{
            //    var localForces = (from x in forces
            //        select x.Clone()).OfType<Force>().ToArray();

            //    // ReSharper disable once PossibleMultipleEnumeration
            //    var localBlocks = (from x in Blocks.ToArray()
            //        select (CityBlock) x.Clone()).ToArray();

            //    // Assign all the possible forces we can to the best possible locations.
            //    foreach (var force in localForces
            //        .TakeWhile(x => x.TryPatrol(localBlocks))
            //        .Where(x => localBlocks.All(y => y.IsPatrolled)))
            //    {
            //        break;
            //    }

            //    threatLevel = Math.Min(threatLevel,
            //        localBlocks.Sum(x => x.ThreatLevel));

            //    // This is as low as we can go, no point in continuing through the (many) other permutations.
            //    if (threatLevel == 0) break;
            //}

            return threatLevel;
        }
Пример #29
0
        // to search for the solution we must
        // find the 126 possible selections for X
        // and determine the set difference set Y. We then must test
        // the various orders of X and Y. In total we
        // end up checking about 10^6 combinations.

        static void Main()
        {
            List <int> t = new List <int>()
            {
                1, 2, 3, 4, 5, 6, 7, 8, 9, 10
            };

            for (int i = 1; i <= 9; ++i)
            {
                for (int j = i + 1; j <= 9; ++j)
                {
                    for (int k = j + 1; k <= 9; ++k)
                    {
                        for (int m = k + 1; m <= 9; ++m)
                        {
                            for (int n = m + 1; n <= 9; ++n)
                            {
                                // for each set of i,j,k,l,m, and n
                                // we want to check the linear solution
                                // using all possible permutations of these numbers
                                // as well as the possible permutations of the difference
                                // set with [1,10]
                                List <int> dSet = new List <int>();
                                List <int> X    = new List <int>();
                                X.Add(i);
                                X.Add(j);
                                X.Add(k);
                                X.Add(m);
                                X.Add(n);
                                foreach (int x in t)
                                {
                                    if (x != i &&
                                        x != j &&
                                        x != k &&
                                        x != m &&
                                        x != n)
                                    {
                                        dSet.Add(x);
                                    }
                                }

                                // now that we have the difference set, we need
                                // to operate on all the permutations of these numbers
                                // and compute the constant we need for our computations
                                int constant = 0;
                                foreach (int item in dSet)
                                {
                                    constant += item;
                                }
                                foreach (int item in X)
                                {
                                    constant += 2 * item;
                                }
                                constant /= 5;

                                List <List <int> > permsX    = Permutator.getIntPermutations(X);
                                List <List <int> > permsDSet = Permutator.getIntPermutations(dSet);
                                foreach (List <int> u in permsDSet)
                                {
                                    foreach (List <int> v in permsX)
                                    {
                                        if (u[0] + v[0] + v[1] == constant &&
                                            u[1] + v[1] + v[2] == constant &&
                                            u[2] + v[2] + v[3] == constant &&
                                            u[3] + v[3] + v[4] == constant &&
                                            u[4] + v[4] + v[0] == constant)
                                        {
                                            // print the solution sets, but print
                                            // the solution in the format as described in the problem description
                                            int min = 10, index = 0;
                                            for (int x1 = 0; x1 < u.Count; ++x1)
                                            {
                                                if (u[x1] <= min)
                                                {
                                                    min   = u[x1];
                                                    index = x1;
                                                }
                                            }
                                            for (int x1 = 0; x1 < u.Count; ++x1)
                                            {
                                                int x2 = (x1 + index) % u.Count;
                                                Console.Write(u[x2] + "," + v[x2 % 5] + "," + v[(x2 + 1) % 5] + "; ");
                                            }
                                            Console.WriteLine();
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            // Keep the console window open in debug mode.
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }