Exemple #1
0
    /*!
     * Shuffle an array. Found on https://dotnetperls.com/fisher-yates-shuffle
     */
    public static void Shuffle <T>(T[] state)
    {
        int l = state.Length;

        for (int i = 0; i < l; i++)
        {
            //! NextDouble returns a double from
            //! 0 to 1
            int r = i + (int)(_random.NextDouble() * (l - i));
            NPuzzleUtils.Swap(state, i, r);
        }
    }
        /*!
         * Don't test for inversions with the largest
         * element in the array
         */
        public void TestCountInversions()
        {
            int[] s1 = { 9, 8, 7, 6, 5, 4, 3, 2, 1 };
            Assert.AreEqual(NPuzzleUtils.CountInversions(s1), 28);
            NPuzzleUtils.Swap(s1, 1, 2);
            Assert.AreEqual(NPuzzleUtils.CountInversions(s1), 27);
            int[] s2 = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            Assert.AreEqual(NPuzzleUtils.CountInversions(s2), 0);

            NPuzzleUtils.Swap(s2, 7, 8);

            Assert.AreEqual(NPuzzleUtils.CountInversions(s2), 0);

            NPuzzleUtils.Swap(s2, 6, 7);

            Assert.AreEqual(NPuzzleUtils.CountInversions(s2), 0);
        }
Exemple #3
0
        // TODO: again, NPuzzleState return type instead of int[]
        public override NPuzzleState <int[]> Result(NPuzzleState <int[]> s, int action)
        {
            int[] state    = s.State;
            int[] newState = new int[state.Length];
            int   emptyIndex;

            state.CopyTo(newState, 0);

            emptyIndex = GetEmptyIndex(state);
            if (emptyIndex == -1)
            {
                NPuzzleUtils.MissingEmptyElementException ex = new NPuzzleUtils.MissingEmptyElementException(state.Length.ToString());
                throw ex;
            }
            if (AcceptableAction(state, emptyIndex, action))
            {
                if (action == 1)
                {
                    NPuzzleUtils.Swap(newState, emptyIndex, emptyIndex + 1);
                }
                else if (action == -1)
                {
                    NPuzzleUtils.Swap(newState, emptyIndex, emptyIndex - 1);
                }
                else if (action == -2)
                {
                    NPuzzleUtils.Swap(newState, emptyIndex, emptyIndex + dimension);
                }
                else
                {
                    NPuzzleUtils.Swap(newState, emptyIndex, emptyIndex - dimension);
                }
            }
            else
            {
                String msg = String.Format("You entered an invalid action: {0} for the state {1}", action, state.ToString());
                NPuzzleUtils.ResultAcceptableActionException ex = new NPuzzleUtils.ResultAcceptableActionException(msg);
                throw ex;
            }

            return(new NPuzzleState <int[]>(newState));
        }