// SOL

        private static void BinarySearchSqrt(int x, InOut.Ergebnis erg)
        {
            int    it = 0;
            double low = 0, high = x, mid;

            while (true)
            {
                it++;
                mid = (high + low) / 2;
                int comp = (mid * mid).CompareTo(x);
                if (comp > 0)
                {
                    high = mid;
                }
                else if (comp < 0)
                {
                    low = mid;
                }
                else
                {
                    break;
                }
            }
            erg.Setze(mid, it, Complexity.LOGARITHMIC, Complexity.CONSTANT);
        }
Beispiel #2
0
        private static void ZigZagConvert2(Input testcase, InOut.Ergebnis erg)
        {
            string        input     = testcase.input;
            int           rows      = testcase.rows;
            StringBuilder converted = new StringBuilder();

            // Down n - 1
            // Lücke n - 2
            // + 1
            // next Element
            int distanceToNextElement = 2 * rows - 2;         // down + Lücke + 1

            for (int row = 0; row < rows; row++)
            {
                int ZagDistance = (rows - 1 - row) * 2; // Diagonal Element in same Row:
                for (int i = row; i < input.Length; i += distanceToNextElement)
                {
                    converted.Append(input[i]);
                    if (row != 0 && row != rows - 1 && i + ZagDistance < input.Length)
                    {
                        converted.Append(input[i + ZagDistance]);
                    }
                }
            }


            erg.Setze(converted.ToString());
        }
        //SOL
        public static void GetMinimumRemovals(string parent, InOut.Ergebnis erg)
        {
            Stack <char> st     = new Stack <char>();
            int          remove = 0;

            foreach (char c in parent)
            {
                if (c == ')')
                {
                    if (st.Count == 0 || st.Peek() != '(')
                    {
                        remove++;
                    }
                    else
                    {
                        st.Pop();
                    }
                }
                else if (c == '(')
                {
                    st.Push(c);
                }
                else
                {
                    throw new Exception(c + " is not a Parenthesis");
                }
            }

            erg.Setze(remove + st.Count, Complexity.LINEAR, Complexity.LINEAR);
        }
Beispiel #4
0
        //SOl
        private static void SolveRecursive(int[] arr, InOut.Ergebnis erg)
        {
            IBTree <int> tree = new BinarySearchTree <int>();

            AddMiddle(arr, 0, arr.Length - 1, tree);
            erg.Setze(tree);
        }
        /* SOL 1
         *
         * Find first lowest Boundary from left and right
         * scan inbetween boundarys and subtract lowest boundary from all elements
         * redo until all el < 0
         * final sweep add all sub 0 vals
         */
        private static void SolveBoundaryScan(int[] arr, InOut.Ergebnis erg)
        {
            int nextBr = arr.Length - 1, nextBl = 0;       //Indexes!!
            int bRight = arr[nextBr], bLeft = arr[nextBl]; //Vals
            int nextBrtmp = nextBr;

            do
            {
                for (int i = nextBl; i < nextBrtmp; i++)
                {
                    arr[i] -= Math.Min(bRight, bLeft);
                    if (arr[nextBl] <= 0 && arr[i] > 0)
                    {
                        nextBl = i;
                    }
                    if (arr[nextBrtmp] <= 0 && arr[i] > 0)
                    {
                        nextBr = i;
                    }
                }
                bRight          = arr[nextBr];
                bLeft           = arr[nextBl];
                nextBrtmp       = nextBr;
                arr[nextBrtmp] -= Math.Min(bLeft, bRight);
            } while (bRight > 0 && bLeft > 0);

            //final sweep
            int sum = 0;

            for (int i = 0; i < arr.Length; i++)
            {
                sum -= Math.Min(arr[i], 0);
            }
            erg.Setze(sum, Complexity.QUADRATIC, Complexity.CONSTANT);
        }
