Tuesday, October 31, 2017

Find Peak

            //given a number of characters find the peak character which is the current that is repeated the most, there can be more than one character at the peak if the number of repeatition tie
            var input = "abbabacdexxxxxxdx"; //return x
            var arr = input.ToCharArray();
            arr = arr.OrderBy(x=> x).ToArray(); //order the list to know when to stop counting occurence
            //Initialize result container
            var result = new List<char>();
            //Loop length of array - pointing to index from left p = 0 
            var currentMax = 0;
            var prevChar = arr[0];
            var r = 0;
            for (int p = 0; p < arr.Length ; p++)
            {
                if (arr[p] == prevChar)
                {
                    r++;
                }
                else
                {
                    if (r > currentMax)
                    {
                        result = new List<char> { arr[p - 1] };
                    }
                    else if (r == currentMax)
                    {
                        result.Add(arr[p - 1]);
                    }
                    currentMax = r;
                    prevChar = arr[p];
                    r = 1;
                }
            }
            //Keep previous character
            //Compare arr[p] to previous 
            //Equal count repeatition r of a
            //not equal stop counting repeatition and compare to max if less than max discard 
            //If equal to max append to peak
            //if less than discard
            //greater than max 
            //discard output collected previously and initialize it only with this character

            if (r > currentMax)
            {
                result = new List<char> { arr.Last() };
            }
            else if (r == currentMax)
            {
                result.Add(arr.Last());

            }

No comments: