protected int RandomBackTrackAndDelay(Stack<TraversalInfo> searchStack, int startPoint)
        {
            //back track the stack randomly to some point
            var backtrackAt = ZingerUtilities.rand.Next(startPoint, searchStack.Count() + 1);
            while (searchStack.Count() > backtrackAt)
            {
                searchStack.Pop();
            }
            //delay the schedule
            var delayedState = searchStack.Peek().GetDelayedSuccessor();

            if (delayedState == null)
            {
                return -1;
            }

            TerminalState terminal = delayedState as TerminalState;
            if (terminal != null)
            {
                if (terminal.IsErroneousTI)
                {
                    lock (SafetyErrors)
                    {
                        SafetyErrors.Add(delayedState.GenerateNonCompactTrace());
                        this.lastErrorFound = delayedState.ErrorCode;
                    }

                    if (ZingerConfiguration.StopOnError)
                    {
                        //Stop all tasks
                        CancelTokenZingExplorer.Cancel(true);
                        throw delayedState.Exception;
                    }
                }
                return -1;
            }
            //push it on stack
            searchStack.Push(delayedState);

            return searchStack.Count();
        }
Example #2
0
        public Stack<int> RoundOnce(Stack<int> A)
        {

            Stack<int> B = new Stack<int>();

            int item = A.Pop();
            B.Push(item);

            for (int i = A.Count() - 1; i >= 0; i--)
            {
                B.Push(A.ElementAt(i));
            }
            return B;
        }
Example #3
0
        public int[] Solution(int[] A, int K)
        {
            Stack<int> B = new Stack<int>();
            if (A.Length == 0) return A;

            int[] res = new int[A.Length];
            for (int i = 0; i < A.Length; i++)
            {
                B.Push(A[i]);
            }
            for (int i = 0; i < K; i++)
            {
                B = RoundOnce(B);
            }
            for (int i = B.Count() - 1, j = 0; i >= 0; i--, j++)
            {
                res[j] = B.ElementAt(i);
            }
            return res;

        }