Beispiel #6
0
        private static void Solve(Input inp, InOut.Ergebnis erg)
        {
            string s   = ConvertToBase(inp.z, inp.b);
            int    num = ConvertFromBase(s, inp.b);

            erg.Setze(new Output(s, num));
        }
        //SOL
        public static void FindContigousSubarray(int[] arr, InOut.Ergebnis erg)
        {
            int maxSum = 0, sum = 0;
            List<int> maxSubArray = null;
            List<int> subArray = new List<int>();
            for(int i=0; i<arr.Length; i++)
            {
                if (sum + arr[i] > 0)
                {
                    sum += arr[i];
                    subArray.Add(arr[i]);
                } else
                {
                    if(sum > maxSum)
                    {
                        maxSubArray = subArray;
                        maxSum = sum;
                    }
                    subArray = new List<int>();
                    sum = 0;
                }
            }

            if (sum > maxSum)
            {
                maxSubArray = subArray;
                maxSum = sum;
            }
            erg.Setze(new Output(maxSubArray.ToArray(), maxSum), Complexity.LINEAR, Complexity.LINEAR);
        }
Beispiel #8
0
        // OPT 3 Idea: All Right Nodes are Subtrees of the Left

        private static void Counting_Subtrees(int n, InOut.Ergebnis erg)
        {
            // Counting all Subtrees Starting from Bottom Left Node of Tree
            int sub1       = 0;
            int sub2       = 1;
            int iterations = 0;

            // Those values are constantly added to each other, because each Node holds all Subtrees of the previous two Nodes

            for (int i = n, tmp; i > 0; i--)
            {
                iterations++;
                tmp = Math.Max(sub1, 1);
                if (sub1 + sub2 < sub1)
                {
                    throw new OverflowException("Integer Overflow");
                }
                sub1 += sub2;
                sub2  = tmp;
            }
            erg.Setze(sub1, iterations == 0 ? 1 : iterations, Complexity.LINEAR, Complexity.CONSTANT);

            /*         13:      0
             *         8:      1
             *         5:     2
             *         3:    3
             *         2:   4
             *         1:  5
             *         1: 6
             *
             *
             *
             */
        }
