How to check ALL elements of a boolean array are true - java

I have a boolean array whose size depends on the size of a randomly selected string.
So I have something like this:
boolean[] foundLetterArray = new boolean[selectedWord.length()];
As the program progresses, this particular boolean array gets filled with true values for each element in the array. I just want to print a statement as soon as all the elements of the array are true. So I have tried:
if(foundLetterArray[selectedWord.length()]==true){
System.out.println("You have reached the end");
}
This gives me an out of bounds exception error. I have also tried contains() method but that ends the loop even if 1 element in the array is true. Do I need a for loop that iterates through all the elements of the array? How can I set a test condition in that?

Using the enhanced for loop, you can easily iterate over an array, no need for indexes and size calculations:
private static boolean allTrue (boolean[] values) {
for (boolean value : values) {
if (!value)
return false;
}
return true;
}

There is a Java 8 one-liner for this:
boolean allTrue(boolean[] arr) {
return IntStream.range(0, arr.length).allMatch(i -> arr[i]);
}

boolean[] foundLetterArray = new boolean[5];
The memory allocation for the abow array is like
foundLetterArray[0],foundLetterArray[1],foundLetterArray[2],foundLetterArray[3],foundLetterArray[4]
Array index starts with 0 and the total memory count is 5 and the last array index is 4.
You are trying to get index 5 that is foundLetterArray[5] which does not exist. That's why you are getting the ArrayIndexOutofBoundsException
if(foundLetterArray[selectedWord.length()-1]==true){
System.out.println("You have reached the end");
}

Arrays in Java starts from index 0 and last index is always [array.length()-1]
As you are checking for foundLetterArray[selectedWord.length()] ,its giving you a array out of Bound Exception try foundLetterArray[selectedWord.length()-1]
Like:
if(foundLetterArray[selectedWord.length()-1]){
System.out.println("You have reached the end");
}

Indices in java, as well as most programming languages, are 0-based, meaning that individual elements in an array with n elements have indices 0, 1, 2, ..., n-1. The last element in an array is always at index array.length - 1.

Array index start from 0 so last index is always 1 less then array length so here you are trying to access last index + 1 by doing foundLetterArray[selectedWord.length()] this so it is throuing ArrayIndexBoundEception use array.lastIndex() method or subtract 1 form length.
Implementing this foundLetterArray[selectedWord.length()-1] You must take care about one thing if your array does not contains any elements then selectedWord.length() return 0 and again you will get same exception so Its good to check lengh before doing this foundLetterArray[selectedWord.length()-1].

do this
public boolean allTrue(boolean[] array) {
for (boolean b : array) {
if (!b) {
return false;
}
}
return true;
}
There is no 'one line' way of knowing whether all of the elements of an array meet a certain condition (there are libraries that take care of the looping for you, but you still need to write the condition). Querying array[x] will only tell you about the xth item in that array, so for your question you need to check every item.
Also, as other people have pointed out, array indices are 0-based, so the first element is at array[0] and the last at array[array.length() - 1].
My example uses an alternate looping construct known as for-each. This is appropriate when you don't need to modify the array contents, you only need to read from them. It avoids any messing around with indices.

You do the check only for last element in the array ( and do it wrong, above is described why ).
In order to get if arrays contains only true values you should check all of them.
boolean allAreTrue = true;
for (boolean val : foundLetterArray) {
allAreTrue = allAreTrue && val;
}
// at this line allAreTrue will contain true if all values are true and false if you have at least one "false"

Related

Which recursive method could be used to evaluate numbers in a list?

