Exemple #1
0
        private static void FindAllSolutions_Recur(int number, int power, SquareStack tmpSolution, List <CandidateSet> candidates = null)
        {
            if (tmpSolution.GetTopCandidateSum() == number)
            {
                return;
            }
            else if (tmpSolution.GetTopCandidateSum() > number)
            {
                tmpSolution.RemoveTop();
            }

            if (candidates != null && candidates.All(x => x.IsVisited) && tmpSolution.GetTopCandidateSum() != number)
            {
                tmpSolution.RemoveTop();
                return;
            }

            int flooredRoot = FlooredRoot(number - tmpSolution.GetTopCandidateSum(), power, tmpSolution.GetTopCandidate());

            if (tmpSolution.StackContains(flooredRoot))
            {
                tmpSolution.RemoveTop();
                return;
            }

            candidates = FindCandidateSet(flooredRoot, tmpSolution.GetTopCandidate());

            foreach (CandidateSet candidateSet in candidates.Where(x => x.IsVisited == false).ToList())
            {
                if (tmpSolution.GetTopCandidate() < candidateSet.Candidate)
                {
                    tmpSolution.RemoveTop();
                    return;
                }

                candidateSet.IsVisited = true;
                tmpSolution.Add(candidateSet.Candidate, power);
                FindAllSolutions_Recur(number, power, tmpSolution, candidates);

                if (tmpSolution.GetTopCandidateSum() != number)
                {
                    tmpSolution.RemoveTop();
                }
                else
                {
                    return;
                }
            }
        }
Exemple #2
0
        // best solution ever
        public static void FindAllSolutions(int number, int power, List <string> solutions)
        {
            int flooredRoot = FlooredRoot(number, power);
            List <CandidateSet> mainRoots = FindCandidateSet(flooredRoot);

            foreach (CandidateSet candidateSet in mainRoots)
            {
                SquareStack tmpSolution = new SquareStack {
                    { candidateSet.Candidate, power, true }
                };

                FindAllSolutions_Recur(number, power, tmpSolution);

                if (tmpSolution.GetTopCandidateSum() == number)
                {
                    string sln = tmpSolution.ToPowerExpression(power);

                    if (!solutions.Any(x => x.Equals(sln)))
                    {
                        solutions.Add(sln);
                    }
                }
            }
        }