Beispiel #9
0
        private static void Counting_Subtrees_2(int n, InOut.Ergebnis erg)
        {
            if (n < 1)
            {
                erg.Setze(0, 1);
                return;
            }

            int sub1       = 1;
            int sub2       = 1;
            int iterations = 0;

            for (int i = n - 1, tmp; i > 0; i--)
            {
                iterations++;
                tmp = Math.Max(sub1, 1);
                if (sub1 + sub2 < sub1)
                {
                    throw new OverflowException("Integer Overflow");
                }
                sub1 += sub2;
                sub2  = tmp;
            }

            erg.Setze(sub1, iterations == 0 ? 1:iterations, Complexity.LINEAR, Complexity.CONSTANT);
        }
        //SOL
        public static void Solve_ConstantSpace(int[] inp, InOut.Ergebnis erg)
        {
            int prev = inp[0];
            int bonus = 1, nextBon = 1;

            for (int i = 1; i < inp.Length; i++)
            {
                if (inp[i] < prev)
                {
                    bonus++;
                }
                else if (inp[i] != prev)
                {
                    nextBon = 2;
                }

                inp[i - 1] = bonus;

                bonus   = nextBon;
                nextBon = 1;
                prev    = inp[i];
            }
            inp[inp.Length - 1] = bonus;

            erg.Setze(inp, Complexity.LINEAR, Complexity.CONSTANT);
        }
        //SOL
        public static void Solve(int num, InOut.Ergebnis erg)
        {
            int it = 0;

            int[][] triangle = new int[num][];
            if (num < 1)
            {
                erg.Setze(triangle, Complexity.LINEAR, Complexity.LINEAR); return;
            }
            triangle[0] = new int[] { 1 };
            if (num == 1)
            {
                erg.Setze(triangle, Complexity.LINEAR, Complexity.LINEAR); return;
            }

            triangle[1] = new int[] { 1, 1 };
            int[] prev = triangle[1], cRow;
            for (int i = 2; i < num; i++)
            {
                cRow    = new int[prev.Length + 1];
                cRow[0] = cRow[cRow.Length - 1] = 1;
                for (int j = 1; j <= (cRow.Length / 2); j++, it++)
                {
                    cRow[j] = prev[j - 1] + prev[j];
                    cRow[cRow.Length - j - 1] = cRow[j];
                }

                prev        = cRow;
                triangle[i] = cRow;
            }

            erg.Setze(triangle, Complexity.LINEAR, Complexity.LINEAR);
        }
        //SOL
        public static void Solver1(char[] c, InOut.Ergebnis erg)
        {
            int i, pt;

            for (i = 0, pt = 0; i < c.Length; i++)
            {
                if (c[pt] == c[i])
                {
                    if (i - pt > 2)
                    {
                        c[i - 1] = c[i];
                    }
                }
                else if (i - pt > 1)
                {
                    c[pt + 1] = (i - pt + "")[0];
                    pt        = i;
                }
                else
                {
                    pt = i;
                }
            }
            if (i - pt > 1)
            {
                c[pt + 1] = (i - pt + "")[0];
            }
            pt++;
            while (++pt < c.Length)
            {
                c[pt] = '-';
            }

            erg.Setze(c, Complexity.LINEAR, Complexity.CONSTANT);
        }
        //SOL

        /*
         * Identify Larger Array.
         * Larger array size = n + m       | Where m is size of smaller Array
         * Use m Part of Large_arr as Puffer
         *
         */

        public static void MergeSmallerArrayIntoLarger_ConstantSpace(int[][] arr, InOut.Ergebnis erg)
        {
            int[] large = arr[0].Length > arr[1].Length ? arr[0] : arr[1];
            int[] small = large == arr[1] ? arr[0] : arr[1];

            int puffer    = small.Length; //Points to Start of Puffer
            int pufferEnd = small.Length;
            //Puffer Stores unprocessed Elements of larger Array
            //if el of small < el of large => puffer el of large
            int ptLarge = 0;    //Points to Current El of Large
            int ptSmall = 0;    //Points to Current El of small

            for (; ptSmall < small.Length; ptLarge++)
            {
                if (pufferEnd - puffer > 0 && large[puffer] < small[ptSmall] && ptLarge < small.Length)
                {
                    large[pufferEnd++] = large[ptLarge];
                    large[ptLarge]     = large[puffer++];
                    large[puffer - 1]  = int.MaxValue;
                }
                else if (large[ptLarge] > small[ptSmall] || ptLarge >= pufferEnd)
                {
                    if (ptLarge < small.Length)
                    {
                        large[pufferEnd++] = large[ptLarge];
                    }
                    large[ptLarge] = small[ptSmall++];
                }
            }

            erg.Setze(large, Complexity.LINEAR, Complexity.CONSTANT);
        }
        private static void BinarySearchSqrt2(int x, InOut.Ergebnis erg)
        {
            int    it = 0;
            long   depth = 1;
            double low = 0, high = x, mid = 0;

            while (depth <= 100000000000)
            {
                it++;
                mid = (high + low) / 2;
                mid = ((double)(int)(mid * depth)) / depth;
                int comp = (mid * mid).CompareTo(x);
                if (comp > 0)
                {
                    high = mid;
                }
                else if (comp < 0)
                {
                    low = mid;
                }
                else
                {
                    break;
                }
                if ((high - low) <= (1.0 / Math.Min(depth * 10, 1)))
                {
                    depth *= 10;
                }
            }
            erg.Setze(mid, it, Complexity.LOGARITHMIC, Complexity.CONSTANT);
        }
Beispiel #15
0
        public static void Solve_NumSpaceComplexity(int num, InOut.Ergebnis erg)
        {
            int it = 0;

            List <int> list = new List <int>();

            if (num > 0)
            {
                list.Add(1);
            }
            if (num > 1)
            {
                for (int i = 1; i < num; i++)
                {
                    list.Add(1);
                    list[0] = 1;
                    int prev = list[0], tmp = list[1];
                    for (int j = list.Count <= 2 ? 20 : 1; j <= (list.Count - 1) / 2; j++, it++)
                    {
                        tmp     = list[j];
                        list[j] = prev + list[j];
                        list[list.Count - 1 - j] = list[j];
                        prev = tmp;
                    }
                }
            }

            erg.Setze(list.ToArray(), it, Complexity.LINEAR, Complexity.LINEAR);
        }
        public static void Solve_BruteForce(int[] arr, InOut.Ergebnis erg)
        {
            HashSet <int> doubles = new HashSet <int>();
            int           maxInd1 = 0, maxInd2 = 0, maxSum = 0;
            int           cycles = 0;

            for (int i = 0; i < (arr.Length + 1) / 2; i++) // Only Process half of the Array
            {
                if (doubles.Contains(arr[i]))
                {
                    continue;
                }
                doubles.Add(arr[i]); // Don't Process Number that apear multiple times

                for (int curr = arr[i], j = 0; j < arr.Length; j++, cycles++)
                {
                    if (i - j == 0 || i - j == 1 || i - j == -1)
                    {
                        continue;
                    }
                    if (curr + arr[j] <= maxSum)
                    {
                        continue;
                    }
                    maxSum  = curr + arr[j];
                    maxInd1 = i;
                    maxInd2 = j;
                }
            }

            erg.Setze(new int[] { maxInd1, maxInd2 }, cycles, Complexity.LINEAR, Complexity.LINEAR);
        }
