【问题标题】:Check if every elements in array is of same value检查数组中的每个元素是否具有相同的值
【发布时间】:2014-07-12 03:42:45
【问题描述】:

基本上我想要做的是检查 int 数组中的每个元素,如果所有元素都具有相同的值。

我创建如下的 int 数组来传递给比较每个数组元素的方法,即使元素不是完全相同的值,它也会返回 boolean true。

Int[] denominator = {3,3,4,3};

boolean compare;

compare = bruteforce(denominator);

public static boolean bruteforce(int[] input) {

int compare =0;
int count =0;

    for (int i = 0; i < input.length; i++) {

        compare = input[i];

        while(count<input.length){

            if(input[i+1]==compare){
            return true;

            }
            i++;
            count++;

        }//end while

    }//end for
    return false;
}//end method

我想上面的方法会循环遍历数组的每个元素并保持比较。

当我打印输出时,它显示它只循环一次,返回布尔值为真。

我真的不知道我的代码有什么问题。

也许我只是忽略了一些愚蠢的错误。

【问题讨论】:

  • 它是因为如果第一个元素等于第二个元素,您会立即返回 true。您需要检查它们是否不相等,如果是则返回false。然后,如果它们永远不相等,则在最后返回 true。此外,你会得到一个索引越界异常。
  • @Carlos Bribiescas 谢谢,最后我得到了上面数组的返回 false 的结果。但是,是的,如果所有元素都是相同的值,它会给出索引超出范围。我该如何解决这个问题?
  • if(input[i+1]==compare){ i == input.length - 1 是 AFA 的罪魁祸首 IndexOutOfBoundsException

标签: java arrays


【解决方案1】:

试试,

Integer[]    array = {12,12,12,12};
Set<Integer> set   = new HashSet<Integer>(Arrays.asList(array));
System.out.println(set.size()==1?"Contents of Array are Same":"Contents of Array are NOT same");

解释:

将数组添加到集合并检查大小 os set ,如果为 1 则内容相同,否则不。

【讨论】:

  • 非常聪明。不过,我认为您的意思是 new HashSet&lt;Integer&gt;(Arrays.asList(array)) 而不是 new HashSet&lt;Integer&gt;(Arrays.asList(array1))。此外,采用这种方法的bruteforce 的实现还应考虑输入数组为null
  • @J0e3gan 感谢编辑这是一个打字错误:)
【解决方案2】:

您只需要一个循环,并且应该在适用的情况下尽快返回false(即当您遇到与第一个不匹配的元素时)。

您还需要考虑输入数组为null 或只有一个元素的极端情况。

尝试这样的事情,我根据您提供的代码进行了最低限度的改编......

public class BruteForceTest {

    public static boolean bruteforce(int[] input) {

        // NOTE: Cover the edge cases that the input array is null or has one element.
        if (input == null || input.length == 1)
            return true; // NOTE: Returning true for null is debatable, but I leave that to you.

        int compare = input[0]; // NOTE: Compare to the first element of the input array.

        // NOTE: Check from the second element through the end of the input array.
        for (int i = 1; i < input.length; i++) {
            if (input[i] != compare)
                return false;
        }

        return true;

    }

    public static void main(String[] args) {

        int[] denominator = {3,3,4,3};
        boolean compare = bruteforce(denominator);

        // FORNOW: console output to see where the first check landed
        System.out.print("{3,3,4,3}:\t");
        if (compare)
            System.out.println("Yup!");
        else
            System.out.println("Nope!");

        // NOTE: a second array to check - that we expect to return true
        int[] denominator2 = {2,2};
        boolean compare2 = bruteforce(denominator2);

        System.out.print("{2,2}:\t\t");
        if (compare2)
            System.out.println("Yup!");
        else
            System.out.println("Nope!");

        /*
         *  NOTE: edge cases to account for as noted below
         */

        // array with one element
        int[] denominator3 = {2};
        System.out.print("{2}:\t\t");
        if (bruteforce(denominator3))
            System.out.println("Yup!");
        else
            System.out.println("Nope!");

        // null array
        System.out.print("null:\t\t");
        if (bruteforce(null))
            System.out.println("Yup!");
        else
            System.out.println("Nope!");

    }

}