I'm strugling learning recursive methods. Could use some advice and a cheer-up :D
Lets say I have a set of numbers in an array, and I want to use a recursive method to evaluate numbers in this set, and by evaluation I mean that our program needs to find zeros in this set, and as a result it should print out position of the last zero in given array.
int a[] = {2,3,4,5,0,1,2,0,5,0};
In case if array above is being evaluated by a recursive method, the program will evaluate each number and, if zero is found, it will save it's position in a variable, AND THEN MOVE ON REPEATING ITSELF until the end of the array. So first zero is at "4" and so on, but the output will show only the poistion number of the last zero in given array.
I kind of got the first part of this code going, but my recursion stops as soon as it finds a zero and just gives out a boolean type variable.
public static boolean checkNum(int i) {
if (i < a.length) {
if (a[i] != 0)
return checkNum(i+1);
else return false;
}
return true;
}
this block of code checks numbers in our set and returns boolean type variable true in case if it never found any zeros.
next method may be similar, but I dont know how to store the position number as a variable with a possibility to print it out in the end of my program. Is there any way to get int i out of the recursive method when it's done repeating itself? Because as far as I understand it is the same as a position number in an array, which I need to print out.
You have two options. Either continue until the end of the list and then return the last index found ... or iterate backwards across your list and use your logic as-is.
You're currently iterating forward, so might as well cover that workflow first.
Since your goal is to figure out the position, your method needs to return an int, not a boolean.
Since you need to return the last index of a zero, that means you need to track the previously found index.
Since you want to iterate to the end of the list, your end condition needs to be a position < length check.
static int[] a; // some array we're checking
public static int checkNum(int index, int lastZero) {
// End condition. If we've finished iterating across the array, return the
// index of the last zero we found.
if (index >= a.length) {
return lastZero;
}
// Check if we've found a zero at the current position.
if (a[index] == 0) {
lastZero = index;
}
// Continue traversing the list.
return checkNum(index+1, lastZero);
}
You'd call this by passing in a negative number as your initial lastZero index:
int lastZeroIndex = checkNum(0, -1);
That way you know that if you end up with a positive number, you have found the last index. Otherwise if you're left with a negative number, there were no zeroes in the array.
A simpler method would simply be to iterate backwards over the array and stop as soon as you find a zero.
We still return an int instead of a boolean because we want to know the index.
Otherwise your method signature remains the same.
static int[] a; // some array we're checking
public static int checkNum(int index) {
// End condition. We've reached the beginning of the array and never found a zero.
// Return a -1 to indicate this.
if (index < 0) {
return -1;
}
// If index is >= a.length, we don't want an index out of bounds...
if (index >= a.length) {
return checkNum(a.length - 1);
}
// Check if we've found a zero at the current position. If we have, return
// the current index.
if (a[index] == 0) {
return index;
}
// Continue traversing the list backwards.
return checkNum(index-1);
}
You'd call this by passing a.length - 1 as your parameter. That's the last valid index in the array, so it's our starting point when we iterate backwards.
int lastZeroFound = checkNum(a.length - 1);
If lastZeroFound is negative (eg. -1), then you found no zeroes.

How to find occurrence of element more than 2 in Arrays