Beispiel #17
0
        private static void Solve(Input input, InOut.Ergebnis erg)
        {
            LinkedList <int> summand1 = input.summand1;
            LinkedList <int> summand2 = input.summand2;

            LinkedList <int> .Node node = summand1.Root, node2 = summand2.Root, outp = null;
            int val = 0;

            while (node != null || node2 != null || val > 0)
            {
                if (node != null)
                {
                    val += node.Val;
                    node = node.Next;
                }
                if (node2 != null)
                {
                    val  += node2.Val;
                    node2 = node2.Next;
                }
                if (outp == null)
                {
                    outp = new LinkedList <int>(val % 10).Root;
                }
                else
                {
                    outp.Next = new LinkedList <int> .Node(val % 10);

                    outp = outp.Next;
                }
                val /= 10;  // Overflow handeln --> val of next iteration == carry
            }
            erg.Setze(outp.List);
        }
        private static void Solve1(string input, InOut.Ergebnis erg)
        {
            int            count = 0;
            LLStack <char> stack = new LLStack <char>();

            for (int i = 0; i < input.Length; i++)
            {
                count++;
                if (stack.Count == 0)
                {
                    stack.Push(input[i]);
                }
                else if (match.Keys.Contains <char>(input[i]))
                {
                    stack.Push(input[i]);
                }
                else if (match[stack.Peek()] == input[i])
                {
                    stack.Pop();
                }
                else
                {
                    break;
                }
            }
            erg.Setze(stack.Count == 0, count);
        }
        // SOLVE
        private static void SolverRecursive(IDictionary <string, string[]> inp, InOut.Ergebnis erg)
        {
            IList <string> list = new List <string>();

            AddPreReq(inp, list, inp.Keys.ElementAt(0));
            erg.Setze(list.ToArray <string>());
        }
        //SOL
        public static void SolveCharArray(string s, InOut.Ergebnis erg)
        {
            char[] cArr = s.ToCharArray();
            int    ptLeft = 0, ptRight = cArr.Length - 1;

            while (ptLeft < ptRight)
            {
                if (!VOWELS.Contains(cArr[ptLeft]))
                {
                    ptLeft++;
                }
                else if (!VOWELS.Contains(cArr[ptRight]))
                {
                    ptRight--;
                }
                else
                {
                    char temp = cArr[ptLeft];
                    cArr[ptLeft++]  = cArr[ptRight];
                    cArr[ptRight--] = temp;
                }
            }


            erg.Setze(new string(cArr), Complexity.LINEAR, Complexity.LINEAR);
        }
