Exemplo n.º 1
0
    static void Main()
    {
        //Vector v = new Vector();
        Stack v = new Stack();
        //LinkedList v = new LinkedList();
        //Queue v = new Queue();
        v.Print();

        v.Add(0);
        v.Add(1);
        v.Add(2);
        v.Print();

        v.Remove();
        v.Print();

        Console.ReadKey();

        //v.RemoveFirst();
        //v.Print();

        //v.RemoveLast();
        //v.Print();

        //v.RemoveLast();
        //v.Add(123);
        //v.Print();

        //Console.ReadKey();
    }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            Stack s = new Stack();

               s.Add(10);
               s.Add(5);
               s.Remove();
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            Stack s =new Stack();

            Random r = new Random();
            int number = r.Next(1, 9);

            s.Add(number);
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            Stack s = new Stack();

            string temp = Console.ReadLine();
            int a;
            int b;
            char x;

            for (var i = 0; i <= temp.Length - 1; i++)
            {
                if ((temp[i] >= '0') && (temp[i] <= '9'))
                {
                    int j = 0;
                    while ((temp[i + j] >= '0') && (temp[i + j] <= '9'))
                    {
                        j++;
                    }

                    string str = temp.Substring(i, j);
                    int k = int.Parse(str);
                    s.Add(k);
                    i = i + j-1;
                }
                else if (temp[i] == ')')
                {
                    b = (int)s.Last();
                    s.Remove();
                    x = (char)s.Last();
                    s.Remove();
                    a = (int)s.Last();
                    s.Remove();
                    s.Remove();
                    int Rez = Solve(a, b, x);
                    s.Add((object)Rez);
                }
                else
                {
                    s.Add(temp[i]);
                }

            }
                Console.WriteLine(s.Last());
        }
        /*
         * Value is normally added to the stack
         */
        public void Add_NormalAdding_AddsValueToStack()
        {
            //Arrange
            Stack expected = new Stack(new int[] { 5, 7, 4, 3 });
            Stack actual   = new Stack(new int[] { 7, 4, 3 });

            //Act
            actual.Add(5);
            //Assert
            Assert.AreEqual(expected, actual);
        }
Exemplo n.º 6
0
        //this test adds more than the allowed 120000 kg on top of a container and should therefore fail the
        //weight check.
        public void CheckWeightTestFalse()
        {
            //arrange
            Ship ship = new Ship(1, 1, 1, 10000000);

            ship.Rows.Clear();
            Row       row        = new Row(false);
            Stack     stack      = new Stack(10);
            Container container  = new Container(6000, Normal);
            Container container2 = new Container(100000, Normal);
            Container container3 = new Container(22000, Normal);

            //act
            stack.Add(container);
            stack.Add(container2);
            row.Add(stack);
            ship.Rows.Add(row);
            //assert
            Assert.IsFalse(stack.AddContainer(ship, row, container3));
        }
Exemplo n.º 7
0
        public void CheckHeightTestFalse()
        {
            //arrange
            Ship ship = new Ship(1, 1, 1, 10000000);

            ship.Rows.Clear();
            Row       row        = new Row(true);
            Stack     stack      = new Stack(2);
            Container container  = new Container(1000, Coolable);
            Container container2 = new Container(2000, Normal);
            Container container3 = new Container(3000, Normal);

            //act
            stack.Add(container);
            stack.Add(container2);
            row.Add(stack);
            ship.Rows.Add(row);
            //assert
            Assert.IsFalse(stack.AddContainer(ship, row, container3));
            Assert.AreEqual(2, stack.Count);
        }
