Check if every elements in array is of same value - java

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.

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.

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!

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.

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.

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

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;

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.

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

Related

Returning different return value

When i have a problem with the code im writing, i usually handle it like a story. Each command is a sentence in a story. The sentences needs to make sense in order for the story to be complete/right.
So im learning java from scratch now with the MOOC course at Helsinki University. I got somewhat stuck at exercise 68. The program is suppose to compare integer values of a list(array) together with user input. What i programmed is a method that return true if the user input number is already on the list, and false if its not.
What I said about story at the start: The commented out code is my initial code. This did not past the last test but in my head both the commented out code and the other code say basically the same
Error message (from last test):
"Answer wrong when parameter was list [0, 7, 9, -1, 13, 8, -1] and value 8 expected: false but was: true"
public static boolean moreThanOnce(ArrayList<Integer> list, int searched)
// if (list.size()==1) {return false;}
//
// for (int i = 0; i < list.size();i++ ){
// if (list.contains(searched))
//
// {
//
// return true; }
//
// }
//return false;
//
int counter = 0;
for (int num : list) {
if (searched == num) {
counter++;
}
}
if (counter >= 2){
return true;
} else {
return false;
}
}
I understand that there is something wrong, just cant seem to figure it out. Do you see why the last code would be accepted, but not the first (commented out one) ?
If any use, the rest of the code (not my work) is this:
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(3);
list.add(2);
list.add(7);
list.add(2);
System.out.println("Type a number: ");
int number = Integer.parseInt(reader.nextLine());
if (moreThanOnce(list, number)) {
System.out.println(number + " appears more than once.");
} else {
System.out.println(number + " does not appear more than once. ");
}
}
}
Code that is commented out guaranties only that if true there is at least one of occurance in array, maybe there are more but not guaranted. If function returns false thes may be 1 or no occurance.
Reason: If arrary os bigger than 1 it does not mean that there are 2 or more occurances of value you search for.
Posible solution: Add counter like uncommented code.
Your first algorithm has a few flaws, first you test for a length of one explicitly. Not null, and not an empty List. Second, you should prefer the List interface to the ArrayList explicit type. And finally, you need to consider the sublist offset by one of the current position when you call contains (clearly the list contains at least the current value).
I think you wanted something like
public static boolean moreThanOnce(List<Integer> list, int searched) {
if (list == null || list.size() < 2) {
return false;
}
int len = list.size();
for (int i = 0; i < len - 1; i++) {
if (list.get(i).equals(searched)
&& list.subList(i + 1, list.size()).contains(searched)) {
return true;
}
}
return false;
}
And, we can express that as generic method. Like,
public static <T> boolean moreThanOnce(List<T> list, T searched) {
if (list == null || list.size() < 2) {
return false;
}
int len = list.size();
for (int i = 0; i < len - 1; i++) {
if (list.get(i).equals(searched)
&& list.subList(i + 1, list.size()).contains(searched)) {
return true;
}
}
return false;
}
or, if you're using Java 8+, use a Stream and filter and then count like
public static <T> boolean moreThanOnce(List<T> list, T searched) {
if (list == null || list.size() < 2) {
return false;
}
return list.stream().filter(v -> v.equals(searched)).count() > 1;
}

Surrounded Character Method Java

I'm working on a java method that checks whether a character in an array of characters is surrounded by a character. Ex: abcdc, d is surrounded by c. Ex: abccc, has no letters that are surrounded. Here is what I have so far.
public static boolean surroundedCharacter(char[] letters){
boolean result = false;
for(char letter : letters)
if(letters[letter-1] == letters[letter+1]){
result = true;
}
return result;
} }
So I basically have a for each loop going through letter in letters and checks whether the letter before the position is equal to letter after the position. If it is, it means that the letter is surrounded and it should change result to true. The junit test says that the if statement is wrong, but I don't know how to fix it. Any help is appreciated.
You have to use an Integer for the index:
public static boolean surroundedCharacter(char[] letters){
boolean result = false;
for(int i = 1; i < letters.length - 1; i++) {
// You said that if the string is "abccc", should return false.
// So, we check if the previous or the next letter is different to
//the actual value of i
if((letters[i-1] == letters[i+1]) && (letters[i-1] != letters[i])) {
result = true;
}
}
return result;
}
Try this one:
public static boolean surroundedCharacter(char[] letters){
boolean result = false;
for( int i=1;i<letters.length-1;i++)
if(letters[i-1] == letters[i+1]){
result = true;
}
}
return result;}
You must use for loop instead of short for. Try this for loop:
for(int i = 1; i< letters.length-1; i++){
if(letters[i-1] == letters[i+1]){
result = true;
}
}
A Java foreach is designed to iterate element after element.
In case of need to get two distinct element at each iteration, you should use a classic for using a int value.
Besides, you don't need to have intermediary variable. When the condition is matched you can return true. Otherwise you return false after the loop.
At last, according to your needs :
Ex: abccc, has no letters that are surrounded.
you should accept the match only if the surrounded char differs from the chars that surround it.
public static boolean surroundedCharacter(char[] letters){
for(int i=1; i<letters.length-1; i++){
var beforeLetter = letters[i-1];
var afterLetter = letters[i+1];
if(beforeLetter == afterLetter && beforeLetter != letters[i]){
return true;
}
}
return false;
}