Beispiel #21
0
        public static void TwoSum_TwoPointers(Input inp, InOut.Ergebnis erg)
        {
            Output outp = new Output(null);

            int[] arr = inp.arr;
            int   tar = inp.target;
            int   it = 0;
            int   ptSmall = 0, ptBig = inp.arr.Length - 1;

            while (ptSmall < ptBig)
            {
                it++;
                int sum = arr[ptSmall] + arr[ptBig];
                if (sum > tar)
                {
                    ptBig--;
                }
                else if (sum < tar)
                {
                    ptSmall++;
                }
                else
                {
                    outp = new Output(new int[] { ptSmall + 1, ptBig + 1 });
                    break;
                }
            }

            erg.Setze(outp, it, Complexity.LINEAR, Complexity.CONSTANT);
        }
        public static void SolveStringbuilder(string s, InOut.Ergebnis erg)
        {
            StringBuilder fHalf = new StringBuilder(), sHalf = new StringBuilder();
            int           ptLeft = 0, ptRight = s.Length - 1;

            while (ptLeft < ptRight)
            {
                bool b1 = !VOWELS.Contains(s[ptLeft]);
                bool b2 = !VOWELS.Contains(s[ptRight]);

                if (b1)
                {
                    fHalf.Append(s[ptLeft++]);
                }
                if (b2)
                {
                    sHalf.Insert(0, s[ptRight--]);
                }
                if (b1 || b2)
                {
                    continue;
                }
                sHalf.Insert(0, s[ptLeft++]);
                fHalf.Append(s[ptRight--]);
            }


            erg.Setze(fHalf.ToString() + (s.Length % 2 == 0 ? "":s[s.Length / 2 + 1] + "") + sHalf.ToString(), Complexity.LINEAR, Complexity.LINEAR);
        }
Beispiel #23
0
        //  Similar to the Recursive Solution
        //  start with 0 and arrLen -1
        //  Adds middle element of range to tree
        //  Adds NEWrange from start of curr_range to middleElement
        //  Adds NEWrange from middleElement to end of curr_range
        private static void SolveIterative(int[] arr, InOut.Ergebnis erg)
        {
            IBTree <int> tree = new BinarySearchTree <int>();

            DS_HANDBOOK.Interfaces.IQueue <int[]> q = new DS_HANDBOOK.Queue.ArrayQueue <int[]>(arr.Length * 2);
            q.AddStringConverter(Helfer.Arrayausgabe <int>);

            q.Enqueue(new int[] { 0, arr.Length - 1 }); // start, end
            while (!q.IsEmpty())
            {
                int[] range  = q.Dequeue();
                bool  isEven = (range[1] + 1 - range[0]) % 2 == 0;
                int   mid    = (range[0] + range[1]) / 2;
                tree.Append(arr[mid]);
                if (range[0] >= range[1])
                {
                    continue;
                }
                q.Enqueue(new int[] { range[0], mid - 1 });             // Add range from start to mid-1
                q.Enqueue(new int[] { mid + (isEven? 2:1), range[1] }); // Add range from mid+1 to end
                if (isEven)
                {
                    q.Enqueue(new int[] { mid + 1, mid + 1 });
                }
            }
            erg.Setze(tree);
        }
        public static void WithHashValue(string[] words, InOut.Ergebnis erg)
        {
            IDictionary <int, List <string> > strIndex = new Dictionary <int, List <string> >();

            for (int i = 0; i < words.Length; i++)
            {
                int key = 1;
                int sec = 0;
                foreach (char c in words[i])
                {
                    key *= c;
                    sec  = sec + (c % 2 == 0 ? c : -c);
                }
                key = key * sec + words[i].Length;

                if (!strIndex.ContainsKey(key))
                {
                    strIndex[key] = new List <string>(new string[] { words[i] });
                }
                else
                {
                    strIndex[key].Add(words[i]);
                }
            }

            string[][] ergArr = new String[strIndex.Count][];
            int        count2 = 0;

            foreach (List <String> wordArr in strIndex.Values)
            {
                ergArr[count2++] = wordArr.ToArray <string>();
            }

            erg.Setze(ergArr);
        }
        private static void SolveSmallerBoundary(int[] arr, InOut.Ergebnis erg)
        {
            int bRight = arr.Length - 1, bLeft = 0;
            int sum = 0, count = 0;

            while (bLeft < bRight + 1)
            {
                if (arr[bLeft] <= arr[bRight])   //Evaluate lower boundary
                {
                    count = bLeft + 1;
                    while (arr[count] <= arr[bLeft] && count < bRight)
                    {
                        sum += arr[bLeft] - arr[count++];                                                 //Eval from left until bigger boundary found
                    }
                    bLeft = count;
                }
                else
                {
                    count = bRight - 1;
                    while (arr[count] <= arr[bRight] && count > bLeft)
                    {
                        sum += arr[bRight] - arr[count--];                                                 //Eval from right until bigger boundary found
                    }
                    bRight = count;
                }
            }
            erg.Setze(sum, Complexity.LINEAR, Complexity.CONSTANT);
        }
        //SOL
        public static void SortWords(string[] words, InOut.Ergebnis erg)
        {
            IDictionary <string, List <string> > strIndex = new Dictionary <string, List <string> >();

            for (int i = 0; i < words.Length; i++)
            {
                char[] arr = words[i].ToCharArray();
                Array.Sort(arr);
                string sorted = new String(arr);
                if (strIndex.Keys.Contains(sorted))
                {
                    strIndex[sorted].Add(words[i]);
                }
                else
                {
                    strIndex[sorted] = new List <string>(new string[] { words[i] });
                }
            }

            string[][] ergArr = new String[strIndex.Count][];
            int        count  = 0;

            foreach (List <String> wordArr in strIndex.Values)
            {
                ergArr[count++] = wordArr.ToArray <string>();
            }


            erg.Setze(ergArr);
        }
        //SOL

        private static void SetZero_ConstantSpace(Helfer.Matrix <int> matrix, InOut.Ergebnis erg)
        {
            int[,] mat = matrix.mat;
            for (int i = 0; i < mat.GetLength(1); i++)
            {
                for (int j = 0; j < mat.GetLength(0); j++)
                {
                    if (mat[j, i] != 0)
                    {
                        continue;
                    }
                    mat[j, 0] = 0;
                    mat[0, i] = 0;
                }
            }
            // Parse first row and skip first col
            for (int i = 1; i < mat.GetLength(0); i++)
            {
                if (mat[i, 0] == 0)
                {
                    SetColZero(mat, i);
                }
            }
            // Parse first col
            for (int i = 0; i < mat.GetLength(1); i++)
            {
                if (mat[0, i] == 0)
                {
                    SetRowZero(mat, i);
                }
            }
            erg.Setze(matrix);
        }