Exemplo n.º 8
0
        async Task InitializeComponents()
        {
            CssClass = "standard-list";

            await Page.GetNavBar().AddButton(ButtonLocation.Right, AddButton = new ImageView
            {
                Id       = "AddButton",
                CssClass = "navbar-button",
                Path     = "Images/Icons/White-Add.png"
            }
                                             .On(x => x.Tapped, () =>
            {
                try { return(Nav.Forward <Pages.Page1Enter>()); }
                catch (Exception ex) { return(Alert.Show(ex.Message)); }
            }
                                                 ));

            await Add(HeaderTitle = new TextView
            {
                Id       = "HeaderTitle",
                Text     = "Contacts",
                CssClass = "module-header-title"
            }
                      );

            await Add(HeaderIntro = new TextView
            {
                Id       = "HeaderIntro",
                Text     = "This module allows you to see all your contacts, interact with them and generally have a lot of fun with it. Am I long enough now?",
                CssClass = "header-intro"
            }
                      );

            await Add(ButtonsContainer = new Stack
            {
                Id        = "ButtonsContainer",
                Direction = RepeatDirection.Horizontal,
                CssClass  = "top-buttons-row"
            }
                      );

            await ButtonsContainer.Add(ReloadButton = new Button { Id = "ReloadButton", Text = "Reload" }
                                       .On(x => x.Tapped, ReloadButtonTapped));

            await Add(List = new ListView <Contact, Row>
            {
                Id         = "List",
                LazyLoad   = true,
                EmptyText  = "Empty list",
                DataSource = Items,
            }
                      );
        }
Exemplo n.º 9
0
        public override async Task OnPreRender()
        {
            await base.OnPreRender();

            Title.Css.Font(size: 17, bold: true);
            Description.Css.Font(size: 10);
            Chevron.Css.Font(size: 14).TextAlignment(Alignment.Middle).Padding(top: 10, bottom: 10);
            Index.Css.Font(size: 17).TextAlignment(Alignment.Middle).Padding(top: 10, bottom: 10);

            Index.Css.Width(10.Percent()).Height(new Length.BindingLengthRequest(VerticalRow.Height));
            VerticalRow.Css.Padding(all: 10).Width(80.Percent());
            Chevron.Css.Height(new Length.BindingLengthRequest(VerticalRow.Height));

            await VerticalRow.Add(Title);

            await VerticalRow.Add(Description);

            await Add(Index);
            await Add(VerticalRow);
            await Add(Chevron);
        }
Exemplo n.º 10
0
 public void PushStack(int value)
 {
     if (StackPointer + 1 >= Stack.Count)
     {
         Stack.Add(value);
         StackPointer++;
     }
     else
     {
         Stack[StackPointer++] = value;
     }
 }
Exemplo n.º 11
0
        public mw() : this(new Builder("GameWindow.glade"))
        {
            MainWidget    = new MainWidget();
            GameWidget    = new GameWidget();
            ConnectWidget = new ConnectWidget();
            RoomWidget    = new RoomWidget();
            stack.Add(MainWidget);
            stack.Add(ConnectWidget);
            stack.Add(RoomWidget);
            stack.Add(GameWidget);


            //MainWidget.ButtonPlay += MainWindow_ButtonPlay;
            MainWidget.ButtonConnect += MainWindow_ButtonConnect;
            MainWidget.ButtonCreate  += MainWindow_ButtonCreate;
            //MainWidget.ButtonSettings += MainWindow_ButtonSettings;
            MainWidget.ButtonQuit += MainWindow_ButtonQuit;


            ConnectWidget.Connecting += ConnectWidget_Connecting;
            ConnectWidget.Cancel     += new EventHandler((o, e) => stack.VisibleChild = MainWidget);
        }
Exemplo n.º 12
0
        public override async Task OnPreRender()
        {
            await base.OnPreRender();

            Title.Css.Font(size: 17, bold: true);
            Description.Css.Font(size: 10);
            Icon.Css.Size(60);

            Icon.Css.Width(17.Percent()).Margin(top: 15, left: 15, bottom: 15);

            VerticalRow.Css
            .Padding(left: 15, bottom: 15)
            .Margin(top: 15)
            .Width(75.Percent())
            .Height(new Length.BindingLengthRequest(Icon.Height));

            await VerticalRow.Add(Title);

            await VerticalRow.Add(Description);

            await Add(Icon);
            await Add(VerticalRow);
        }
Exemplo n.º 13
0
    public static IEnumerable <int> EnumerateDigits(this int @this)
    {
        Stack <byte> stack = new Stack <byte>();

        do
        {
            var digit = (byte)(@this % 10);
            stack.Add(digit);
            @this /= 10;
        } while (@this != 0);
        while (stack.Count > 0)
        {
            yield return(stack.Pop());
        }
    }
Exemplo n.º 14
0
        private void PushFrame(StackFrame frame)
        {
            if (Stack.Any(f => f.Rule == frame.Rule && f.InputIndex == frame.InputIndex))
            {
                throw new Exception();
            }

            if (frame.Rule is NamedRule named)
            {
                Super.ReportHypothesis(named, Index);
            }

            Stack.Add(frame);
            head          = frame;
            LastOperation = Operation.Push;
        }
