3

Basically what I want to do is to check on each element in an array of int, if all elements are of the same value.

I create int array as below to pass to the method for comparing each array element, it return boolean true even tough the elements are not all the same values.

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

I suppose the method above will loop for and keep compare for each element of the array.

When I print out the output, it showed that it only loop once, the return the boolean as true.

I really lost the clue what could be wrong in my code.

Perhaps I just overlook of some silly mistakes.

3
  • 3
    its because you return true immediately if the first element equals the second element. you need to check to see if they are unequal, if so return false. then if they are never unequal, return true at the end. also, you will get an index out of bounds exception. Commented Jul 12, 2014 at 3:45
  • @Carlos Bribiescas thanks, finally I got the result as return false for the array above. But yeah, if all elements are same value, it give index out of bounds. How can I fix this? Commented Jul 12, 2014 at 4:45
  • if(input[i+1]==compare){ when i == input.length - 1 is the culprit AFA the IndexOutOfBoundsException. Commented Jul 12, 2014 at 5:07

8 Answers 8

3

Try,

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

Explanation:

Add the array to a set and check the size os set , if it is 1 the contents are same else not.

Sign up to request clarification or add additional context in comments.

2 Comments

Very clever. I think you mean new HashSet<Integer>(Arrays.asList(array)) rather than new HashSet<Integer>(Arrays.asList(array1)), though. Also, an implementation of bruteforce that takes this approach should additionally account for the input array being null.
@J0e3gan Thanks For Edit it was an typing mistake :)
2

You only need one loop and should return false as quickly as possible where applicable (i.e. when you encounter an element that doesn't match the first).

You also need to account for the edge cases that the input array is null or has one element.

Try something like this, which I minimally adapted from the code you provided...

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!");

    }

}

...and outputs:

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

Comments

2

If an array elements are equal you only need to compare the first element with the rest so a better solution to your problem is the following:

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

     return true;
}

You don't need more than one loop for this trivial algorithm. hope this helps.

4 Comments

This is concise but does not account for input possibly being null. The method should account for this edge case.
Thanks, @Oussama Bouguerne but the array elements are not static. I mean, it will change according to user input.
Yes @J0e3gan I am aware of that and forgot to include it, thanks for the reminder.
@user3790782 the method I wrote above will work for any input size, although if you give it large input sizes it will be slow.
0

If all elements are the same value, why not use only one for loop to test the next value in the array? If it is not, return false.

Comments

0

If you want to check if all elements are of same value then you can do it in a simpler way,

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

Comments

0

Right now, you are not checking if "all the elements are of the same value". You are ending the function and returning true whenever (the first time) two elements are equal to each other. Why not set the boolean value to true and return false whenever you have two elements that are not equal to each other? That way you can keep most of what you have already.

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

Comments

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

    }
}

One mistake that I noticed right of the bat was that you declared your array as Int[], which is not a java keyword it is in fact int[]. This code checks your array and returns false if the array possesses values that are not equal to each other. If the array possesses values that are equal to each other the program returns true.

3 Comments

Good call on Int[] vs. int[]. I forgot that I immediately corrected that when I worked with the OP's code. :}
This implementation looks like it will work, but it will also needlessly iterate through every element of the array - when the inequality of elements has already been determined; on big inputs, this will hurt: you need a conditional break or return to avoid this.
Ya that seems about right thanks for the correction.
-1

If you're interested in testing array equality (as opposed to writing out this test yourself), then you can use Arrays.equals(theArray, theOtherArray).

2 Comments

This is about testing the equality of all elements in a given array, not testing the equality of two arrays.
@J0e3gan Arrays.equals(a,b), unlike a.equals(b), will return true if and only if the two arrays contain the same elements in the same order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.