Java: Find if an array has at least 3 elements with the same value

Pretty much what the title said. I thought of using Sets and comparing sizes with the normal array but then if I had 2 elements with duplicates the Set size would be the same as having one element with 2 duplicates.
Any help on how to approach this would be much appreciated!
I think the fastest approach is the brute force one, i.e. traversing the array and count what you want to count. Each other implementation which you can call by a one liner must traverse the array as well, using a HashMap adds the overhead to fill and maintain the map, and you cannot stop iterating if you have found what you searched for.
With following private method you can use it also by a one liner call from your main code:
main()
{
String[] myArray = new String[] {
"Hello",
"Hello",
"Hello",
null,
null,
};
boolean gotIt = hasAtLeastThreeOccurences( myArray, "Hello");
myLog.debug( "gotIt: " + gotIt );
}
private <T> boolean hasAtLeastThreeOccurences( T[] aArray, T aValue)
{
int count = 0;
boolean isNull = (aValue == null);
for ( T t : aArray )
{
if ( isNull )
{
if ( t == null )
{
count++;
}
}
else
{
if ( aValue.equals( t ) )
{
count++;
}
}
if ( count >= 3 )
{
return true;
}
}
return false;
}
Assuming your array is a String Array (just as an example), you can call this method, if it return null then there is no 3 elements or more with the same value, else it will return the first element found 3 times or more
public String getRedundantItem(String... myArray) {
// Convert the array to List
ArrayList<String> myList = new ArrayList<String>(Arrays.asList(myArray));
// Look for the element which frequency is three or more
for (String item : myList) {
if (Collections.frequency(myList, item) > 2) {
return item;
}
}
// No element more than 2 times
return null;
}
Test Example:
public void test(){
String[] someData = {"stack","over", "flow", "stack", "stack"};
String[] otherData = {"stack","over", "flow", "stack", "flow"};
System.out.println(getRedundantItem(someData)); // prints stack
System.out.println(getRedundantItem(otherData)); // prints null
}
If an array have three elements with same value
we keep : element => number of occurence. difficult to do less or faster
List<String> array=Arrays.asList(new String[] {"aa","bb","cc","aa","bb","dd"}); // Complete with other tests
Iterator<String> it=array.iterator();
// Keep element => occurences
Map<String,Integer> occurences=new HashMap<String,Integer>();
while (it.hasNext())
{
String one_string=it.next();
if (occurences.containsKey(one_string))
{
int how_many=occurences.get(one_string);
if (how_many==2) return true;
// IF NOT
occurences.put(one_string, how_many+1);
}
else // NEW
occurences.put(one_string, 1);
}
// finally
return false;
This is an example using int variables, but the basic idea is that the value to be compared to the other values of the array is set to the first variable. Then as we find elements equal to the key, we increment a temporary count variable. If the temporary count variable is greater than the real count variable, then the real count variable is replaced by the temporary count variable. Once an unequal element is found, a new key value is set to the current element being iterated on and the temporary count variable is reset. This could be tinkered with, however, for example you can break out of the loop once the the temporary count reaches three. I'm not sure if this was what you were looking for, but enjoy.
int key = arr[0];
int tempCount = 0;
int realCount = 0;
for(int i = 1; i < arr.length; i++){
if(arr[i] == key){
tempCount++;
}
else{
key = arr[i];
tempCount = 0;
}
if(tempCount > realCount){
realCount = tempCount;
}
}
if(realCount >= 3){
boolean hasThreeOfTheSame = true;
//do stuff you want to do
}
EDIT: I now realize that the OP wanted a way to find if there were 3 of the same elements in an array despite the order. I misread this so my solution finds whether an array has 3 or more consecutive elements in a row (ex: [1, 1, 1, 2, 3] or [1, 2, 2, 2, 3]). I'm only going to keep this up because it may help someone out there.