...和输出:

{3,3,4,3}:  Nope!
{2,2}:      Yup!
{2}:        Yup!
null:       Yup!

【讨论】:

    【解决方案3】:

    如果数组元素相等,您只需将第一个元素与其余元素进行比较,因此更好的解决方案如下:

    public static boolean bruteforce(int[] input) {
         for(int i = 1; i < input.length; i++) {
             if(input[0] != input[i]) return false;
         }
    
         return true;
    }
    

    对于这个简单的算法,您不需要多个循环。希望这会有所帮助。

    【讨论】:

    • 这很简洁,但没有说明input 可能是null。该方法应考虑到这种极端情况。
    • 谢谢@Oussama Bouguerne,但数组元素不是静态的。我的意思是,它会根据用户输入而改变。
    • 是的@J0e3gan 我知道了,但忘了包括它,谢谢提醒。
    • @user3790782 我上面写的方法适用于任何输入大小,但如果你给它大输入大小会很慢。
    【解决方案4】:

    如果所有元素都是相同的值,为什么不只使用一个 for 循环来测试数组中的下一个值呢?如果不是,则返回 false。

    【讨论】:

      【解决方案5】:

      如果你想检查所有元素是否具有相同的值,那么你可以用更简单的方式来做,

      int arr = {3,4,5,6};
      
      int value = arr[0];
      
      
      flag notEqual = false;
      
      for(int i=1;i < arr.length; i++){
      
           if(!arr[i] == value){
                 notEqual = true;
                 break;
           }
      
      }
      
      if(notEqual){
           System.out.println("All values not same");
      }else{
           System.out.println("All values same);
      }
      

      【讨论】:

        【解决方案6】:

        现在,您没有检查“所有元素是否具有相同的值”。每当(第一次)两个元素彼此相等时,您将结束函数并返回 true。 当你有两个不相等的元素时,为什么不将布尔值设置为 true 并返回 false 呢?这样您就可以保留大部分已有的东西。

        if(input[i+1]!=compare) 返回 false;

        【讨论】:

          【解决方案7】:
          public class Answer {
          
              public static void main(String[] args)
              {
                  boolean compare = false;
                  int count = 0;
                  int[] denominator = { 3, 3, 4, 3 };
          
          
                  for (int i = 0; i < denominator.length; i++)
                  {
                      if(denominator[0] != denominator[i]) 
                      {
                          count++;
                      }
                  }
                  if(count > 0)
                  {
                      compare = false;
                  } else
                  {
                      compare = true;
                  }
                  System.out.println(compare);
          
              }
          }
          

          我注意到蝙蝠右侧的一个错误是您将数组声明为 Int[],这不是 java 关键字,实际上是 int[]。此代码检查您的数组,如果数组中的值不相等,则返回 false。如果数组的值彼此相等,则程序返回 true。

          【讨论】:

          • Int[]int[] 的良好通话。我忘记了当我使用 OP 的代码时我立即纠正了这一点。 :}
          • 这个实现看起来可以工作,但它也会不必要地遍历数组的每个元素——当元素的不等式已经确定时;在大输入时,这会受到伤害:您需要有条件的 breakreturn 来避免这种情况。
          • 你说得对,感谢您的指正。
          【解决方案8】:

          如果您对测试数组相等性感兴趣(而不是自己编写此测试),那么您可以使用Arrays.equals(theArray, theOtherArray)

          【讨论】:

          • 这是关于测试给定数组中所有元素的相等性,而不是测试两个数组的相等性。
          • @J0e3gan Arrays.equals(a,b)a.equals(b) 不同,当且仅当两个数组包含相同顺序的相同元素时才会返回 true。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-01-03
          • 2014-02-03
          • 1970-01-01
          • 2013-11-21
          • 1970-01-01
          • 2019-04-27
          • 1970-01-01
          相关资源
          最近更新 更多