Beispiel #28
0
        //SOL
        public static void Solve(int num, InOut.Ergebnis erg)
        {
            int it = 0;

            if (num < 1)
            {
                erg.Setze(new int[] { }, Complexity.LINEAR, Complexity.LINEAR); return;
            }
            if (num == 1)
            {
                erg.Setze(new int[] { 1 }, Complexity.LINEAR, Complexity.LINEAR); return;
            }

            int[] prev = new int[] { 1, 1 }, cRow = prev;
            for (int i = 2; i < num; i++)
            {
                cRow    = new int[prev.Length + 1];
                cRow[0] = cRow[cRow.Length - 1] = 1;
                for (int j = 1; j <= (cRow.Length / 2); j++, it++)
                {
                    cRow[j] = prev[j - 1] + prev[j];
                    cRow[cRow.Length - j - 1] = cRow[j];
                }

                prev = cRow;
            }

            erg.Setze(cRow, it, Complexity.LINEAR, Complexity.LINEAR);
        }
        public static void GetMinimumRemovals_ConstantSpace(string parent, InOut.Ergebnis erg)
        {
            int open   = 0;
            int remove = 0;

            foreach (char c in parent)
            {
                if (c == ')')
                {
                    if (open > 0)
                    {
                        open--;
                    }
                    else
                    {
                        remove++;
                    }
                }
                else if (c == '(')
                {
                    open++;
                }
                else
                {
                    throw new Exception(c + " is not a Parenthesis");
                }
            }

            erg.Setze(remove + open, Complexity.LINEAR, Complexity.CONSTANT);
        }
Beispiel #30
0
        //SOL
        public static void SolveOnePass(int[] arr, InOut.Ergebnis erg)
        {
            int max3 = int.MinValue, max2 = int.MinValue, max1 = int.MinValue, it = 0;

            for (int i = 0, curr = arr[0]; i < arr.Length; i++, it++)
            {
                curr = arr[i];
                if (curr == max1 || curr == max2 || curr == max3)
                {
                    continue;
                }
                else if (curr > max1)
                {
                    max3 = max2;
                    max2 = max1;
                    max1 = curr;
                }
                else if (curr > max2)
                {
                    max3 = max2;
                    max2 = curr;
                }
                else
                {
                    max3 = curr;
                }
            }

            erg.Setze(max3 == int.MinValue ? max1 : max3, it, Complexity.LINEAR, Complexity.CONSTANT);
        }