How to find occurrence of element more than 2 in Arrays - java

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!

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.

Checking to see if array is full

If I have an Array Candy[] type;
and type = new Candy[capacity];
if the Array is full is capacity = type.length ?
Since you are using array, the size of array is determined during compilation. Thus if your intention is to check whether current array's index has reached the last array element, you may use the following condtion (possibly in a loop) to check whether your current array index is the last element. If it is true, then it has reached the last element of your array.
Example:
int[] candy = new int[10]; //Array size is 10
//first array: Index 0, last array index: 9.
for (int x=0; x < candy.length; x++)
if (x == candy.length - 1)
//Reached last element of array
You can check the size of the array by using:
candy.length
You check whether it is last element by using:
if (currentIndex == candy.length - 1) //Where candy is your array
Make sure you are using double equal == for comparison.
Single equal = is for assignment.
Java creates an array with capacity count of references to the Candy instances initializing array with the nulls. So any array in java is full and
type.length == capacity
is always true.
type = new Candy[capacity] is equivalent to
type = new Candy[] {null, null, null, /* capacity count of nulls */, null};
In the example you show type.length will always be equal to capacity(after the initialization). Also your array will always have capacity elements but they will initially all be null.
If you want to check if array is full (no null elements), use something like this:
//1
boolean b = false;
//2
for(int i = 0; i < type.length; i++){
if(type[i] == null){
b = true;
}
}
//3
if(b == false){
System.out.println("Array is full");
}
What does it mean?
//1. At beginning you have one boolean (b) which is false.
//2. If any value in your array is null, b will be true.
//3. You check if value of b is still false. If it is, that means that b is never changed, so array is full (no null elements) .

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.

ArrayList sorting longest sequence

I'm not asking anyone to solve this for me, I just need a little push because I have no earthly idea on where to begin with this. All I know is that I should implement collections in this and have a sort.
Write a method longestSortedSequence that returns the length of the longest sorted sequence within a list of integers. For example, if a variable called list stores the following sequence of values:
[1, 3, 5, 2, 9, 7, -3, 0, 42, 308, 17]
then the call: list.longestSortedSequence() would return the value 4 because it is the length of the longest sorted sequence within this list (the sequence -3, 0, 42, 308). If the list is empty, your method should return 0. Notice that for a non-empty list the method will always return a value of at least 1 because any individual element constitutes a sorted sequence.
Assume you are adding to the ArrayIntList class with following fields:
public class ArrayIntList
{
private int[] elementData;
private int size;
// your code goes here
}
Iterate the array, and increment the counter variable if the next element you process is larger then the last one.
If the next element is smaller, or the end of the array is reached, store the current counter value if its larger then the currently stored max value and reset the counter variable with 0.
Pseudo code:
Variable X: first item of list
Variable Y: length of sequence (initial: 1)
Variable Z: max length occurred (initial: 0)
Loop over the list starting from 2nd index
if item is higher than X
set X to item
add 1 to Y
else
if Y is higher than Z
set Z to Y
end if
set X to item
set Y to 1
end if
End-Loop
This method will restart the counter every time the sequence 'restarts', aka: it's no longer sorted. While the list is sorted it just adds 1 for each element that is in sorted order.
When the sequence stops being ordered it checks if the current sequence is longer than the longest sequence length so far. If it is, you have your new longest sequence.
Have you thought about a for loop and if else statements? i hope this doesn't give it away. think one element at a time.
Loop over your array and compare i element with i+1 element. Make a counter. While i is less than i+1 increment the counter, when i is greater than i+1 reset the counter.

How to check ALL elements of a boolean array are true

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"

Categories