Exemplo n.º 15
0
        private void CluePlayerDeck(object sender, Clue.SetGameItemsEventArgs e)
        {
            Random random = new Random();

            foreach (var item in e.Clues)
            {
                int index = random.Next(item.Value.Count);
                for (int i = 0; i < item.Value.Count; i++)
                {
                    if (i != index)
                    {
                        _cards.Add(new Card(item.Value[i], item.Key));
                    }
                }
            }
        }
Exemplo n.º 16
0
 public List <TreeNode <T> > Holes(List <TreeNode <T> > holes = null)
 {
     if (holes == null)
     {
         holes = new List <TreeNode <T> >();
     }
     foreach (var child in Children)
     {
         if (child.IsHole)
         {
             holes.Add(child);
         }
         child.Holes(holes);
     }
     return(holes);
 }
Exemplo n.º 17
0
        public void IsFullTest()
        {
            var stack1 = new Stack(5);

            stack1.Add(1);
            Assert.IsFalse(stack1.IsFull);

            var stack2 = new Stack(5);

            stack2.Add(5);
            Assert.IsTrue(stack2.IsFull);

            var stack3 = new Stack();

            stack3.Add(5);
            Assert.IsFalse(stack3.IsFull);
        }
Exemplo n.º 18
0
        public Task <TView> AddButton <TView>(ButtonLocation location, TView button) where TView : View
        {
            if (location == ButtonLocation.Left)
            {
                return(Left.Add(button));
            }

            if (location == ButtonLocation.Right)
            {
                return(Right.Add(button));
            }

            else
            {
                throw new NotSupportedException(location + " is not supported?!");
            }
        }
Exemplo n.º 19
0
        AstBinary ProcessBinaryNode(AstBinary astBinary, bool inList)
        {
            var safeIsInRightSideOfBinary = _isInRightSideOfBinary;

            DescendNode(astBinary.Left);
            _isInRightSideOfBinary = true;
            DescendNode(astBinary.Right);
            _isInRightSideOfBinary = safeIsInRightSideOfBinary;
            return(astBinary);

            void DescendNode(AstNode node)
            {
                Stack.Add(node);
                Before(node, inList);
                Stack.Pop();
            }
        }
Exemplo n.º 20
0
        EquationElement Add(EquationElement item)
        {
            item.Parent = this;
            if (item is EquationValue)
            {
                // 변수와 변수 사이에 *를 삽입
                if (LastElement is EquationValue)
                {
                    Stack.Add(new Operator('*'));
                }

                if (PopSignOperator() != null)
                {
                    ((EquationValue)item).Signed = true;
                }
                Stack.Add(item);
                return(item);
            }
            if (item is Operator)
            {
                // 괄호앞에 - 이외엔 쓸수 없음.
                if (((Operator)item).CanStartTerm == false && Stack.Count == 0)
                {
                    throw new ParseException(string.Empty, 0, "- 기호 이외엔 괄호앞에 사용 할 수 없습니다.");
                }
                // -(-) 일 경우도 생각
                Operator op = LastElement as Operator;
                if (op != null && ((Operator)item).IsSign == false)
                {
                    throw new ParseException(Root.ToString(), 0, "연속된 연산자는 유효하지 않습니다.");
                }
                if (OperatorCount >= 2)
                {
                    throw new ParseException(Root.ToString(), 0, "연속된 연산자는 유효하지 않습니다.");
                }
                Stack.Add(item);
                return(item);
            }
            if (item is CompareOperator)
            {
                Stack.Add(item);
                return(item);
            }
            return(null);
        }
Exemplo n.º 21
0
    private Stack BuildStackFromStackMeta(StackMeta stackMeta, PrefabsManager prefabsManager)
    {
        Stack stack = prefabsManager.CreateStack();

        for (int i = 0; i < stackMeta.ChipCount(); i++)
        {
            int  prefabId = stackMeta.GetChipMetaAt(i).prefabId;
            Chip chip     = prefabsManager.GetChip(prefabId);
            stack.Add(chip);
            chip.chipMeta.CrushWeight = stackMeta.GetChipMetaAt(i).CrushWeight;
            if (chip.chipMeta.orientation != stackMeta.GetChipMetaAt(i).orientation)
            {
                chip.chipMeta.Flip();
                chip.transform.localRotation = Quaternion.Euler(180f, 0f, 0f);
            }
        }
        return(stack);
    }
