Beispiel #1
0
 public static Stack<int> MakeContainerFromList(LinkedList<int> a)
 {
     Stack<int> newStack = new Stack<int>();
     foreach (int value in a)
         newStack.Push(value);
     return newStack;
 }
        public IGrid<Cell> On(IGrid<Cell> grid, Cell startAt = null)
        {
            if (startAt == null)
            {
                startAt = grid.RandomCell();
            }

            var stack = new Stack<Cell>();
            stack.Push(startAt);

            while (stack.Count != 0)
            {
                var current = stack.Peek();
                var neighbours = current.Neighbours().Where(n => n.Links.Count == 0).ToList();
                if (neighbours.Count == 0)
                {
                    stack.Pop();
                }
                else
                {
                    var neighbour = neighbours[rand.Next(neighbours.Count)];
                    current.Link(neighbour);
                    stack.Push(neighbour);
                }


            }

            return grid;
        }
Beispiel #3
0
        static void Main(string[] args)
        {
            doubleStack = new Stack<double>(5);
            intStack = new Stack<int>(10);

            TestPushDouble();
            TestPopDoubel();
            TestPushInt();
            TestPopInt();
        }
Beispiel #4
0
 public static void PrintContainer(Stack<int> a)
 {
     a.Reverse();
     int count = 0;
     Console.WriteLine();
     while (count < 100)
     {
         Console.Write(a.Pop() + " ");
         count++;
     }
 }
Beispiel #5
0
        /// <summary>
        /// Encode the given number into a Base36 string
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public static String Encode(long input)
        {
            if (input < 0) throw new ArgumentOutOfRangeException("input", input, "input cannot be negative");

            if (input == 0)
            {
                return "0";
            }

            char[] clistarr = CharList.ToCharArray();
            var result = new Stack<char>();
            while (input != 0)
            {
                result.Push(clistarr[input % 36]);
                input /= 36;
            }
            return new string(result.ToArray());
        }
Beispiel #6
0
        public static string transposition(string expression)
        {
            StringBuilder sb = new StringBuilder();
            Stack<char> stack = new Stack<char>();
            char s;

            for (int i = 0; i < expression.Length; i++)
            {
                if (expression[i] == '(')
                {
                    stack.Push(expression[i]);
                }
                else if (expression[i] == ')')
                {
                    while (0 < stack.Count)
                    {
                        s = stack.Pop();
                        if (s != '(')
                        {
                            sb.Append(s);
                        }
                        else break;
                    }
                }
                else if (expression[i] == '^')
                {
                    stack.Push(expression[i]);
                }
                else if ((expression[i] == '*') || (expression[i] == '/'))
                {
                    stack.Push(expression[i]);
                }
                else if ((expression[i] == '+') || (expression[i] == '-'))
                {
                    stack.Push(expression[i]);
                }
                else
                {
                    sb.Append(expression[i]);
                }
            }

            return sb.ToString();
        }
        public static IEnumerable<Segment> Parse(string s)
        {
            var segments = new List<Segment>();

            var stack = new Stack<Tuple<int, Segment>>();

            var lines = s.Split('\n');

            foreach (var line in lines)
            {
                var match = Regex.Match(line, @"^(\s*)(.*)$");
                var whiteSpace = match.Result("$1").Replace("\t", "    ");
                var text = match.Result("$2");

                if (string.IsNullOrWhiteSpace(text))
                {
                    //stack.Clear();
                    continue;
                }

                var segment = new Segment(text.Trim());

                var indent = whiteSpace.Length;

                if (stack.Any())
                {
                    while (stack.Any() && stack.Peek().Item1 >= indent)
                        stack.Pop();
                    if (stack.Any())
                        stack.Peek().Item2.Add(segment);
                }

                if (stack.Any() == false)
                    segments.Add(segment);
                stack.Push(Tuple.Create(indent, segment));
            }

            return segments;
        }
