Boolean with loops to check an array - java

Write Java code for a loop that sets boolean variable isOrdered to true if the elements of a given array of ints called are in non-decreasing order, otherwise it sets isOrdered to false.
int i[] = { 1, 2, 3, 4, 5 };
int b = 0;
boolean isOrdered = false;
while (b < i.length) {
if (i[0] <= i[b]) {
isOrdered = true;
}
b++;
}
out.println(isOrdered);
Am I doing this correctly?

Let's see what is wrong.
if (i[0] <= i[b])
This is the main area which troubles me with your code. How are you checking if the next value you is lower/higher then i[b] you are only comparing values at index zero to index b!
Essentially your code would look like this in a loop.
/w int i[] = { 1, 2, 3, 4, 5 };
i[0] i[b]
1 1
1 2
1 3
...
you get the picture right? What you really need is to check the next value after b.
so the code would look like i[b] > i[b+1]
Honestly, you could probably make it work on how you initialized the order of isOrdered to true and false. I would first initialize it to true. Then the idea is to break out of whatever process you are doing if you find a fallacy in the question with a false. Please look at my examples for further references.
iterative
boolean isOrdered = true;
while(isOrdered && array.length - 1 > b){
if(array[b] > array[b+1]) isOrdered = false;
b++;
}
recursive
boolean isOrdered(int[] array, index){
if(index == array.length - 1) return true;
if(array[index] > array[index + 1]) return false;
return isOrdered(array, index + 1);
}
The recursive method for this is waaaaaaaaaay cooler.

No; you are only checking whether the first element of the array is smaller than or equal to at least one of the elements - including the first element itself, which will always be equal to itself, setting isOrdered to true no matter what the remaining elements are.
Hint #1: you should be comparing every element except the first one with the element immediately before it.
Hint #2: you should be optimistic and assume that the array is ordered, then search for a counter-example. As soon as you found a pair of elements that violate the ordering, set isOrdered to false and break out of the loop.

do a for loop on the size of the array to check if the next item is less then the current:
int arr[] = { 1, 2, 3, 4, 5 };
int b = 0;
boolean isOrdered = true;
for (int i = 0; i< arr.length - 1 ; i ++) {
if (arr[i] > arr[i+1])
{
isOrdered = false;
break;
}
b++;
}
out.println(isOrdered);

Related

Check whether the given number is fasinating or not

I am doing question on geeksforgeeks and i have come up with a question.
Given a number N. Your task is to check whether it is fascinating or not.
Fascinating Number: When a number(should contain 3 digits or more) is multiplied by 2 and 3 ,and when both these products are concatenated with the original number, then it results in all digits from 1 to 9 present exactly once.
Example 1:
Input:
N = 192
Output: Fascinating
Explanation: After multiplication with 2
and 3, and concatenating with original
number, number will become 192384576
which contains all digits from 1 to 9.
Example 2:
Input:
N = 853
Output: Not Fascinating
Explanation: It's not a fascinating
number.
Your Task:
You don't need to read input or print anything. Your task is to complete the function fascinating() which takes the integer n parameters and returns boolean denoting the answer.
Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
Constraints:
100 <= N <= 107
i have to complete the following fascinating function my code is returning error.
class Solution {
boolean fascinating(String q) {
// code here
int sum = 0;
for(int i=0; i<q.length(); i++){
sum = sum + Integer.parseInt(Character.toString(q.charAt(i)));
}
if(sum == 45){
return true;
}
return false;
}
}
When i saw the solution code i am not able to understand how it is doing the things.
class Solution {
boolean fascinating(String q) {
int A[] = {0, 0, 0, 0, 0, 0,
0, 0, 0, 0}; // to store count of every digit from '0' to '9'
int i, flag = 0;
char ch;
for (i = 0; i < q.length(); i++) {
ch = q.charAt(i);
A[ch - 48]++;
}
for (i = 1; i < 10; i++) {
// checking if every digit from '1' to '9' are present exactly once
// or not
if (A[i] != 1) {
flag = 1; // flag is set to 1 if frequency is not 1
break;
}
}
if (flag == 1)
return false;
else
return true;
}
}
Can anyone please explain this to me it will be very helpful.
class Solution {
fascinating returns a boolean, true/false to the question, "is it fascinating?"
boolean fascinating(String q) {
int A[] = {0, 0, 0, 0, 0, 0,
0, 0, 0, 0}; // to store count of every digit from '0' to '9'
Here you just initialize A as an array of zeroes, effectively (but not technically) 'empty'.
int i, flag = 0;
char ch;
Here you initialize i and flag at 0 and declare ch.
for (i = 0; i < q.length(); i++) {
ch = q.charAt(i);
A[ch - 48]++;
}
Here you have a for loop that goes through each character in q.
For example, let q = 192384576. This is not N, but rather N concatenated with (Nx2) concatenated with (Nx3).
So the for loop first sets ch = q.charAt(0). This is the first character, 1. Then it increments (adds one to) a certain index in A.
This index, much credit and thanks to Andreas for explaining this, is the difference of the Numeric ASCII value for ch and 48, which is the Numeric ASCII value for 0.
In Numeric ASCII:
0 = 48
1 = 49
2 = 50
3 = 51
and the rest.
Therefore, ch-48 will give the index in A that should represent ch. For example, when ch is 1, ASCII value of ch is 49 and 49-48 = 1. Therefore, it goes to A[1] and increments it.
Remember, arrays go [0,1,2,3, etc.] So it goes to [0, 0, 0, etc] and adds one to the second 0 -- A[1], thus making A = [0,1,0,etc].
It continues through each digit in q, and thus fills the array A.
for (i = 1; i < 10; i++) {
// checking if every digit from '1' to '9' are present exactly once
// or not
if (A[i] != 1) {
flag = 1; // flag is set to 1 if frequency is not 1
break;
}
}
Here, it iterates through A, set to length 10 because we are checking 0-9, and checks at each index if the value in that index is equal to 1. Hence,
if (A[i]!=1){}
The array should look like [1,1,1,1,etc].
If any of these indices is found not to be 1, it sets flag = 1 and immediately will break or exit the for loop.
if (flag == 1)
return false;
else
return true;
}
}
This final if-else statement checks whether flag is equal to 1. Remember, we only set it equal to 1 if the array is not uniformly filled with 1's, meaning the String q does not contain exactly one of each digit 0-9.
If flag is 1, return false, meaning it is not fascinating. Otherwise, it is fascinating. Thus, when fascinating, return true.