Exemplo n.º 22
0
        static void Main(string[] args)
        {
            Stack s = new Stack();

            s.Add(1);
            s.Add(2);
            s.Add(3);
            s.Add(4);
            s.Remove();
            s.Add(5);
            s.Add(6);
            s.Remove();
        }
Exemplo n.º 23
0
        /// <summary>
        /// Depth-first (post-order) search through the tree, recording the stack state as the
        /// lineage every time a terminal is reached.
        /// </summary>
        /// <remarks>
        /// Depth-first (post-order) search through the tree, recording the stack state as the
        /// lineage every time a terminal is reached.
        /// This implementation uses the Index annotation to store depth. If CoreLabels are
        /// not present in the trees (or at least something that implements HasIndex), an exception will result.
        /// </remarks>
        /// <param name="t">The tree</param>
        /// <returns>A list of lineages</returns>
        private static IList <IList <CoreLabel> > MakeLineages(Tree t)
        {
            if (t == null)
            {
                return(null);
            }
            ((IHasIndex)t.Label()).SetIndex(0);
            Stack <Tree> treeStack = new Stack <Tree>();

            treeStack.Push(t);
            Stack <CoreLabel> labelStack = new Stack <CoreLabel>();
            CoreLabel         rootLabel  = new CoreLabel(t.Label());

            rootLabel.SetIndex(0);
            labelStack.Push(rootLabel);
            IList <IList <CoreLabel> > lineages = new List <IList <CoreLabel> >();

            while (!treeStack.IsEmpty())
            {
                Tree node      = treeStack.Pop();
                int  nodeDepth = ((IHasIndex)node.Label()).Index();
                while (!labelStack.IsEmpty() && labelStack.Peek().Index() != nodeDepth - 1)
                {
                    labelStack.Pop();
                }
                if (node.IsPreTerminal())
                {
                    IList <CoreLabel> lin = new List <CoreLabel>(labelStack);
                    lineages.Add(lin);
                }
                else
                {
                    foreach (Tree kid in node.Children())
                    {
                        ((IHasIndex)kid.Label()).SetIndex(nodeDepth + 1);
                        treeStack.Push(kid);
                    }
                    CoreLabel nodeLabel = new CoreLabel(node.Label());
                    nodeLabel.SetIndex(nodeDepth);
                    labelStack.Add(nodeLabel);
                }
            }
            return(lineages);
        }
Exemplo n.º 24
0
        //the CheckStacks method checks the stacks and adds a container if possible
        public void CheckStacksTestTrue()
        {
            //arrange
            Ship ship = new Ship(1, 1, 1, 10000);

            ship.Rows.Clear();
            Row       row        = new Row(true);
            Stack     stack      = new Stack(2);
            Container container  = new Container(100, Normal);
            Container container2 = new Container(100, Normal);

            //act
            stack.Add(container);
            row.Add(stack);
            ship.Rows.Add(row);
            //assert
            Assert.IsTrue(row.CheckStacks(container2, ship));
            Assert.AreEqual(2, row[0].Count);
        }
Exemplo n.º 25
0
 public AstNode Transform(AstNode start, bool inList = false)
 {
     Stack.Add(start);
     try
     {
         var x = Before(start, inList);
         if (x != null)
         {
             return(x);
         }
         start.Transform(this);
         x = After(start, inList);
         return(x ?? start);
     }
     finally
     {
         Stack.Pop();
     }
 }
        // Balances this tree
        public virtual IntervalTree.TreeNode <E, T> Balance(IntervalTree.TreeNode <E, T> node)
        {
            Stack <IntervalTree.TreeNode <E, T> > todo = new Stack <IntervalTree.TreeNode <E, T> >();

            todo.Add(node);
            IntervalTree.TreeNode <E, T> newRoot = null;
            while (!todo.IsEmpty())
            {
                IntervalTree.TreeNode <E, T> n = todo.Pop();
                // Balance tree between this node
                // Select median nodes and try to balance the tree
                int medianAt = n.size / 2;
                IntervalTree.TreeNode <E, T> median = GetNode(n, medianAt);
                // Okay, this is going to be our root
                if (median != null && median != n)
                {
                    // Yes, there is indeed something to be done
                    RotateUp(median, n);
                }
                if (newRoot == null)
                {
                    newRoot = median;
                }
                if (median.left != null)
                {
                    todo.Push(median.left);
                }
                if (median.right != null)
                {
                    todo.Push(median.right);
                }
            }
            if (newRoot == null)
            {
                return(node);
            }
            else
            {
                return(newRoot);
            }
        }