Beispiel #8
0
 static bool doit(byte[,] matrix)
 {
     bool isWinner = true;
     Stack<byte> stek = new Stack<byte>();
     int columnLenght = matrix.GetLength(0);
     for (int j=0;j<matrix.GetLength(1) ;j++ )
     {
         for (int i = 0; i < columnLenght; i++)
         {
             if(matrix[i,j]!=0)
             {
                 isWinner = false;
                 stek.Push(matrix[i, j]);
             }
         }
         for (int k = columnLenght-1; (k >= 0); k--)
         {
             try
             {
                 matrix[k, j] = stek.Pop();
             }
             catch (Exception)
             {
                 matrix[k, j] = 0;
             }
         }
     }
         return isWinner;
 }
        static bool CheckFriendConnectionDFS(string name1, string name2, SocialNetwork sn)
        {
            Stack<Panda> q = new Stack<Panda>();
            HashSet<Panda> visited = new HashSet<Panda>();

            q.Push(sn[name1]);
            visited.Add(sn[name1]);

            Console.WriteLine("Starting from " + name1);
            while (q.Count > 0)
            {
                Panda current = q.Pop();
                Console.WriteLine("Currently at " + current.Name);
                foreach (Panda friend in current.Friends)
                {
                    if (friend.Name == name2)
                    {
                        return true;
                    }

                    if (!visited.Contains(friend))
                    {
                        Console.WriteLine("Added friend " + friend.Name);
                        q.Push(friend);
                        visited.Add(friend);
                    }
                }
            }

            return false;
        }
 public Weapon()
 {
     max = 7;
     cont = 0;
     holder = new Stack<Bullet>();
     tmpB = new Bullet();
 }