Example #4
0
        /// <summary>
        /// This is called to fill best path for solution.
        /// </summary>
        /// <param name="flagpass">A flag, 0 for DFS, 1 for BFS.</param>
        public void getPath(Object flagpass)
        {
            int flag = (int)flagpass;
            mapboat = new Dictionary<String, bool>();
            List<Boat> listboatf = new List<Boat>();
            foreach (Boat boat in boats)
            {
                listboatf.Add(new Boat(this,boat));
            }
            List<BoatPath> boatpath = new List<BoatPath>();
            mapboat.Add(ListBoatToString(listboatf), false);
            bestmove = -1;

            if (flag == 0)
            {
                bool cek = true;
                Stack<KeyValuePair<KeyValuePair<List<Boat>, List<BoatPath>>, Sea>> stackDFS = new Stack<KeyValuePair<KeyValuePair<List<Boat>, List<BoatPath>>, Sea>>();
                stackDFS.Push(new KeyValuePair<KeyValuePair<List<Boat>, List<BoatPath>>, Sea>(new KeyValuePair<List<Boat>, List<BoatPath>>(listboatf, boatpath), new Sea(this, map)));

                while ((cek)&&(stackDFS.Count() > 0))
                {
                    KeyValuePair<KeyValuePair<List<Boat>, List<BoatPath>>, Sea> pair = stackDFS.Pop();
                    List<Boat> listboat = pair.Key.Key;
                    List<BoatPath> listpath = pair.Key.Value;
                    Sea localmap = pair.Value;

                    if ((int)(listboat.ElementAt(0).Position.X / widthPerTile) + (int)(listboat.ElementAt(0).Size.X / widthPerTile) == map.outPos.X)
                    {
                        bestmove = listpath.Count();
                        bestpath = listpath;
                        cek = false;
                    }
                    if (cek)
                    {
                        for (int i = 0; i < listboat.Count(); ++i)
                        {
                            Boat tempboat = listboat.ElementAt(i);
                            if ((tempboat.Arah == Boat.Orientation.Left) || (tempboat.Arah == Boat.Orientation.Right))
                            {
                                int x = (int)(tempboat.Position.X / widthPerTile);
                                int y = (int)(tempboat.Position.Y / heightPerTile);
                                int sizex = (int)(tempboat.Size.X / widthPerTile);
                                if ((x > 0) && (localmap.GetStatus(x - 1, y) == 0))
                                {
                                    listboat.ElementAt(i).Position = new Vector2((x - 1) * widthPerTile, y * heightPerTile);
                                    bool tempbool = false;
                                    if ((!(mapboat.TryGetValue(ListBoatToString(listboat), out tempbool))) || (tempbool))
                                    {
                                        if (!tempbool)
                                            mapboat.Add(ListBoatToString(listboat), false);
                                        else
                                            mapboat[ListBoatToString(listboat)] = false;
                                        localmap.SetStatus(x - 1, y, 1);
                                        localmap.SetStatus(x + sizex - 1, y, 0);
                                        List<BoatPath> templistpath = listpath.ToList();
                                        templistpath.Add(new BoatPath(i, new Vector2(x * widthPerTile, y * heightPerTile), new Vector2((x - 1) * widthPerTile, y * heightPerTile)));
                                        List<Boat> templistboat = new List<Boat>();
                                        foreach (Boat boat in listboat)
                                        {
                                            templistboat.Add(new Boat(this, boat));
                                        }
                                        stackDFS.Push(new KeyValuePair<KeyValuePair<List<Boat>, List<BoatPath>>, Sea>(
                                                        new KeyValuePair<List<Boat>, List<BoatPath>>(templistboat, templistpath), new Sea(this,localmap)));
                                    }
                                    listboat.ElementAt(i).Position = new Vector2(x * widthPerTile, y * heightPerTile);
                                    localmap.SetStatus(x - 1, y, 0);
                                    localmap.SetStatus(x + sizex - 1, y, 1);
                                }
                                if ((x + sizex < sizeX) && (localmap.GetStatus(x + sizex, y) == 0))
                                {
                                    listboat.ElementAt(i).Position = new Vector2((x + 1) * widthPerTile, y * heightPerTile);
                                    bool tempbool = false;
                                    if ((!(mapboat.TryGetValue(ListBoatToString(listboat), out tempbool))) || (tempbool))
                                    {
                                        if (!tempbool)
                                            mapboat.Add(ListBoatToString(listboat), false);
                                        else
                                            mapboat[ListBoatToString(listboat)] = false;
                                        localmap.SetStatus(x + sizex, y, 1);
                                        localmap.SetStatus(x, y, 0);
                                        List<BoatPath> templistpath = listpath.ToList();
                                        templistpath.Add(new BoatPath(i, new Vector2(x * widthPerTile, y * heightPerTile), new Vector2((x + 1) * widthPerTile, y * heightPerTile)));
                                        List<Boat> templistboat = new List<Boat>();
                                        foreach (Boat boat in listboat)
                                        {
                                            templistboat.Add(new Boat(this, boat));
                                        }
                                        stackDFS.Push(new KeyValuePair<KeyValuePair<List<Boat>, List<BoatPath>>, Sea>(
                                            new KeyValuePair<List<Boat>, List<BoatPath>>(templistboat, templistpath), new Sea(this, localmap)));
                                    }
                                    listboat.ElementAt(i).Position = new Vector2(x * widthPerTile, y * heightPerTile);
                                    localmap.SetStatus(x + sizex, y, 0);
                                    localmap.SetStatus(x, y, 1);
                                }
                            }
                            else if ((tempboat.Arah == Boat.Orientation.Top) || (tempboat.Arah == Boat.Orientation.Bottom))
                            {
                                int x = (int)(tempboat.Position.X / widthPerTile);
                                int y = (int)(tempboat.Position.Y / heightPerTile);
                                int sizey = (int)(tempboat.Size.Y / heightPerTile);
                                if ((y > 0) && (localmap.GetStatus(x, y - 1) == 0))
                                {
                                    listboat.ElementAt(i).Position = new Vector2(x * widthPerTile, (y - 1) * heightPerTile);
                                    bool tempbool = false;
                                    if ((!(mapboat.TryGetValue(ListBoatToString(listboat), out tempbool))) || (tempbool))
                                    {
                                        if (!tempbool)
                                            mapboat.Add(ListBoatToString(listboat), false);
                                        else
                                            mapboat[ListBoatToString(listboat)] = false;
                                        localmap.SetStatus(x, y - 1, 1);
                                        localmap.SetStatus(x, y + sizey - 1, 0);
                                        List<BoatPath> templistpath = listpath.ToList();
                                        templistpath.Add(new BoatPath(i, new Vector2(x * widthPerTile, y * heightPerTile), new Vector2(x * widthPerTile, (y - 1) * heightPerTile)));
                                        List<Boat> templistboat = new List<Boat>();
                                        foreach (Boat boat in listboat)
                                        {
                                            templistboat.Add(new Boat(this, boat));
                                        }
                                        stackDFS.Push(new KeyValuePair<KeyValuePair<List<Boat>, List<BoatPath>>, Sea>(
                                            new KeyValuePair<List<Boat>, List<BoatPath>>(templistboat, templistpath), new Sea(this, localmap)));
                                    }
                                    listboat.ElementAt(i).Position = new Vector2(x * widthPerTile, y * heightPerTile);
                                    localmap.SetStatus(x, y - 1, 0);
                                    localmap.SetStatus(x, y + sizey - 1, 1);
                                }
                                if ((y + sizey < sizeY) && (localmap.GetStatus(x, y + sizey) == 0))
                                {
                                    listboat.ElementAt(i).Position = new Vector2(x * widthPerTile, (y + 1) * heightPerTile);
                                    bool tempbool = false;
                                    if ((!(mapboat.TryGetValue(ListBoatToString(listboat), out tempbool))) || (tempbool))
                                    {
                                        if (!tempbool)
                                            mapboat.Add(ListBoatToString(listboat), false);
                                        else
                                            mapboat[ListBoatToString(listboat)] = false;
                                        localmap.SetStatus(x, y + sizey, 1);
                                        localmap.SetStatus(x, y, 0);
                                        List<BoatPath> templistpath = listpath.ToList();
                                        templistpath.Add(new BoatPath(i, new Vector2(x * widthPerTile, y * heightPerTile), new Vector2(x * widthPerTile, (y + 1) * heightPerTile)));
                                        List<Boat> templistboat = new List<Boat>();
                                        foreach (Boat boat in listboat)
                                        {
                                            templistboat.Add(new Boat(this, boat));
                                        }
                                        stackDFS.Push(new KeyValuePair<KeyValuePair<List<Boat>, List<BoatPath>>, Sea>(
                                            new KeyValuePair<List<Boat>, List<BoatPath>>(templistboat, templistpath), new Sea(this, localmap)));
                                    }
                                    listboat.ElementAt(i).Position = new Vector2(x * widthPerTile, y * heightPerTile);
                                    localmap.SetStatus(x, y + sizey, 0);
                                    localmap.SetStatus(x, y, 1);
                                }
                            }
                        }
                    }
                }
            }
            else if (flag == 1)
            {
                bool cek = true;
                Queue<KeyValuePair<KeyValuePair<List<Boat>, List<BoatPath>>, Sea>> queueBFS = new Queue<KeyValuePair<KeyValuePair<List<Boat>, List<BoatPath>>, Sea>>();
                queueBFS.Enqueue(new KeyValuePair<KeyValuePair<List<Boat>, List<BoatPath>>, Sea>(new KeyValuePair<List<Boat>, List<BoatPath>>(listboatf, boatpath), new Sea(this, map)));

                while ((cek) && (queueBFS.Count() > 0))
                {
                    KeyValuePair<KeyValuePair<List<Boat>, List<BoatPath>>, Sea> pair = queueBFS.Dequeue();
                    List<Boat> listboat = pair.Key.Key;
                    List<BoatPath> listpath = pair.Key.Value;
                    Sea localmap = pair.Value;

                    if ((int)(listboat.ElementAt(0).Position.X / widthPerTile) + (int)(listboat.ElementAt(0).Size.X / widthPerTile) == map.outPos.X)
                    {
                        bestmove = listpath.Count();
                        bestpath = listpath;
                        cek = false;
                    }
                    if (cek)
                    {
                        for (int i = 0; i < listboat.Count(); ++i)
                        {
                            Boat tempboat = listboat.ElementAt(i);
                            if ((tempboat.Arah == Boat.Orientation.Left) || (tempboat.Arah == Boat.Orientation.Right))
                            {
                                int x = (int)(tempboat.Position.X / widthPerTile);
                                int y = (int)(tempboat.Position.Y / heightPerTile);
                                int sizex = (int)(tempboat.Size.X / widthPerTile);
                                if ((x > 0) && (localmap.GetStatus(x - 1, y) == 0))
                                {
                                    listboat.ElementAt(i).Position = new Vector2((x - 1) * widthPerTile, y * heightPerTile);
                                    bool tempbool = false;
                                    if ((!(mapboat.TryGetValue(ListBoatToString(listboat), out tempbool))) || (tempbool))
                                    {
                                        if (!tempbool)
                                            mapboat.Add(ListBoatToString(listboat), false);
                                        else
                                            mapboat[ListBoatToString(listboat)] = false;
                                        localmap.SetStatus(x - 1, y, 1);
                                        localmap.SetStatus(x + sizex - 1, y, 0);
                                        List<BoatPath> templistpath = listpath.ToList();
                                        templistpath.Add(new BoatPath(i, new Vector2(x * widthPerTile, y * heightPerTile), new Vector2((x - 1) * widthPerTile, y * heightPerTile)));
                                        List<Boat> templistboat = new List<Boat>();
                                        foreach (Boat boat in listboat)
                                        {
                                            templistboat.Add(new Boat(this, boat));
                                        }
                                        queueBFS.Enqueue(new KeyValuePair<KeyValuePair<List<Boat>, List<BoatPath>>, Sea>(
                                                        new KeyValuePair<List<Boat>, List<BoatPath>>(templistboat, templistpath), new Sea(this, localmap)));
                                    }
                                    listboat.ElementAt(i).Position = new Vector2(x * widthPerTile, y * heightPerTile);
                                    localmap.SetStatus(x - 1, y, 0);
                                    localmap.SetStatus(x + sizex - 1, y, 1);
                                }
                                if ((x + sizex < sizeX) && (localmap.GetStatus(x + sizex, y) == 0))
                                {
                                    listboat.ElementAt(i).Position = new Vector2((x + 1) * widthPerTile, y * heightPerTile);
                                    bool tempbool = false;
                                    if ((!(mapboat.TryGetValue(ListBoatToString(listboat), out tempbool))) || (tempbool))
                                    {
                                        if (!tempbool)
                                            mapboat.Add(ListBoatToString(listboat), false);
                                        else
                                            mapboat[ListBoatToString(listboat)] = false;
                                        localmap.SetStatus(x + sizex, y, 1);
                                        localmap.SetStatus(x, y, 0);
                                        List<BoatPath> templistpath = listpath.ToList();
                                        templistpath.Add(new BoatPath(i, new Vector2(x * widthPerTile, y * heightPerTile), new Vector2((x + 1) * widthPerTile, y * heightPerTile)));
                                        List<Boat> templistboat = new List<Boat>();
                                        foreach (Boat boat in listboat)
                                        {
                                            templistboat.Add(new Boat(this, boat));
                                        }
                                        queueBFS.Enqueue(new KeyValuePair<KeyValuePair<List<Boat>, List<BoatPath>>, Sea>(
                                            new KeyValuePair<List<Boat>, List<BoatPath>>(templistboat, templistpath), new Sea(this, localmap)));
                                    }
                                    listboat.ElementAt(i).Position = new Vector2(x * widthPerTile, y * heightPerTile);
                                    localmap.SetStatus(x + sizex, y, 0);
                                    localmap.SetStatus(x, y, 1);
                                }
                            }
                            else if ((tempboat.Arah == Boat.Orientation.Top) || (tempboat.Arah == Boat.Orientation.Bottom))
                            {
                                int x = (int)(tempboat.Position.X / widthPerTile);
                                int y = (int)(tempboat.Position.Y / heightPerTile);
                                int sizey = (int)(tempboat.Size.Y / heightPerTile);
                                if ((y > 0) && (localmap.GetStatus(x, y - 1) == 0))
                                {
                                    listboat.ElementAt(i).Position = new Vector2(x * widthPerTile, (y - 1) * heightPerTile);
                                    bool tempbool = false;
                                    if ((!(mapboat.TryGetValue(ListBoatToString(listboat), out tempbool))) || (tempbool))
                                    {
                                        if (!tempbool)
                                            mapboat.Add(ListBoatToString(listboat), false);
                                        else
                                            mapboat[ListBoatToString(listboat)] = false;
                                        localmap.SetStatus(x, y - 1, 1);
                                        localmap.SetStatus(x, y + sizey - 1, 0);
                                        List<BoatPath> templistpath = listpath.ToList();
                                        templistpath.Add(new BoatPath(i, new Vector2(x * widthPerTile, y * heightPerTile), new Vector2(x * widthPerTile, (y - 1) * heightPerTile)));
                                        List<Boat> templistboat = new List<Boat>();
                                        foreach (Boat boat in listboat)
                                        {
                                            templistboat.Add(new Boat(this, boat));
                                        }
                                        queueBFS.Enqueue(new KeyValuePair<KeyValuePair<List<Boat>, List<BoatPath>>, Sea>(
                                            new KeyValuePair<List<Boat>, List<BoatPath>>(templistboat, templistpath), new Sea(this, localmap)));
                                    }
                                    listboat.ElementAt(i).Position = new Vector2(x * widthPerTile, y * heightPerTile);
                                    localmap.SetStatus(x, y - 1, 0);
                                    localmap.SetStatus(x, y + sizey - 1, 1);
                                }
                                if ((y + sizey < sizeY) && (localmap.GetStatus(x, y + sizey) == 0))
                                {
                                    listboat.ElementAt(i).Position = new Vector2(x * widthPerTile, (y + 1) * heightPerTile);
                                    bool tempbool = false;
                                    if ((!(mapboat.TryGetValue(ListBoatToString(listboat), out tempbool))) || (tempbool))
                                    {
                                        if (!tempbool)
                                            mapboat.Add(ListBoatToString(listboat), false);
                                        else
                                            mapboat[ListBoatToString(listboat)] = false;
                                        localmap.SetStatus(x, y + sizey, 1);
                                        localmap.SetStatus(x, y, 0);
                                        List<BoatPath> templistpath = listpath.ToList();
                                        templistpath.Add(new BoatPath(i, new Vector2(x * widthPerTile, y * heightPerTile), new Vector2(x * widthPerTile, (y + 1) * heightPerTile)));
                                        List<Boat> templistboat = new List<Boat>();
                                        foreach (Boat boat in listboat)
                                        {
                                            templistboat.Add(new Boat(this, boat));
                                        }
                                        queueBFS.Enqueue(new KeyValuePair<KeyValuePair<List<Boat>, List<BoatPath>>, Sea>(
                                            new KeyValuePair<List<Boat>, List<BoatPath>>(templistboat, templistpath), new Sea(this, localmap)));
                                    }
                                    listboat.ElementAt(i).Position = new Vector2(x * widthPerTile, y * heightPerTile);
                                    localmap.SetStatus(x, y + sizey, 0);
                                    localmap.SetStatus(x, y, 1);
                                }
                            }
                        }
                    }
                }
            }
        }