Exemplo n.º 27
0
        static void SolvePuzzle(bool IsGreedy, bool print = false)
        {
            //int[] board = { 5, 0, 2, 6, 3, 4, 8, 1, 7 };
            ;           var gb = new GameBoard(3, 3);

            var solution = PuzzleSolver.A_Star_Search(gb, IsGreedy);

            if (solution == null && print)
            {
                Console.WriteLine("Could not find a solution!");
                return;
            }

            Stack <NodePath <GameBoard> > stk = new Stack <NodePath <GameBoard> >();

            while (solution != null)
            {
                stk.Add(solution);
                solution = solution.Parent;
            }

            if (!print)
            {
                return;
            }

            var sb = new StringBuilder();

            while (!stk.IsEmpty())
            {
                var top = stk.Pop().Node;
                if (print)
                {
                    sb.Append(top.GetValue().MoveInformation).AppendLine();
                    sb.Append(top.GetValue()).AppendLine();
                }
            }

            Console.WriteLine(sb);
        }
Exemplo n.º 28
0
        private static int checkFinishedTrace(int traces, NodePath <VectorizeState> top, VectorizeState top_state, string[][] transitions)
        {
            for (int ar = 0; ar < transitions.Length; ar++)
            {
                if (top_state.States[ar] < transitions[ar].Length)
                {
                    return(traces);
                }
            }

            var stk = new Stack <NodePath <VectorizeState> >();

            NodePath <VectorizeState> ptr = top;

            while (ptr != null)
            {
                stk.Add(ptr);

                ptr = ptr.Parent;
            }

            Console.Write("Trace {0}: ", ++traces);

            while (!stk.IsEmpty())
            {
                var here = stk.Pop();
                if (here.Parent != null)
                {
                    var msg = ((FSM_Node <VectorizeState>)here.Parent.Node).GetMessage((FSM_Node <VectorizeState>)here.Node);
                    Console.Write(msg);
                    if (!stk.IsEmpty())
                    {
                        Console.Write(" -> ");
                    }
                }
            }
            Console.WriteLine();

            return(traces);
        }
Exemplo n.º 29
0
        public void Walk(AstNode?start)
        {
            if (start == null)
            {
                return;
            }
            Stack.Add(start);
            var backupStopDescending = _stopDescending;

            try
            {
                _stopDescending = false;
                Visit(start);
                if (!_stopDescending)
                {
                    Descend();
                }
            }
            finally
            {
                _stopDescending = backupStopDescending;
                Stack.Pop();
            }
        }
Exemplo n.º 30
0
        public override void startElement(string name, IDictionary <string, string> attributes)
        {
            if (MucElementNames.DOC_ELEMENT.Equals(name))
            {
                isClearAdaptiveData = true;
            }

            if (MucElementNames.CONTENT_ELEMENTS.Contains(name))
            {
                isInsideContentElement = true;
            }

            if (NAME_ELEMENT_NAMES.Contains(name))
            {
                string nameType = attributes["TYPE"];

                if (!EXPECTED_TYPES.Contains(nameType))
                {
                    throw new InvalidFormatException("Unknown timex, numex or namex type: " + nameType + ", expected one of " + EXPECTED_TYPES);
                }

                incompleteNames.Add(new Span(text.Count, text.Count, nameType.ToLower(Locale.ENGLISH)));
            }
        }
Exemplo n.º 31
0
        public void TestStack()
        {
            Stack <Int32> stack = new Stack <int>();

            stack.Add(0);
            stack.Add(1);
            stack.Add(2);
            stack.Add(3);
            stack.Add(4);
            stack.Add(5);

            Int32 integer;

            integer = stack.Take();
            integer = stack.Take();
            integer = stack.Take();
            integer = stack.Take();
            integer = stack.Take();
            integer = stack.Take();
        }