Why no out of bounds error on for loop (Java)

I'm doing a problem on codingbat.com and am confused with why this solution to the problem does not give an index out of bounds error. Wouldn't the first for loop search for an index that is beyond the length of the passed array?
Here's the problem:
We'll say that a value is "everywhere" in an array if for every pair of adjacent elements in the array, at least one of the pair is that value. Return true if the given value is everywhere in the array.
Here's my working solution:
public boolean isEverywhere(int[] nums, int val) {
boolean flag1 = true;
boolean flag2 = true;
for (int i = 0; i < nums.length; i += 2) {
if (nums[i] != val) flag1 = false;
}
for (int i = 0; i < nums.length - 1; i += 2) {
if (nums[i + 1] != val) flag2 = false;
}
return flag1 || flag2;
}
Thanks!
No. The test happens after i is incremented. So, once i is not less than the length of the nums array the loop stops. The second loop uses i + 1 at if (nums[i + 1] != val) which is why it needs to test that i is less than the length minus one.
Also you can make the method static (since it uses no instance state).
It wouldn't because while i += 2 is written after i < nums.length, the loop still checks that i is less than the given length(nums.length) before going onto the body of the loop even after 2 has been added on.

Why I am returning the wrong output?

I am not sure why I am returning false for the first test run as shown in the test table attachment. This was one of my assignments last semester and I never figured out how to solve it:/ My assignment was to:
Write the definition of a method , oddsMatchEvens, whose two parameters are arrays of integers of equal size. The size of each array is an even number. The method returns true if and only if the even-indexed elements of the first array equal the odd-indexed elements of the second, in sequence. That is if w is the first array and q the second array , w[0] equals q[1], and w[2] equals q[3], and so on.
Test table
My code was:
public boolean oddsMatchEvens(int[] w, int[] q) {
int count = 0;
for (int i = 0; i < w.length; i++) {
if (w[i] == q[i + 1])
count++;
if (count == (w.length - 1))
return true;
}
return false;
}
if (count == (w.length - 1))
return true;
This is wrong, since you have only w.length/2 indices which you have to compare.
You should just return false, if w[i] != q[i+1].
And you should increase i by 2, not by 1.
There are two problems with the code:
Firstly, it is clearly mentioned the two input arrays are of equal length and you have to compare them even index to odd index. So the corner case occurs when you are checking last item of first array with last+1 item of second array(which doesn't exist as arrays are of equal length.
Secondly, you have to check first array even with second array odd so increment should be i+=2 and not i++.
Correct code with optimization(if one check fails you can come out of loop):
public boolean oddsMatchEvens(int[] w, int[] q) {
for (int i = 0; i < w.length-1; i+=2) {
if (w[i] != q[i + 1])
return false;
else
continue;
}
return true;
}
public boolean oddsMatchEvens (int []w, int []q) {
for (int j = 0; j < w.length-1; j+=2) {
if (w [j] != q [j+1])
return false;
continue;
}
return true;
}

Remove Leading zeroes from an ArrayList of integers

I have an ArrayList of integers, I want to remove all the leading zeroes, code seems all right but U am getting unusual output.
Input:
0 0 0 1 9 9
Output:
0 1 9 9
Expected output:
1 9 9
public class Solution {
public ArrayList<Integer> plusOne(ArrayList<Integer> a) {
int flag=0;
//System.out.println(a.size()+" "+a.get(2));
for(int i=0;i<a.size();i++)
{
if(flag==0)
{
//System.out.println("val of i="+i+" "+a.get(i));
if(a.get(i)==0){
a.remove(i);
//System.out.println(flag);
}
else
{
//System.out.println("flag="+flag+" i="+i+" value"+a.get(i));
flag=1;
//System.out.println("flag="+flag+" i="+i+" value"+a.get(i));
}
}
if(flag==1)
break;
}
System.out.println();
return a;
}
}
You can remove the leading zeros by just searching for the first non-zero value, and then clearing the preceding sublist:
Iterator<Integer> it = list.iterator();
int i = 0;
while (it.hasNext() && it.next() == 0) {
++i;
}
list.subList(0, i).clear();
Removing a block of the list like this can be more efficient than removing the elements one at a time. e.g. if you removed them one at a time, ArrayList would shift all of the tail elements one position along each time, so the removal would be O(n^2).
The problem is that you're removing elements from the list while you're iterating over it. When i = 0:
a.remove(i);
removes the first element of the list and all elements are shifted: the 2nd becomes the 1st, etc. Then in the for loop, i is set to 1 after that. Hence, the second element is ignored: it became the first after the remove operation and i jumped over it because it was incremented.
The ugly solution would be to have i--; right after a.remove(i); to account for that shift.
However, a better solution would be to use a ListIterator:
public ArrayList<Integer> plusOne(ArrayList<Integer> a) {
ListIterator<Integer> it = a.listIterator();
while (it.hasNext() && it.next() == 0) {
it.remove();
}
return a;
}
This code retrieves it with listIterator(). While there are still elements and the next element is 0, we remove it with remove().
The problem is that i is incrementing while a.size() is shrinking. When i==0 you remove element 0 so all the values shift down 1, and next you remove element 1 but element 0 is also 0 so you skip this. i.e. you are only removing half the leading zeros.
BTW You should be able to confirm this by stepping through your code in your debugger. Helping you understand your code and find bugs is what it is for.
The simplest change is
for (int i = 0, max = a.size(); i < max; i++)
and
// you only want to check the first element.
if (a.get(0) == 0)
a.remove(0);
A more efficient way of doing this is to find the first element which is not 0 and return a sub list
public static List<Integer> trimLeadingZeros(List<Integer> list) {
for (int i = 0; i < list.size(); i++)
if (list.get(i) != 0)
return list.subList(i, list.size());
return Collections.emptyList();
}
Logic: anytime you see 0, loop from that point to the end, if inside that loop you see anything other than 0, break out from that loop.
Code:
//a is arrayList;
int count = 0;
for(int c = b; c < size; c++){
if(a.get(c) == 0 )
{
count++;
}
}
//size = 10,saw zero at 6th position that means leading zeros has to be 4,
// b is when I first saw 0
if(count == (size -b)) {}
else {
//else we just copy
ret.add(b, a.get(b));
}
Loop through the ArrayList and if you encounter 0 just remove it.
while (i < a.size() - 1 && a.get(i) == 0) {
a.remove(i);
}
Best Solution:
while(a.get(0)==0) { a.remove(0); }

(Java) Check array for increasing elements

I'm attempting to create a method that checks an array for increasing elements. True should be returned if all the elements are in increasing order. I get an out-of-bounds exception when I compare arr[i+1]. Any ideas on how I can make it work.
int[] one = {1,2,3,4,5};
public static boolean isIncreasing(int[]arr)
{
boolean z = false;
for(int i=0; i<arr.length;i++)
{
if(arr[i]<arr[i+1])
{
z = true;
}
}
return z;
}
Because in a list with n items there are only n-1 gaps between them.
Change to
for (int i=0; i<arr.length-1; i++)
(Also you might want to check whether starting with false and setting to true is the right way around).
You have two problems:
Your loop is one iteration too long: Because you are checking element i+1, i needs to finished incrementing one iteration earlier than a usual loop.
Your logic is flawed. Your loop will terminate the first time the check is true, so this array will pass: {1, 2, 0} when tested the first iteration tests 1 < 2 which is true, so return true - this is not what we want)
Fixing these two problems:
int[] one = {1,2,3,4,5};
public static boolean isIncreasing(int[] arr) {
for(int i=0 ; i < arr.length - 1; i++) { // finish at length - 1
if (arr[i] > arr[i+1]) {
return false; // found elements that are out of order - return false
}
}
return true; // nothing out of order found - return true
}
This kind of logic - with an early exit with false on problem and a final return of true - is very common and a good pattern to learn.
I suggest you write your method like this
public static boolean isIncreasing(int[]arr)
{
for(int i=1; i<arr.length;i++)
{
if(arr[i-1]>arr[i])
return false;
}
return true;
}
it will help
return the proper result (yours returns true when it should not)
consider out of bounds
avoid unnecessary looping
You get that exception as when (i+1)'s value becomes array.length. For example if you have an array of length 10, the elements indexes will be from 0,1,2...till 9. so either you have to check till i < arr.length - 1 or you can modify your logic accordingly.
You can use Java 8's IntStream.
import java.util.stream.IntStream;
public class Test {
public static boolean isIncreasing(int[] a) {
return IntStream.range(1, a.length).reduce(0, (acc, e) -> acc + (a[e - 1] <= a[e] ? 0 : 1)) == 0;
}
}

Categories

Resources