Example #5
0
        private void evalNumExpr()
        {
            //initialize stack
            Stack<Object> s = new Stack<Object>();
            Double result = 0;
            String ex = "";

            if (expr.Count() < 2 && expr.Count() > 0)
            {
                string temp = expr.Pop();
                if (Double.TryParse(temp, out result))
                {
                    acc = result;
                    ans = acc.ToString();
                }
                else if(temp == "totoo")
                {
                    abc = true;
                    ans = "totoo";
                }
                else if (temp == "peke")
                {
                    abc = false;
                    ans = "peke";
                }
               return;
            }

            while (expr.Count() != 0)
            {
                /**
                    fetch part
                **/
                String i = expr.Pop();
                while (true)
                {
                    //check if input is a number
                    if (Double.TryParse(i, out result))
                    {
                        s.Push(result);
                    }

                    //check if input is a string literal
                    /*else if(){
                    }*/

                    //check if input is a variable
                    else if (variableExists(i))
                    {
                        s.Push(i);
                    }

                    //input is a command
                    else
                    {
                        ex = i;
                        break;
                    }

                    //get next lexeme
                    i = expr.Pop();
                }

                /**
                 * execute part
                 * Check what kind of instruction
                 **/

                /** Arithmetic Operations**/
                //addition operator
                if (ex == "+")
                {
                    s.Push((Double)s.Pop() + (Double)s.Pop());
                }

                //subtraction operator
                else if (ex == "-")
                {
                    s.Push((Double)s.Pop() - (Double)s.Pop());
                }

                //multiplication operator
                else if (ex == "*")
                {
                    s.Push((Double)s.Pop() * (Double)s.Pop());
                }

                //division operator
                else if (ex == "/")
                {
                    s.Push((Double)s.Pop() / (Double)s.Pop());
                }

                //modulo operator
                else if (ex == "%")
                {
                    s.Push((Double)s.Pop() % (Double)s.Pop());
                }

                /** Logical Operations**/
                else if (ex == "<")
                {
                    abc = (Double)s.Pop() < (Double)s.Pop() ? true : false;
                    if (abc == true) ans = "totoo";
                    else ans = "peke";
                }
                else if (ex == ">")
                {
                    abc = (Double)s.Pop() > (Double)s.Pop() ? true : false;
                    if (abc == true) ans = "totoo";
                    else ans = "peke";
                }
                else if (ex == "<=")
                {
                    abc = (Double)s.Pop() <= (Double)s.Pop() ? true : false;
                    if (abc == true) ans = "totoo";
                    else ans = "peke";
                }
                else if (ex == ">=")
                {
                    abc = (Double)s.Pop() >= (Double)s.Pop() ? true : false;
                    if (abc == true) ans = "totoo";
                    else ans = "peke";
                }
                else if (ex == "=")
                {
                    abc = (Double)s.Pop() == (Double)s.Pop() ? true : false;
                    if (abc == true) ans = "totoo";
                    else ans = "peke";
                }
            }
            if (s.Count() != 0)
            {
                acc = (Double)s.Pop();
                ans = acc.ToString();
            }
        }
        private static void FilterCommandsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            AutoCompleteTextBox autoCompleteTextBox = d as AutoCompleteTextBox;

            if (autoCompleteTextBox == null)
                return;

            var commandTextList = new Stack<IFilterCommand>((IEnumerable<IFilterCommand>)e.NewValue);

            while (commandTextList.Count != 0)
            {
                IFilterCommand filterCommand = commandTextList.Pop();

                if (commandTextList.Count(c => c.CommandText == filterCommand.CommandText) > 0)
                {
                    throw new ArgumentException(string.Format("Two filter commands with the same command text \"{0}\" were added.  The command text must be unique.", filterCommand.CommandText));
                }
            }
        }
