c#数组长度更新

本文关键字:更新 数组 | 更新日期: 2023-09-27 18:16:28

我正在从这个链接解决问题:https://www.hackerrank.com/challenges/cut-the-sticks(如果我的解释不够或不太清楚,我添加了更多细节的链接。)

从练习中得到的点,我在第一个例子中给出了一个(int)数量的棍子,我将在操作中使用这些棍子。第二行我输入棒子的长度。所以我必须找到最小的木棍(k),然后从剩下的木棍中减去它,然后让程序打印出我砍下的木棍的总数。所以如果棍子之前被切过或者它的原始值是0,我必须把它移走,不计算它。然后这应该重复来重新定义k的值,因为最小数组值将被改变,因为所有的棒都被剪掉了。

下面是我使用的代码:
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();

问题是它一直打印n值,这是数组的原始大小,它在删除0后不修改。那么我如何修复它,让它只打印被切割的棒子的数量当所有的棒子都是0时,中断?

我很抱歉我的英语,如果我的解释有点难,但我只是c#的新手。

c#数组长度更新

这是您所期望和测试的工作代码。

注意:我只是像你一样重用了所有的变量名和命名约定,这些可以进一步重构。

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);
            }
        }
    }

如果你有一个基于web/winForm的应用程序,删除相应的static关键字

您的代码中有一个明显的错误。字符'0'不是整数0。char和int之间的自动转换允许编译和运行此代码,但您没有正确测试输入

例如

int[] arr = new int[] {0,1,2,3,4};
if(arr[0] == '0')
    Console.WriteLine("Is Zero");

永远不会输出"Is Zero",而

int[] arr = new int[] {48,1,2,3,4};
if(arr[0] == '0')
    Console.WriteLine("Is Zero");

将打印"Is Zero",因为字符'0'的整数值是48。

现在给你的问题一个解决方案,我可以张贴这个代码

int cutCount = 1;
int n = Convert.ToInt32(Console.ReadLine());
string[] userinput = Console.ReadLine().Split(' ');
int[] arr = Array.ConvertAll(userinput, Int32.Parse);
// Loop until we finish to empty the array
while (true)
{
    // remove any zero present in the array
    arr = arr.Where(s => s != 0).ToArray();
    // If we don't have any more elements we have finished
    if(arr.Length == 0) 
        break;
    // find the lowest value
    int k = arr.Min();
    // Start a loop to subtract the lowest value to all elements
    for (int i = 0; i < arr.Length; i++)
        arr[i] -= k;
    // Just some print to let us follow the evolution of the array elements
    Console.WriteLine($"After cut {cutCount} the array length is {arr.Length}");
    Console.Write("Array is composed of: ");
    foreach(int x in arr)
        Console.Write(x + " ");
    Console.WriteLine();
}
Console.ReadLine();

但是请仔细学习,否则我的解决方案对你以后的编程任务没有任何帮助