For Example:
int[] array={1, 1, 2, 2, 2, 3, 3}
the array is sorted and each element of array occurred more than two times and return true.
if int[] array={1, 2, 2, 2, 3, 3} the array is sorted but 1 occur in array only one time should return false.
Following are the code for checking the array is sorted or not , if array is sorted return true if not return false:
public class Second {
public static void main(String[] args){
int[] array = {7,6,3,4,5};
boolean sorted = true;
for(int i = 1; i < array.length; i++) {
if(array[i-1] > array[i]){
sorted = false;
break;
}
}
System.out.println("Sorted: " + sorted);
}
How i achieve my second task in the above code for occurrence of element more than two times should return true, otherwise return false.
This algorithm handles both requirements at the same time, with a single pass through the array:
If the array is empty, return whatever the appropriate flag is (true or false)
Otherwise (the array isn't empty):
Set previousValue to the array's first entry
Set previousRepeats to false
Loop through the array starting with the second entry:
Get the current value as value
If value is equal to previousValue, set previousRepeats to true and start the next loop iteration
Otherwise, if value is less than previousValue, return false — the array is not sorted
Otherwise, we know value is greater than previousValue:
If previousRepeats is false, return false — you have a value that isn't repeated
If that didn't happen, set previousValue to value and set previousRepeats to false, and start the next loop iteration
When you reach the end of the loop, return the value of the previousRepeats flag (to handle the final entry)
If you need to know the index of the bad entry, here's a slight modification to the above (changes in bold):
Let's assume a return value of -1 means "all is good", and a return value of 0 or more is the index of the first "bad" entry in the array:
If the array is empty, return whatever value is appropriate for a blank array (it's up to you)
Otherwise (the array isn't empty):
Set previousValue to the array's first entry
Set previousRepeats to false
Loop through the array starting with the second entry, keeping track of the array index in index
Get the current value as value
If value is equal to previousValue, set previousRepeats to true and start the next loop iteration
Otherwise, if value is less than previousValue, return index — the array is not sorted as of this value
Otherwise, we know value is greater than previousValue:
If previousRepeats is false, return index - 1 — the previous entry's value is not repeated, so the "bad" entry is the previous one
If that didn't happen, set previousValue to value and set previousRepeats to false, and start the next loop iteration
When you reach the end of the loop, if previousRepeats is true, return -1; otherwise, return index - 1 to indicate that the final value in the array is not repeated
Write a nested loop to check each element in the array and check it against all the other elements in the array, increment a counter every time you come across the same value. At the end of the inner loop, check if the counter is greater than or equals to 2. If not break the loop.
set counter to 0
Repeat i till end of array{
Repeat j till end of array{
check if array[j] == array[i]{
increment the counter
}
}
check if counter<2{
break;
}
}
check if counter<2{
return false;
}
else{
return true;
}
Have a method that accepts two parameters: your array and the int/entry entry you are looking for multiple occurrences of. Loop through the array and simply keep track of whether the current array index's element == the one you are looking for (your second parameter). If so, increment a counter. If the counter ever exceeds the value you want, return true. Otherwise return false after the loop.
That should help you write the code yourself!

Understanding Java sorting

I'm still learning about sorting and Arrays. Came up with this code which does sorting letters or numbers on ascending order but I really don't get the last part where System.out.println(SampleArray[i]);. Why is it SapleArray[i]? can someone enlighten me please.
public class TestClass {
public static void main(String[] args) {
String SampleArray[] = {"B","D","A","R","Z"};
Arrays.sort(SampleArray);
for (int i=0; i < SampleArray.length; i++) {
System.out.println(SampleArray[i]);
}
}
}
SampleArray refers to the whole array - here containing five strings.
SampleArray[0] refers to the first item in the array (here the string "B").
for (int i=0; i < SampleArray.length; i++) {
System.out.println(SampleArray[i]);
}
lets i take the values 0, 1, 2, 3, 4 one after another, so you print out first SampleArray[0]and then SampleArray[1] and so on until all the items have been printed.
You are trying to print an array, which is an ordered collection of items.
SampleArray[i] inside the loop lets you access one element at a time, in order.
More specifically, i takes on the values 0 through 4 in this case.
SampleArray[0] would give you the first element of SampleArray, because Java uses zero-based indexing for arrays.
Going through your code:
first you create a String array with those letters as element, which are saved like this: element 0 of array = B, element 1= D, etc. (in Arrays the counting always begin by 0 and not by 1).
Then it sort it in ascending order.
The for loop is there to print the sorted array, it iterate through the array beginning by element 0, until it is at the last element of the Array and it print these element.
The for loop does something over and over again.
The first part of the for loop, int i = 0 sets up a variable.
The second part i < SampleArray.length is the 'terminating condition' - it's the condition that has to remain true before each iteration of the loop.
The last part i++ is what happens after each iteration - i gets incremented.
So we are printing each element within SampleArray. i goes between 0 and the one less than the number of elements in the array. (e.g. if the array contained 4 elements, i would be 0 to 3, which is what we want).
And in the body of the loop, the [i] bit selects that element from SampleArray, and that is the value that gets printed on each line.
Another way of looking at it: SampleArray supports the [] operator, which when applied, will return an element from the array.

JavaArray Index out of Bounds exception w/ for loop

I am getting an array index out of bounds exception while iterating over an array through the for-loop. Can someone tell me why this is happening it I have set the boolean in the for-loop to be i
public static boolean verify(int [] seq ){
for (int i=0; i<seq.length; i++){
//If the number is even, the next number
//must the half the previous number
if (seq[i] %2==0){
if (seq[i+1] != (seq[i]/2)){
return false;
}
}
//If the number is positive, the next number
//must be 3 times + 1 the previous number
else if (seq[i] %2!=0){
if (seq[i+1] != ((seq[i])*3+1)){
return false;
}
}
}
}
The problem is when you access index i+1. If i is the last possible value (seq.length - 1), then i+1 is one beyond the end of the array, resulting in an ArrayIndexOutOfBoundsException.
Stop your for loop one iteration earlier by modifying your condition to be:
i < seq.length - 1
You will face exception for the maximum value of i bcoz you are increasing the value by 1 to find the index value.
if (seq[i] %2==0){
if (seq[i+1] != (seq[i]/2)){
---------------------^
return false;
}
}
You're trying to access position i+1 or the Array. Since your for loop goes until the last element, you'll try to access 1 position after the last element, what causes the Out Of Bounds exception.
You are iterating over all elements in the array, but checking element seq[i + 1] for i == seq.lenth - 1 will always cause the exception. The last number is fully constrained by your conditions, so no need to check it. Make your loop run as follows: for (int i=0; i <seq.length - 1; i++)
This:
if (seq[i+1] != (seq[i]/2)) {
cannot access an element beyond the end of the array, when i is seq.length - 1.
Another line like that is down in the else branch.
Its quite obvious , when you are passing an array (i.e. array contains 10 elements) and operating inside loop that correct.But when you are accessing seq[i+1] , there might be the you are accessing the index which is not available in the array.
When the i value reaches at 10 and you are trying to access i+1 , but this index is not in array (as we know array size is 10)
So , its caused this exception.
Hope it will help you.

How to check if an array has two different pairs of matching values?

public static boolean hasTwoPair(int[] arrayOfInts){
}
The method is supposed to return true if it can find two different pairs of matching int values. So if the array was {2,2,4,7,7}, it should return true because it has two 2s and two 7s.
It only applies to different pair values though. If it was {2,2,2,2,5}, it would return false because they are not different pair values.
EDIT: This is what I have so far for the body of the method:
boolean pairFound = false;
int pairValue;
for(int s = 0; s < arrayOfInts.length - 1; s++){
pairValue = arrayOfInts[s];
for(int c = s + 1; c < arrayOfInts.length; c++){
if(pairValue == arrayOfInts[c])
pairFound = true;
}
}
return false; //placeholder
I'm not sure where to go from here.
Since you haven't actually tried any code, I'll give a description of how to solve this problem, but no actual code.
Start with a boolean like pairFound that's initialized to false and change to true when you find your first pair. Additionally, you'll need an int (pairValue to keep track of the value of the first pair found (if you found one).
Iterate through, looking for a pair. If you find a pair, and pairFound is false, set pairFound to true, and set pairValue to the value of your first found pair. Now keep iterating through.
If you find a pair and pairFound is true and the pair is != pairValue, then return true;. If you iterate through everything and haven't returned true yet, then you can return false.
Based on your updated question, you're pretty close.
boolean pairFound = false;
int pairValue = Integer.MIN_VALUE;
//or some value that arrayOfInts will never have based on context
for(int s = 0; s < arrayOfInts.length - 1; s++){
if(arrayOfInts[s] == pairValue) {
continue;
}
for(int c = s + 1; c < arrayOfInts.length; c++){
if(arrayOfInts[s] == arrayOfInts[c]) {
if(arrayOfInts[s] != pairValue) {
if(pairFound) {
return true;
}
pairValue = arrayOfInts[s];
pairFound = true;
break;
}
}
}
}
return false;
This task asks you to build a list of counts:
Create a data structure (say, a Map<Integer,Integer>) containing a count for each number from the array.
Go through the map, and count the number of entries with the count of two and above.
If you counted two or more items, return true; otherwise, return false.
The counts for your first example would look like this:
V #
- -
2 - 2
4 - 1
7 - 2
You have two items (2 and 7) with counts of 2, so return true.
The counts for your second example look like this:
V #
- -
2 - 4
5 - 1
There is only one item with the count above 2, so return false.
If you use a HashMap, this algorithm produces an answer in O(n).
Sort the array. Then look for the first two consecutive values that match. If found, skip to the first entry that is different from the matched pair and repeat. If you reach the end of the array before either the first or second search succeeds, return false.
You don't need to sort the array, that would give O(n*log(n)) complexity. But your current solution is even worse since it's yielding O(n^2) complexity. But you also don't need a HashMap. A Set and an integer is enough:
For each array element do
Check: is the element already in the set?
If not put it into the set
If yes check if it's equal to your last found Int pair (yes, use a boxed Int, not a primitive int here, to be able to initialize it with null)
If it's equal continue
If it's not equal
If the last found pair is null set it to elements value
Otherwise you're done and you have at least 2 different pairs
If you iterated over the list without reaching the last condition you don't have 2 different pairs
As for the Set implementation I would recommend a HashSet
There is more to say here though. If you implement it like this you make no assumption about integers and indexable arrays. All you need is a list of comparable elements. So you could make the signature of your method much more generic:
public static boolean hasTwoPair(Iterable<E> iterable)
But since arrays don't support generics and the Iterable interface every client of this method would have to transform Array parameters to an Iterable with the asList() method. If that's too inconvenient you can provide another method:
public static <T> boolean hasTwoPair(T[] array)
In general it's a good idea to use the most generic type possible when you design API's (also see Item 40 and 52 in "Effective Java, Second Edition")

Categories