Example #7
0
        /// <summary>
        /// Takes in an expression in the form of a string; returns answer as integer
        /// </summary>
        /// <param name="v"></param>
        /// <returns></returns>
        public static int Evaluate(String exp, Lookup variableEvaluator)
        {
            exp = exp.Replace(" ", ""); //Cut out empty space
            string[] substrings = Regex.Split(exp, "(\\()|(\\))|(-)|(\\+)|(\\*)|(/)"); //Separates pieces of equation
            Stack<double> values = new Stack<double>();
            Stack<string> operators = new Stack<string>();
            int i = 0;
            int ssize = substrings.Count();
            int number = 0;
            for (i = 0; i < ssize; i++) //Will iterate once for each piece of equation
            {
                //Check for integer first
                if (Int32.TryParse(substrings[i], out number))
                {
                    Convert.ToDouble(number);
                    if (operators.Count() != 0)
                    {
                        //Multi/divi carried out first; we'll do that now with the current and previous number if needed
                        if (operators.Peek() == "*" || operators.Peek() == "/")
                        {
                            if (operators.Peek() == "*")
                            {
                                string now = operators.Pop();
                                double first = values.Pop();
                                values.Push(first * number);
                            }
                            else
                            {
                                string now = operators.Pop();
                                double first = values.Pop();
                                values.Push(first / number);
                            }
                        }
                        else //If another operator waits, number goes to stack; we'll come back
                        {
                            values.Push(number);
                        }
                    }
                    else //Number also goes to stack if there are no operators
                    {
                        values.Push(number);
                    }
                }

                //Check for variable (has a letter in it) and put it on stack
                else if (substrings[i].Any(x => char.IsLetter(x))) //Checks for letter(variable)
                {
                    values.Push(Convert.ToDouble(variableEvaluator(substrings[i])));
                }

                //Check for addition/subtraction
                else if (substrings[i].Equals("+") || substrings[i].Equals("-")) //Checks for addition/subtraction
                {
                    if (operators.Count() != 0)
                    {
                        //Carry out previous addition/subtraction (other operations will be handled by this point)
                        if (operators.Peek() == "+")
                        {
                            string now = operators.Pop();
                            double second = values.Pop();
                            double first = values.Pop();
                            values.Push(first + second);
                        }
                        else if (operators.Peek() == "-")
                        {
                            string now = operators.Pop();
                            double second = values.Pop();
                            double first = values.Pop();
                            values.Push(first - second);
                        }
                    }
                    operators.Push(substrings[i]); //Put on stack if there aren't other operators there
                }

                //Check for multiplication/division/opening parenthesis and put on stack
                else if (substrings[i].Equals("*") || substrings[i].Equals("/")
                    || substrings[i].Equals("("))
                {
                    operators.Push(substrings[i]);
                }

                //Check for closing parenthesis
                else if (substrings[i].Equals(")"))
                {
                    //if parentheses contain add/sub, we carry it out
                    //(add/sub expected to be reason for parentheses)
                    if (operators.Peek() == "+" || operators.Peek() == "-")
                    {
                        if (operators.Peek() == "+")
                        {
                            string now = operators.Pop();
                            double second = values.Pop();
                            double first = values.Pop();
                            values.Push(first + second);
                        }
                        else
                        {
                            string now = operators.Pop();
                            double second = values.Pop();
                            double first = values.Pop();
                            values.Push(first - second);
                        }
                    }

                    //Take the opening parenthesis off the stack
                    if (operators.Peek() == "(")
                    {
                        operators.Pop();
                    }

                    //Carry out the multi/divi waiting outside parentheses
                    if (operators.Peek() == "*" || operators.Peek() == "/")
                    {
                        if (operators.Peek() == "*")
                        {
                            string now = operators.Pop();
                            double second = values.Pop();
                            double first = values.Pop();
                            values.Push(first * second);
                        }
                        else
                        {
                            string now = operators.Pop();
                            double second = values.Pop();
                            if (second == 0) { throw new ArgumentException("Division by zero encountered"); }
                            double first = values.Pop();
                            values.Push(first / second);
                        }
                    }
                }

                //Exception thrown if another symbol is used
                else if (substrings[i] != "") //Regex leaves some empty strings
                {
                    {
                        throw new System.ArgumentException("Expression contains invalid character");
                    }
                }
            }

            //Return answer if no operators remain
            if (operators.Count() == 0)
            {
                if (values.Count() == 1)
                {
                    int answer = Convert.ToInt32(values.Pop());
                    return answer;
                }
                else
                    throw new System.ArgumentException("Operators/values don't add up");
            }

            //Carry out final operation if one operator remains
            else if (operators.Count() == 1 && values.Count() == 2) ;
            {
                String now = operators.Pop();
                double second = values.Pop();
                double first = values.Pop();
                if (now == "+")
                {
                    int answer = Convert.ToInt32(first + second);
                    return answer;
                }
                else if (now == "-")
                {
                    int answer = Convert.ToInt32(first - second);
                    return answer;
                }
                //Exception if there's a structure problem in expression
                else throw new System.ArgumentException("Problem with expression construction");
            }
        }