Exemplo n.º 32
0
        public static void Run(string input)
        {
            //add base classes to stack                 parents:
            mainstack.classes.Add("void", new Void());                //no
            mainstack.classes.Add("byte", new wolByte());             //void
            mainstack.classes.Add("short", new wolShort());           //byte
            mainstack.classes.Add("string", new wolString());         //void
            mainstack.classes.Add("int", new wolInt());               //short
            mainstack.classes.Add("float", new wolFloat());           //int
            mainstack.classes.Add("long", new wolLong());             //int
            mainstack.classes.Add("double", new wolDouble());         //float
            mainstack.classes.Add("Type", new wolType());             //void
            mainstack.classes.Add("Func", new wolFunc());             //void
            mainstack.classes.Add("Enum", new wolEnum());             //void
            mainstack.classes.Add("char", new wolChar());             //void
            mainstack.classes.Add("Block", new wolBlock());           //void
            mainstack.classes.Add("Collection", new wolCollection()); //void
            mainstack.classes.Add("Array", new wolArray());           //Collection
            mainstack.classes.Add("Link", new wolLink());             //void
            mainstack.classes.Add("bool", new wolBool());             //void

            //main cycle
            position = 0;
            char current = input[0];
            int  time    = Environment.TickCount;

            while (position < input.Length)
            {
                while (char.IsWhiteSpace(current)) //skip whitespaces
                {
                    position++;
                    if (position > input.Length)
                    {
                        ThrowVMException("Build-file have only whitespaces", position, ExceptionType.BLDSyntaxException);
                        return;
                    }
                    current = input[position];
                }
                StringBuilder buffer = new StringBuilder();
                while (!char.IsWhiteSpace(current)) //get word
                {
                    buffer.Append(current);
                    position++;
                    try
                    {
                        current = input[position];
                    }
                    catch (IndexOutOfRangeException)
                    {
                        ThrowVMException("Build-file have only one word", position, ExceptionType.BLDSyntaxException);
                        return;
                    }
                }
                if (buffer.ToString() == "_loads")
                {
                    buffer.Clear();
                    while (char.IsWhiteSpace(current))
                    {
                        position++;
                        if (position > input.Length)
                        {
                            ThrowVMException("Start of loads struct not found", position, ExceptionType.BLDSyntaxException);
                            return;
                        }
                        current = input[position];
                    }
                    if (current == '{')
                    {
                        buffer.Clear();
                        while (current != '}') //get loads body
                        {
                            buffer.Append(current);
                            position++;
                            if (position > input.Length)
                            {
                                ThrowVMException("End of loads struct not found", position, ExceptionType.BLDSyntaxException);
                                return;
                            }
                            current = input[position];
                        }
                        buffer.Remove(0, 1);
                        //start parse loads
                        string        dllSource = buffer.ToString();
                        Type          mainType  = typeof(VMLibrary);
                        List <string> dllNames  = dllSource.Split(';').ToList();
                        foreach (string dllName in dllNames)
                        {
                            Assembly assembly  = null;
                            string   full_path = AppDomain.CurrentDomain.BaseDirectory + dllName.Trim() + ".dll";
                            try
                            {
                                assembly = Assembly.LoadFrom(full_path);
                            }
                            catch (Exception ex)
                            {
                                ThrowVMException($"Library with info {full_path} not found.\n{ex.Message}", position, ExceptionType.FileNotFoundException);
                                break;
                            }
                            Type mainClass = assembly.GetTypes().FirstOrDefault(t => t != mainType && mainType.IsAssignableFrom(t));
                            if (test)
                            {
                                Console.WriteLine("Framework Info: " + assembly);
                                Console.WriteLine("Full path to framework: " + full_path);
                                Console.WriteLine(string.Join <Type>(' ', assembly.GetTypes()));
                            }
                            if (mainClass != null)
                            {
                                if (Activator.CreateInstance(mainClass) is VMLibrary mainObj)
                                {
                                    mainObj.Load();
                                }
                                else
                                {
                                    ThrowVMException($"Main class in library by name {dllName} haven`t type VMLibrary and will cannot loaded", position, ExceptionType.LoadsException);
                                }
                            }
                            else
                            {
                                ThrowVMException($"Library by name {dllName} haven`t main class and will cannot loaded", position, ExceptionType.LoadsException);
                            }
                        }
                        //end parse loads
                    }
                    else
                    {
                        ThrowVMException("Start of loads struct not found", position, ExceptionType.BLDSyntaxException);
                    }
                }
                else if (buffer.ToString() == "stack")
                {
                    buffer.Clear();
                    while (char.IsWhiteSpace(current))
                    {
                        position++;
                        if (position > input.Length)
                        {
                            ThrowVMException("Start of stack not found", position, ExceptionType.BLDSyntaxException);
                            return;
                        }
                        current = input[position];
                    }
                    if (current == '{')
                    {
                        cycle : while (current != '}') //get stack body
                        {
                            buffer.Append(current);
                            position++;
                            if (position > input.Length)
                            {
                                ThrowVMException("End of stack not found", position, ExceptionType.BLDSyntaxException);
                                return;
                            }
                            current = input[position];
                        }
                        if (input[++position] == ';')
                        {
                            buffer.Append(current);
                            current = input[position];
                            goto cycle;
                        }
                        mainstack.Add(Stack.Parse(buffer.ToString().Trim()));
                    }
                    else
                    {
                        ThrowVMException("Start of stack not found", position, ExceptionType.BLDSyntaxException);
                    }
                    position--;
                }
                else if (buffer.ToString() == "main")
                {
                    buffer.Clear();
                    while (char.IsWhiteSpace(current))
                    {
                        position++;
                        if (position > input.Length)
                        {
                            ThrowVMException("Start of script not found", position, ExceptionType.BLDSyntaxException);
                            return;
                        }
                        current = input[position];
                    }
                    if (current == '{')
                    {
                        while (current != '}') //get script
                        {
                            buffer.Append(current);
                            position++;
                            if (position > input.Length)
                            {
                                ThrowVMException("End of script not found", position, ExceptionType.BLDSyntaxException);
                                return;
                            }
                            current = input[position];
                        }
                        Script.Parse(buffer.ToString().Trim().Remove(0, 1));
                    }
                    else
                    {
                        ThrowVMException("Start of script not found", position, ExceptionType.BLDSyntaxException);
                    }
                }
                else if (buffer.ToString() == "end")
                {
                    if (test)
                    {
                        //test stack
                        Console.WriteLine("Info about program in the end.\nMain stack:");
                        Console.WriteLine(mainstack.ToString());
                        Console.WriteLine("Expressions:");
                        foreach (string expr_name in expressions.Keys)
                        {
                            Console.WriteLine(expr_name);
                        }
                        Console.WriteLine($"Time of program: {Environment.TickCount - time}");
                    }
                    return;
                }
                else if (buffer.ToString() == "}")
                {
                    position++;
                    continue;
                }
                else
                {
                    ThrowVMException($"Unknown keyword {buffer.ToString()}", position, ExceptionType.BLDSyntaxException);
                }
            }
        }