Beispiel #11
0
 static void Main()
 {
     Stack stack = new Stack();
     stack.Push(1);
     stack.Push(2);
     stack.Push(3);
     stack.Pop();
     Console.WriteLine(stack.Count+ " " + stack.Contains(1));
     stack.PrintStack();
     Console.WriteLine("Top element:"+stack.Peek());
     Console.WriteLine("**************************");
     Stack<int> stack1 = new Stack<int>();
     stack1.Push(1);
     stack1.Push(2);
     stack1.Push(3);
     stack1.Pop();
     Console.WriteLine(stack1.Count + " " + stack1.Contains(1));
     foreach (int i in stack1)
     {
         Console.WriteLine(i);
     }
     Console.WriteLine("Top element:"+stack1.Peek());
 }
 static void Main(string[] args)
 {
     Stack<int> L=new Stack<int>();
     Stack<int> L1 = new Stack<int>();
     Stack<int> L2= new Stack<int>();
     Random r = new Random();
     Console.WriteLine("Заполняем стэки одновременно, нажатие enter приведет к завершению заполнения ");
     ConsoleKeyInfo key;
     do
     {
         Console.WriteLine("еще?");
         key = Console.ReadKey();
         L1.Push(r.Next(-10, 10)); L2.Push(r.Next(-10, 10));
     }
     while (ConsoleKey.Enter != key.Key);
     Console.WriteLine("1 стэк");
     foreach(int z in L1)
         Console.WriteLine(z);
     Console.WriteLine("2 стэк");
     foreach (int z in L2)
         Console.WriteLine(z);
     int srav = 0;
     for (int i = 0; i < L1.Count; i++)
     {
         for (int j = 0; j < L2.Count; j++)
             if (L1.[i] == L2.[j]||L1.[i] == L1.[j]) {break; }
Beispiel #13
0
        public void DFS(List<DirectedNode> nodelist, int goalNodeid)
        {
            Stack<DirectedNode> stack = new Stack<DirectedNode>();
            stack.Push(nodelist[0]);
            DirectedNode frontiernode;
            int[] adjlist;

            while (stack.Count() != 0)
            {
                frontiernode = stack.Pop();
                adjlist = frontiernode.adjnodes;

                if (adjlist == null) { continue; }

                foreach (int i in adjlist)
                {
                    stack.Push(nodelist[i]);

                    node previousnode = nodelist[nodelist[i].PreviousNodeid];
                    float edgeweight = ConsoleApplication1.Driver.distance(frontiernode, nodelist[i]);
                    float newdistance = frontiernode.ShortestDistanceTo + edgeweight;

                    if (nodelist[i].ShortestDistanceTo == 0)
                    {
                        nodelist[i].ShortestDistanceTo = newdistance;
                        nodelist[i].PreviousNodeid = frontiernode.id;
                    }
                    else if (newdistance < nodelist[i].ShortestDistanceTo)
                    {
                        nodelist[i].ShortestDistanceTo = newdistance;
                        nodelist[i].PreviousNodeid = frontiernode.id;
                    }
                    else { }
                }
            }
            int prevNodeId = goalNodeid - 1;
            Console.Write("Path: " + prevNodeId);
            while (prevNodeId != 0)
            {
                Console.Write(" <- " + nodelist[prevNodeId].PreviousNodeid);
                prevNodeId = nodelist[prevNodeId].PreviousNodeid;
            }
            Console.Write("\nDistance: " + nodelist[goalNodeid - 1].ShortestDistanceTo);
        }
        private static void Main(string[] args)
        {
            // sum of numbers taken fom array input and splited by " "

            string arrString = Console.ReadLine();

            string[] items = arrString.Split(new char[] {' '},   // removes empty entries,
                StringSplitOptions.RemoveEmptyEntries);         // EX: if there are two spaces instead of one between the numbers

            int[] numbers = new int[items.Length];

            for (int i = 0; i < numbers.Length; i++)
            {
                numbers[i] = int.Parse(items[i]);
            }

            Console.WriteLine(numbers.Sum());

            // ================== how to output string: they are 3 ways - for loop, foreach loop and Join method

                string [] strings = new string[]
                {
                    "First string",
                    "Second string",
                    "Varna"
                };

            // first way
            //for (int i = 0; i < strings.Length; i++)
            //{
            //    Console.WriteLine(strings[i]);
            //}

            //second way
            //foreach (var s in strings)
            //{
            //    Console.WriteLine(s);
            //}

            //third way
            string str = string.Join(",", strings);
            Console.WriteLine(str);

               //================== find squares of array of numbers (squeare for each number)

            int[] array = {2, 3, 4};
            int[] squares = new int[array.Length];

            for (int i = 0; i < array.Length; i++)
            {
                squares[i] = array[i]*array[i];
            }

            Console.WriteLine(string.Join(",", squares));

            //================ array of anonomouis objects

            var arr = new[]
            {
                new { Name="Pesho", age=15},
                new { Name="Gosho", age=22},
                new { Name="Maria", age=18}
            };

            foreach (var item in arr)
            {
                Console.WriteLine(item);
            }

            //=======================Lists====

               // object lists or anonomys list

            List<object> list = new List<object>
            {
                "Pesho",
                "Gosho",
                "Maria",
                5,
                new DateTime(2015, 1, 1)

            };

            //print it on the console - functional way
                list.ForEach(i => Console.WriteLine(i));

            //add range

            List<int> intItems = new List<int>();
            intItems.AddRange(new int[]{4,5,6});

            //index of
            Console.WriteLine(intItems.IndexOf(5)); // show on which postions we have the int '5'

            // count how many '5' we have in the list - functional way
            Console.WriteLine(intItems.Count(p=> p==5));

            //count how many '5' we have in the list with loop

            int count = 0;
            int startIndex = -1;
            while (true)
            {
                startIndex = intItems.IndexOf(4, startIndex + 1);
                if (startIndex == -1)
                {
                    break;
                }
                count++;
            }

            // reverse the list

            intItems.Reverse();

            ////////min max sum (list)

            List<int> lista = new List<int>() {3,4,5};
            Console.WriteLine("Sum = {0}", lista.Sum());
            Console.WriteLine("Min = {0}", lista.Min());
            Console.WriteLine("Max = {0}", lista.Max());

            Console.WriteLine(lista.Skip(2).FirstOrDefault()); // sskip number on the second position

            // Distinct()  -removes the ones that repeat

            //========================Stack==============

            //stack keeps all the added items in the opposite order:

            Stack<string> stack = new Stack<string>();
                stack.Push("Възглавничка синя");
                stack.Push("одеало");
                stack.Push("зелен чаршав");
                stack.Push("голяма възглавница");

            while (stack.Count > 0)
            {
                Console.WriteLine(stack.Pop());
            }
                //output will be:
                    //голяма възглавница
                    //зелен чаршав
                    //одеало...
        }
Beispiel #15
0
 public void Init()
 {
     stack = new Stack<string>();
 }
Beispiel #16
0
        public void ThirdConstructorTest()
        {
            List<int> l = new List<int>() {1, 2, 3};
            Stack<int> ss = new Stack<int>(l);

            Assert.That(ss.Pop(), Is.EqualTo(3));
            Assert.That(ss.Pop(), Is.EqualTo(2));
            Assert.That(ss.Pop(), Is.EqualTo(1));
        }