试图计算二维数组中的项目数

时间:2016-09-17 20:32:37

标签: java arrays

我试图找到一个与2D数组中所有行相同的可比值。 对于该值,我想找到所有行中存在的最小(> 0)重复次数。

例如,使用String数组时:

private bool NoLoop { get; set; }

void switcher_Toggled(object sender, ToggledEventArgs e)
        {
            Device.BeginInvokeOnMainThread(async () =>
            {
                if (NoLoop)
                {
                    NoLoop = false;
                    return;
                }
                bool alert;

                if (this._isConnectionStatusOpen == true)
                {
                    alert = await DisplayAlert("Close ", "Are you sure you want to close connection?", "Yes", "No");
                }
                else
                {
                    alert = await DisplayAlert("Open", "Are you sure you want to Open connection?", "Yes", "No");

                }

                if (alert != true)
                {
                    NoLoop = true;
                    Switch thisSender = (Switch)sender;
                    thisSender.IsToggled = !thisSender.IsToggled;

                }
            });
        }

所有行中唯一存在的值是" A"。连续出现的最小次数为1,因此答案为{ {A, C, B}, {A, A, B}, {C, D, A} }

这是我的代码:我试图连续搜索每一列中的重复项(或三元组等),确定给定行的计数并将其与其他行进行比较以确定数量最少的行。还有,也许有更优雅的方法?由于某种原因,它不起作用(集合是一个二维字符串数组):

1 A

2 个答案:

答案 0 :(得分:0)

好吧,首先,当collections[0][i].toString()i时,您需要0,以便评估为A,然后程序会遍历所有这些循环并设置lowestCount1。然后,您的第一个for循环移至B并重置lowestCount,而不会将其保存在任何位置。您应该将lowestCount保存在数组或列表中,并在第一个for循环结束时(在其他两个for循环之后)将lowestCount添加到该数组,您将具有最低计数每一封信。如果您不想保存,可以System.out.println("Lowest count of letter: "+current+" is: "+lowestCount);。如果要确定具有最低计数的行,您还可以将其保存在数组中(每个字母的计数最少的行),如果if语句通过(if(lowestCount < count)),则将其设置为。 / p>

我不确定我是否理解正确,但肯定有更好的方法来解决这个问题。

答案 1 :(得分:0)

你可以这样做

int[][] arr = new int[5][2];
    int count =0;
    for(int[] i : arr){
        count = count + i.length;
    }
    System.out.println(count);