Rewriting the whole String Class methods

My professor have given me a challenging homework, where the idea is to rewrite all the methods in the String classes without using String, StringBuilder, and Wrapper classes. This is for Intro to Java class. I already have some methods done but having a hard time with some other ones. This is for the main class only with no creation of any string inside.
What I have: a "data" as a char[] data for my "MyOwnString" object.
CompareTo method:
public int compareTo(MyOwnString rhs){
if (this.data == rhs.data){
return 0;
} else if (this.data > rhs.data){
return 1;
}
else {
return -1;
}
}
This one shows an error. My guess is that the rhs needs to be declare before being able to compare to any string being assigned to a MyOwnString object.
Since there is a compareTo method and a compareToIgnoreCase, then I would have to add a line to ignore the comparsion?
Update:
This is the code I went with for the compareTo method by creating own method using length of the array.
public int compareTo(MyOwnString cts){
int word1 = data.length;
int word2 = cts.length();
int result = 0;
for (int i=0; i<word1; i++){
for (int j=0;j<word2; j++){
if(word1 == word2){
result = 0;
}
else if (word1 > word2){
result = 1;
}
else {
result = -1;
}
}
}
return result;
}
Since you are not allowed to use String.compareTo()
and since java doesn't support > for your custom objects or char[] for that matter (e.g doesn't support operator overloading) you have to do it programmatically.
In other words you have the two char arrays and you have to loop through all the characters. You compare the first two characters from each of the char arrays (there you can use > or <) if they are == you compare the second two characters and so on.. till you find two characters that break the tie - you can then break your for loop and return the result as -1, 1. If they are tied on every character you return 0.
If you want to implement equals you could just call compareTo and optimize it a bit by checking the lengths of the strings. If they are different then of course the strings are not equal
Update: I am not sure if you ran your code above - try to compile your code and run it before you move forward. I believe it won't even compile.
Here is, I believe, a correct unchecked version. I could have mixed the -1 and 1s as always..
public int compareTo(MyOwnString cts){
int word1Length = ((MyOwnString)this).data.length;
int word2Length = cts.data.length;
for (int i=0; i < Math.min(word1Length,word2Length); i++){
if(this.data[i] == cts.data[i]){
continue;
}
else if (this.data[i] > cts.cts[i]){
return -1;
}
else if (this.data[i] < cts.cts[i]) {
return 1;
}
}
if (word1Length == word2Length){
return 0;
}
else if(word1Length < word2Length){
return 1;
}
else {
return -1;
}
}
public boolean equals(MyOwnString cts){
int word1Length = ((MyOwnString)this).data.length;
int word2Length = cts.data.length;
if (word1Length != word2Length){
return false;
}
else { // if they are equal
int comparison = this.compareTo(cts);
if (comparison==0){
return true;
}
else {
return false;
}
}
}
You can't compare char[] objects with the > operator, since it's not defined on them. You'll have to iterate over the char[] arrays and compare the characters yourself.
BTW, it's very easy to cheat in this assignment, since the code of the String class is available online.

When comparing array elements of two arrays, boolean result always returns true

I am having an issue when comparing elements in two int arrays. I am using a for loop to compare each element in the two arrays, and if the elements match, the boolean result is to return true, and if not, return false. The problem is that it is always returning true, regardless of whether they match or not.
Entire program here http://pastebin.ca/2626244
the loop:
boolean result;
int counter = 0;
//compares answers[] to key[]
for (int i = 0; i < size; i++) {
if (answers[i] == key[i]) {
result = true;
}
if (answers[i] != key[i]) {
result = false;
}
if (result = true) {
counter++;
}
}
System.out.println(counter+"/"+size+" questions are correct.");
As a result, "counter" is always the same value as the total elements ("size"). Even if both arrays contain completely different values, the result still will not be 0/size. It always seems to be size/size.
Am I comparing the arrays incorrectly (see full program), or is there just something wrong with my loop?
Use the comparison operator == to compare things, not the assignment operator =. But because result is a boolean already, just use the boolean itself.
Change
if (result = true) {
to
if (result)
= is use to assign the value and to compare the value use `==`
So need to change below code :
if (result == true) {
counter++;
}
or better solution is
if (result) {
counter++;
}

Categories