Example #8
0
        void perturb(Tuple<List<int>, List<int>> V, int p, BidirectionalGraph<int, Edge<int>> G)
        {
            Stack<int> S1 = new Stack<int>();
            Stack<int> S2 = new Stack<int>();
            Random rand = new Random();

            foreach (int i in G.Vertices)
            {
                if (gain(i, V, G) > -rand.Next(Math.Abs(p) + 1))
                {
                    if (iV == 1)
                    {
                        V.Item1.Remove(i);
                        V.Item2.Add(i);
                        S2.Push(i);
                    }
                    else
                    {
                        V.Item2.Remove(i);
                        V.Item1.Add(i);
                        S1.Push(i);
                    }
                }
            }

            int j = V.Item1.Count() > V.Item2.Count() ? 1 : 2;
            double alpha = 0.6; //0.5 <= alpha <= 1
            int k;
            int vc = G.Vertices.Count<int>();

            while (j == 1 && V.Item1.Count() > alpha * vc && S1.Count() != 0 ||
                j == 2 && V.Item2.Count() > alpha * vc && S2.Count() != 0)
            {
                if (j == 1)
                {
                    k = S1.Pop();
                    V.Item1.Remove(k);
                    V.Item2.Add(k);
                }
                else
                {
                    k = S2.Pop();
                    V.Item2.Remove(k);
                    V.Item1.Add(k);
                }
            }
        }