Exemplo n.º 33
0
 public void Push(StackValue data)
 {
     Stack.Add(data);
 }
Exemplo n.º 34
0
        private void LoadStack(XmlReader reader, Stack stack)
        {
            if (reader.IsEmptyElement)
            {
                reader.Read();
                return;
            }

            while (!reader.EOF && reader.NodeType != XmlNodeType.EndElement)
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        var unit = _unitFactory[reader.Name]();
                        if (reader.MoveToFirstAttribute())
                        {
                            for (; ; )
                            {
                                int value;
                                if (Int32.TryParse(reader.Value, out value))
                                {
                                    unit = _unitDecorator[reader.Name](unit, value);
                                }
                                if (!reader.MoveToNextAttribute())
                                    break;
                            }
                            reader.MoveToElement();
                        }

                        stack.Add(unit);
                        break;
                }

                reader.Read();
            }
        }
Exemplo n.º 35
0
    public void Find(PathRequest request, Action <Result> retrive)
    {
        Vector3[] waypoints  = new Vector3[0];
        bool      pathSucces = false;

        Node startNode = grid.NodeFromWorldPoint(request.start);
        Node endNode   = grid.NodeFromWorldPoint(request.end);

        if (startNode.walkable && endNode.walkable)
        {
            Stack <Node>   setOpen  = new Stack <Node>(grid.GridSize);
            HashSet <Node> setClose = new HashSet <Node>();
            setOpen.Add(startNode);

            while (setOpen.Count > 0)
            {
                Node currNode = setOpen.Delete();



                setClose.Add(currNode);

                if (currNode == endNode)
                {
                    pathSucces = true;
                    break;
                }

                foreach (Node n in grid.Neighbours(currNode))
                {
                    if (!n.walkable || setClose.Contains(n))
                    {
                        continue;
                    }

                    int newCost = currNode.costA + Distance(currNode, n);
                    if (newCost < n.costA || !setOpen.Includes(n))
                    {
                        n.costA = newCost;
                        n.costB = Distance(n, endNode);
                        n.root  = currNode;

                        if (!setOpen.Includes(n))
                        {
                            setOpen.Add(n);
                        }
                        else
                        {
                            setOpen.Update(n);
                        }
                    }
                }
            }
        }



        if (pathSucces)
        {
            waypoints  = ExtractPath(startNode, endNode);
            pathSucces = waypoints.Length > 0;
        }
        retrive(new Result(waypoints, pathSucces, request.retrive));
    }
