Omar Alaa Omar Alaa - 1 month ago 10
C# Question

C# Array Length Update

I am solving the problem from this link: https://www.hackerrank.com/challenges/cut-the-sticks (I added the link for more details if my explanation wasn't enough or wasn't quite clear.)

The point here from the exercise that I in the first I give a (int) number of sticks that I will use in the operation. the second line I enter the sticks length. So I must find the smallest stick(k), then subtract it from the rest of the sticks, then make the program print the number of total sticks that I have cut. So if the stick was cut before or its original value is 0 I have to remove it and don't count it. Then this should repeat over to redefine the value of the k because the min array value will be changed because all the sticks are cutted.

Here is my code that I used:

int n = Convert.ToInt32(Console.ReadLine());
string[] userinput = Console.ReadLine().Split(' ');
int[] arr = new int[n];
arr = Array.ConvertAll(userinput, Int32.Parse);
for (int i = 0; i < n - 1; i++)
{
arr = arr.Where(s => s != '0').ToArray();
int k = arr.Min();
arr[i] -= k;
Console.WriteLine(arr.Length);
}
Console.ReadKey();


The problem is it keeps printing the n value, which is the array's original size, it doesn't modify after the removing of the 0. So how can I fix it to just print the number of cutted sticks and when the all sticks is 0 so break?

I'm sorry for my English and if my explanation is a bit hard, but I am just new to C#.

Answer

This is the working code as you expected and tested.

Note: I just reused all the variable names and naming conventions as you did which can be refactored further.

class Program
    {
        static void Main(string[] args)
        {
            int n = Convert.ToInt32(Console.ReadLine());
            string[] userinput = Console.ReadLine().Split(' ');
            int[] arr = new int[n];
            arr = Array.ConvertAll(userinput, Int32.Parse);
            CutTheStick(arr);
            Console.ReadKey();
        }

        private static void CutTheStick(int[] arr)
        {
            arr = arr.Where(s => s != 0).ToArray();

            if (arr.Length > 0)
            {
                Console.WriteLine(arr.Length);
                int k = arr.Min();

                for (int i = 0; i < arr.Length; i++)
                {
                    arr[i] -= k;
                }

                CutTheStick(arr);
            }
        }
    }

If you had web/winForm based application, remove the static keyword accordingly.