Example #9
0
        /// <summary>
        /// Evaluates this Formula, using the Lookup delegate to determine the values of variables.  (The
        /// delegate takes a variable name as a parameter and returns its value (if it has one) or throws
        /// an UndefinedVariableException (otherwise).  Uses the standard precedence rules when doing the evaluation.
        /// 
        /// If no undefined variables or divisions by zero are encountered when evaluating 
        /// this Formula, its value is returned.  Otherwise, throws a FormulaEvaluationException  
        /// with an explanatory Message.
        /// </summary>
        public double Evaluate(Lookup lookup)
        {

            Stack<double> num = new Stack<double>();
            Stack<string> op = new Stack<string>();

            foreach(string e in list)
            {
                if (ifDouble(e))
                {
                    double temp;
                    Double.TryParse(e,out temp);
                    if(op.Count()!=0&&op.Peek().Equals("*"))
                    {
                        double temp1 = num.Pop();
                        op.Pop();
                        num.Push(temp * temp1);
                    }
                    else if (op.Count() != 0 && op.Peek().Equals("/"))
                    {
                        double temp1 = num.Pop();
                        op.Pop();
                        if (temp1 == 0)
                            throw new FormulaEvaluationException("can not divided by 0");
                        else
                            num.Push(temp / temp1);
                    }
                    else
                        num.Push(temp);
                }

                else if (ifVar(e))
                {
                    double temp;
                    try
                    {
                        temp = lookup(e);
                    }
                    catch (UndefinedVariableException)
                    {                    
                    }
                    temp = lookup(e);
                    if (op.Count() != 0 && op.Peek().Equals("*"))
                    {
                        double temp1 = num.Pop();
                        op.Pop();
                        num.Push(temp * temp1);
                    }
                    else if (op.Count() != 0 && op.Peek().Equals("/"))
                    {
                        double temp1 = num.Pop();
                        op.Pop();
                        if (temp1 == 0)
                            throw new FormulaEvaluationException("can not divided by 0");
                        else
                            num.Push(temp / temp1);
                    }
                    else
                        num.Push(temp);
                }

                else if(e.Equals("+")||e.Equals("-"))
                {
                    if(op.Count() != 0 && op.Peek().Equals("+"))
                    {
                        op.Pop();
                        double temp1 = num.Pop();
                        double temp2 = num.Pop();
                        num.Push(temp1 + temp2);
                        op.Push(e);
                    }
                    else if (op.Count() != 0 && op.Peek().Equals("-"))
                    {
                        op.Pop();
                        double temp1 = num.Pop();
                        double temp2 = num.Pop();
                        num.Push(temp1 - temp2);
                        op.Push(e);
                    }
                    else
                        op.Push(e);
                }

                else if(e.Equals("*") || e.Equals("/"))
                {
                    op.Push(e);
                }

                else if (e.Equals("("))
                {
                    op.Push(e);
                }
                
                else if (e.Equals(")"))
                {
                    if (op.Count() != 0 && op.Peek().Equals("+"))
                    {
                        op.Pop();
                        double temp1 = num.Pop();
                        double temp2 = num.Pop();
                        num.Push(temp1 + temp2);
                        op.Push(e);
                        op.Pop();
                    }
                    else if (op.Count() != 0 && op.Peek().Equals("-"))
                    {
                        op.Pop();
                        double temp1 = num.Pop();
                        double temp2 = num.Pop();
                        num.Push(temp1 - temp2);
                        op.Push(e);
                        op.Pop();
                    }
                    else
                        op.Pop();
                    if (op.Count() != 0 && op.Peek().Equals("*"))
                    {
                        op.Pop();
                        double temp1 = num.Pop();
                        double temp2 = num.Pop();
                        num.Push(temp1 * temp2);
                    }
                    else if (op.Count() != 0 && op.Peek().Equals("/"))
                    {
                        op.Pop();
                        double temp1 = num.Pop();
                        double temp2 = num.Pop();
                        num.Push(temp1 / temp2);
                    }
                }
            }
            if (op.Count() == 0)
            {
                return num.Pop();
            }
            else
            {
                if (op.Count() != 0 && op.Peek().Equals("+"))
                {
                    double temp1 = num.Pop();
                    double temp2 = num.Pop();
                    return temp1 + temp2;
                }
                else
                {
                    double temp1 = num.Pop();
                    double temp2 = num.Pop();
                    return temp1 - temp2;
                }           
            }
                
              
           


        }
Example #10
0
        /// <summary>
        /// Main method where the program execution starts
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            Node startNode = new Node();
            Node goalNode = new Node();

            //Prompts the user to enter start state and goal state
            Console.WriteLine("Enter the start state:");
            startNode.State = CheckInput();
            Console.WriteLine("Enter the goal state:");
            goalNode.State = CheckInput();

            startNode.PathCost = 0;
            startNode.Parent = null;

            Node bestNode = new Node();

            //Create an object of AStarProgram and call the AStar algorithm
            AStarProgram astar = new AStarProgram();
            bestNode = astar.AStar(startNode, goalNode);

            //Used a stack to display the path of solution
            Stack<Node> result = new Stack<Node>();
            if (bestNode != null)
            {
                while (bestNode.Parent != null)
                {
                    result.Push(bestNode);
                    bestNode = bestNode.Parent;
                }
            }
            else
            {
                //if bestnode is null then display
                Console.WriteLine("Solution does not exist");
            }

            //Print the solution, Number of nodes generated and nodes expanded
            Console.WriteLine("Number of Nodes in solution path : " + result.Count());
            Node tempNode = new Node();
            startNode.PrintState();
            Console.WriteLine();
            while (result.Count != 0)
            {
                tempNode = result.Pop();
                tempNode.PrintState();
                Console.WriteLine();
            }
            Console.WriteLine(); Console.WriteLine();
            Console.WriteLine("Number of Nodes generated : " + AStarProgram.noOfNodesGenerated);
            Console.WriteLine("Number of Nodes Expanded : " + AStarProgram.noOfNodesExpanded);
            Console.Read();
        }
        protected override void SearchStateSpace(object obj)
        {
            int myThreadId = (int)obj;
            while (!GlobalFrontierSet.IsCompleted())
            {
                FrontierNode fNode = GlobalFrontierSet.GetNextFrontier();
                if (fNode == null)
                {
                    //Taking item from the global frontier failed
                    Contract.Assert(GlobalFrontierSet.IsCompleted());
                    continue;
                }
                TraversalInfo startState = fNode.GetTraversalInfo(StartStateStateImpl, myThreadId);

                //Check if we need to explore the current frontier state
                if (!MustExplore(startState) && !ZingerConfiguration.DoDelayBounding)
                {
                    continue;
                }

                if (ZingerConfiguration.zBoundedSearch.checkIfIterativeCutOffReached(fNode.Bounds))
                {
                    GlobalFrontierSet.Add(startState);
                    continue;
                }

                //create search stack
                Stack<TraversalInfo> LocalSearchStack = new Stack<TraversalInfo>();
                LocalSearchStack.Push(startState);

                //dp local bounded dfs using the local search stack
                while (LocalSearchStack.Count() > 0)
                {
                    //check if cancellation token is triggered
                    if (CancelTokenZingExplorer.IsCancellationRequested)
                    {
                        return;
                    }

                    //start exploring the top of stack
                    TraversalInfo currentState = LocalSearchStack.Peek();

                    //update the maximum depth
                    ZingerStats.MaxDepth = Math.Max(ZingerStats.MaxDepth, currentState.CurrentDepth);
                    //Check if the DFS Stack Overflow has occured.
                    if (currentState.CurrentDepth > ZingerConfiguration.BoundDFSStackLength)
                    {
                        //BUG FOUND
                        //update the safety traces
                        SafetyErrors.Add(currentState.GenerateNonCompactTrace());
                        // return value
                        this.lastErrorFound = ZingerResult.DFSStackOverFlowError;

                        throw new ZingerDFSStackOverFlow();
                    }

                    //Add current state to frontier if the bound is greater than the cutoff and we have fingerprinted the state (its not a single successor state)
                    if (ZingerConfiguration.zBoundedSearch.checkIfIterativeCutOffReached(currentState.zBounds) && currentState.IsFingerPrinted)
                    {
                        GlobalFrontierSet.Add(currentState);
                        //since current state is add to the frontier; pop it
                        LocalSearchStack.Pop();

                        continue;
                    }

                    // OK. Current state is not at the frontier cutoff so lets explore further
                    TraversalInfo nextState = currentState.GetNextSuccessor();

                    //All successors explored already
                    if (nextState == null)
                    {
                        //since all successors explored pop the stack
                        LocalSearchStack.Pop();
                        continue;
                    }

                    //Check if its a terminal state
                    TerminalState terminalState = nextState as TerminalState;
                    if (terminalState != null)
                    {
                        if (terminalState.IsErroneousTI)
                        {
                            lock (SafetyErrors)
                            {
                                //BUG FOUND
                                //update the safety traces
                                SafetyErrors.Add(nextState.GenerateNonCompactTrace());
                                // return value
                                this.lastErrorFound = nextState.ErrorCode;
                            }

                            //find all errors ??
                            if (ZingerConfiguration.StopOnError)
                            {
                                //Stop all tasks
                                CancelTokenZingExplorer.Cancel(true);
                                throw nextState.Exception;
                            }
                        }

                        //else continue
                        continue;
                    }

                    if (MustExplore(nextState) && !SearchStackContains(LocalSearchStack, nextState))
                    {
                        LocalSearchStack.Push(nextState);
                        continue;
                    }
                    else
                    {
                        continue;
                    }
                }
            }
        }