Exemplo n.º 36
0
        // Metoda, ve které se uskutečňuje pohyb agenta po hracím poli
        public void PohybujSe(int pocetBehu)
        {
            for (int b = 0; b < pocetBehu; b++)
            {
                // Pomocné pole pro uložení výsledku posunu agenta ve třídě POZICE
                int[] report_pomocna = new int[4];
                // Do tohoto pole si uložím možné směry agenta, které zjišťuji v metodě expandujVrcholy
                int[] expanduj_pomocna = ExpandujVrcholy(agent.AktPozice[0], agent.AktPozice[1]);
                // Směr je nejprve na sever, protože směry v expanduj_pomocna jsou uloženy od severu
                int smer = 0;
                // Projdu všechny směry v expanduj_pomocna
                foreach (int i in expanduj_pomocna)
                {
                    // Pokud je dany smer povoleny, tedy -- 1, tak se vytvori nova POZICE s hodnotami tohoto policka
                    if (i == 1)
                    {
                        // Prozkoumám pozici daným směrem a získám report se vším potřebným pro vytvoření této pozice
                        report_pomocna = agent.Pohyb(smer);
                        // Výpočet heuristické funkce pro danou pozici
                        // Vstupem je X -- Y -- aktuální cena cesty
                        int celkovaCena = HeuristickaFunkce(report_pomocna[1], report_pomocna[2], report_pomocna[0]);
                        // Přidání nalezené pozice do NEXT, tedy budoucích pozicí, kam je možné jít
                        Next.Add(new Pozice(IDVrcholu, report_pomocna[0], report_pomocna[1], report_pomocna[2], report_pomocna[3], celkovaCena));
                        // Zvýším ID, aby další vrchol měl jedičné
                        IDVrcholu++;
                        // Porovnám pozice v NEXT podle celkové ceny cesty SESTUPNE
                        IEnumerable <Pozice> zalozni = Next.OrderBy(a => a.CelkovaCenaCesty);
                        Next = new List <Pozice>();
                        // Porovnanou kolekci si uložím z5 do původní, tedy do NEXT
                        foreach (Pozice p in zalozni)
                        {
                            Next.Add(p);
                        }
                    }
                    // Zvýším proměnnou směr, čímž půjdu na směr posunutý o 90°
                    smer++;
                }
                // Do prozkoumaných pozic ve STACK si uložím současnou pozici agenta, tedy poslední prozkoumanou
                Stack.Add(agent);
                // Vezmu první pozici v NEXT, tedy ta s nejnižší celkovou cenou cesty
                agent = Next[0];
                // Kontrola zda tato nová pozice, která se bude při dalším běhu této metody prozkoumávat není výherní
                if (Vyhra(agent.AktPozice[0], agent.AktPozice[1], b))
                {
                    break;
                }
                // Vykreslím hrací pole, kde pozici agenta znázorňuje prázdná pozice
                ZobrazHraciPole(agent.AktPozice[0], agent.AktPozice[1]);
                // Smažu pozici, kterou jsem si uložil do agenta z NEXT
                Next.RemoveAt(0);
            }

            Console.WriteLine("\n---------------STACK-----------------\n|X      |Y      |AktCena|CelkCena");
            foreach (Pozice p in Stack)
            {
                Console.WriteLine(p);
            }

            Console.WriteLine("\n---------------NEXT-----------------\n|X      |Y      |AktCena|CelkCena");
            foreach (Pozice p in Next)
            {
                Console.WriteLine(p);
            }

            Console.WriteLine("\n---------------AGENT-----------------\n|X      |Y      |AktCena|CelkCena");
            Console.WriteLine(agent);
        }