Java newbie here, I'm doing some practice about array on Codingbat haveThree. This is the question :"Given an array of ints, return true if the value 3 appears in the array exactly 3 times, and no 3's are next to each other." My code works on most situation but not all.
My code:
public boolean haveThree(int[] nums){
int counter=0;
for(int i=0; i<nums.length-2;i++){
if(nums[i]==3){
counter++;
}
if(counter==3){
return true;
}
}
return false;
}
Can anyone help me and tell me where I was wrong? How can I fix it?
"Given an array of ints, return true if the value 3 appears in the
array exactly 3 times, and no 3's are next to each other."
you're almost there, however, there are a few mistakes and incomplete implementations:
you didn't check if the value 3 is next to another value 3 (in which case we return false)
you return as soon as count == 3 even though you didn't search the entire array to conclude that there is no more 3s.
as it stands your loop condition i < nums.length-2 doesn't include the last two elements of the array within the search.
solution:
public boolean haveThree(int[] nums){
int counter = 0;
for(int i = 0; i < nums.length; i++){
if(nums[i] == 3){
counter++;
}
if(i + 1 < nums.length) {
if (nums[i] == 3 && nums[i + 1] == 3) return false;
}
}
if(counter == 3) return true;
return false;
}
Here is my solution for this, Have a look :)
public boolean haveThree(int[] nums) {
boolean check=true;
int count = 0;
for(int i=0;i<nums.length;i++){
if( nums[i]==3 && count++>0 && ( (i>0 && nums[i-1] == 3) || (i<nums.length-1 && nums[i+1] == 3) ) )
{//just checking if there are any consecutive 3's next to each other and counting them
check = false;
}
}
return (check && count==3);//count should be 3 and no 3's should be next to each other
}
Here is my solution, which passed all the tests on CodingBat:
public boolean haveThree(int[] nums) {
int counter3 = 0;
if (nums.length >= 5) {
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 3) {
counter3++;
}
}
}
if (counter3 == 3) {
for (int i = 0; i < nums.length - 4; i++) {
if ( (nums[i] == 3) &&
(nums[i+1] != 3) &&
(nums[i+2] == 3) &&
(nums[i+3] != 3) &&
(nums[i+4] == 3)
) { return true; }
}
}
return false;
}
Your loop does not lookup for each element you are missing the last 2 ones. Should be i < nums.length or use simply enhanced for so you don't have to save the current num on a value.
Check if no 3's are next to each other, because now you aren't checking that. I think the best salution to secure that no 3's are next to each other is to save the last number and compare it to the current one.
You can only be sure that the value 3 appears exactly 3 times in the array if you had seen the whole array so check that at the end and not in the loop.
public boolean haveThree(int[] nums) {
int lastNum = 0;
int counter = 0;
for (int currNum : nums) {
if (currNum == 3) {
counter++;
if (lastNum == currNum) {
return false;
}
}
lastNum = currNum;
}
return counter == 3;
}
A very Simple solution for this problem:
public boolean haveThree(int[] nums) {
int count = 0;
int preNum = 0;
for(int i =0; i<nums.length;i++){
if(nums[i]==3){
count++;
if(preNum ==3){
return false;
}
}
preNum = nums[i];
}
return count == 3;
}
Related
How i can check if all elements in the arrays are even or odd?
For the evens I try with this:
public boolean isEvens(int[] array) {
for (int i = 0; i<array.length;i++) {
if ( i % 2 == 0) {
return true;
}
else {
return false;
}
}
}
But there is error......
Thnx in advance !
You should check the array elements, not the array indices.
You shouldn't return true before checking all the elements of the array.
You can use a counter to count the number of odds or evens, or a boolean to determine if there are any odds or evens.
For example:
public boolean allEven(int[] array) {
for (int i = 0; i<array.length; i++) {
if (array[i] % 2 != 0) {
return false;
}
}
return true;
}
To check whether all are even or all are odd:
public boolean allEvenOrAllOdd(int[] array) {
boolean hasOdd = false;
boolean hasEven = false;
for (int i = 0; i<array.length; i++) {
if (array[i] % 2 == 0) {
hasEven = true;
if (hasOdd) { // has both odds and evens
return false;
}
} else {
hasOdd = true;
if (hasEven) { // has both odds and evens
return false;
}
}
}
return true; // either all elements are odd or all elements are even
}
Since java 8 it's a good practice to reduce code by using lambdas:
For even:
return Arrays.stream(array).allMatch( i -> i % 2 == 0);
for odd:
return Arrays.stream(array).allMatch( i -> i % 2 == 1);
Just check for an odd element, if not present then all are even.
public boolean isEvens (int[] array){
for (int i = 0; i < array.length; i++) {
if (array[i] % 2 != 0) {
return false;
}
}
return true;
}
You want to be comparing array elements at index i, and not i itself.
The check should be if (array[i] % 2 == 0)
Use Below code to for reference use a[i]
public static void isEvens() {
int [] array = {1,2,3,4,5};
for (int i = 0; i<array.length;i++) {
if (array[i] % 2 == 0) {
System.out.println("Even");
}
else {
System.out.println("Odd");
}
}
I would recommend using recursion for it, because with recursion the run time will be less than with loops, also it's some lines of code.
I made a code for doing this but with c#, I will post it below, it might help you, because the syntax in java is so similar to the syntax of c#.
public static bool isAllEvens(int[] a, int index)
{
if (index == 0 && a[index] % 2 == 0) return true;
else
{
if (a[index] % 2 == 0)
return true && isAllEvens(a, index - 1);
return false;
}
}
And to call this function just call it with two parameters(array, and array.length - 1 which is the last index).
Here is an example for calling this function:
int[] a = new int[4];
a[0] = 8; a[1] = 4; a[2] = 8; a[3] = 8;
Console.WriteLine(isAllEvens(a, a.Length - 1));
static boolean checkNum(int[] array) {
boolean bool = true;
for (int i = 0; i < array.length; i++) {
if (array[i] != 1 || array[i] != 4) {
return !bool;
}
i++;
}
return bool;
}
I have tried coding this a few ways but have not had any luck. How should I be doing it? it just needs to go through the array and find anything that isn't a 1 or 4, otherwise it should be true.
You have two problems in your code:
array[i] != 1 || array[i] !=4 will always evaluate to true. Any number is either not 1 or not 4.
You are looking for the condition array[i] != 1 && array[i] !=4, which says "the number is not 1 and not 4". Another valid alternative would be !(array[i] == 1 || array[i] == 4), which says "the number is not either 1 or 4". Which one you end up going with is up to your personal preference.
As others pointed out, the i++ inside the loop is redundant and makes the loop skip every second element.
This version should fix your problems:
static boolean checkNum(int[] array) {
for (int i = 0; i < array.length; i++) {
if (array[i] != 1 && array[i] != 4) {
return false;
}
}
return true;
}
You see how it was additionally possible to get rid of the variable bool?
Bonus: It is even more clear if you use a forEach loop instead of the for loop:
static boolean checkNum(int[] array) {
for (int i : array) {
if (i != 1 && i != 4) {
return false;
}
}
return true;
}
Logically, if the value at the current position is not 1 and is not 4 then return false.
static boolean checkNum(int[] array){
for(int i = 0; i < array.length; i++){
if(array[i] != 1 && array[i] != 4){
return false;
}
}
return true;
}
I would also recommend the for-each loop like
static boolean checkNum(int[] array){
for(int val : array){
if (val != 1 && val != 4){
return false;
}
}
return true;
}
You are only checking every second element because you are incrementing i twice.
Remove this line: i++;
You are already incrementing i in the for loop here: for(int i = 0; i < array.length; i++){
if(array[i] != 1 && array[i] !=4){
or
if(!(array[i] = 1 || array[i] =4)){
You've managed to conflate both of the correct tests that would work and produce one that doesn't work. Pretty easy to do, so always check your complex boolean expressions.
Good luck :)
I am working on a coding problem on a site called coding bat and can't figure out why one of the tests fails.
-Problem
"Given an array of ints, return true if .. 1, 2, 3, .. appears in the array somewhere."
http://codingbat.com/prob/p136041
public boolean array123(int[] nums) {
boolean result = false;
for(int i=0; i < nums.length-2; i++){
if (nums[i] == 1 && nums[i+1] == 2 && nums[i+2] == 3){
result = true;
} else{ result = false;}
}
return result;
}
All tests pass except for this:
array123({1, 1, 2, 3, 1}) → true but my code is actually returning false. Why?
You should return true immediately when you find one occurrence of the sequence.
public boolean array123(int[] nums) {
for(int i=0; i < nums.length-2; i++){
if (nums[i] == 1 && nums[i+1] == 2 && nums[i+2] == 3)
return true;
}
return false;
}
You need to return your result, or break out of the loop when you get a positive result. You've gotten other answers using return. Here's a version with the return statement at the end:
public boolean array123(int[] nums) {
boolean result = false;
for(int i=0; i < nums.length-2; i++){
if (nums[i] == 1 && nums[i+1] == 2 && nums[i+2] == 3){
result = true;
break;
}
}
return result;
}
You're code fails because result is set correctly to true on the next to last iteration, but back to false on the last iteration. If you didn't care about optimization you could also simply just delete the else part of your if-statement.
public boolean array123(int[] nums) {
boolean result = false;
for(int i=0; i < nums.length-2; i++){
if (nums[i] == 1 && nums[i+1] == 2 && nums[i+2] == 3){
result = true;
}
}
return result;
}
If it ever comes across your sequence then it sets result to true, and it will never be able to go back to false. Although you will be running to the end of the number series - not optimal.
You don't need the else statement, you already initialize result to false. Here is the code after the fix.
public boolean array123(int[] nums) {
for(int i=0; i < nums.length-2; i++){
if (nums[i] == 1 && nums[i+1] == 2 && nums[i+2] == 3){
return true;
}
}
return false;
}
boolean result = false;
for(int i=0; i <= nums.length-2; i++){
if (nums[i] == 1 && nums[i+1] == 2 && nums[i+2] == 3)
result = true;
}
Only this will suffice. You've an else statement placed wrongly. On finding 1,2,3 it sets result=true but then it moves to 2,3,1 and there it goes in else and sets result=false again.
This the question I must answer-
Given an array of ints, return true if the value 3 appears in the array exactly 3 times, and no 3's are next to each other.
haveThree({3, 1, 3, 1, 3}) → true
haveThree({3, 1, 3, 3}) → false
haveThree({3, 4, 3, 3, 4}) → false
This is my solution:
public boolean haveThree(int[] nums) {
int count = 0;
for (int i=0;i<nums.length-1;i++) {
if (nums[i] == 3 && nums[i+1] ==3) {
return false;
}
else
if ((nums[i]==3 && nums[i+1]!=3)||(nums[i]==3 && nums[i+1]!=3)) {
count ++;
}
}
return count ==3;
}
It fails for some tests. For example {3,1,3,1,3} should result in true being returned; however, false is returned and I can't figure out why.
You need to loop all the way to nums.length to count all occurences. Also, there is no need for the else statement. I would do something like:
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 3) {
if ((i < nums.length - 1) && (nums[i + 1] == 3)) {
return false;
}
count++;
}
}
It fails for that example because you don't check the last index, presumably to fix the out of bounds error for checking if two 3's are next to eachother. Also the or condition in your second if statement is redundant.
public boolean haveThree(int[] nums) {
int count = 0;
for (int i=0;i<nums.length-1;i++) {
if (nums[i] == 3 && nums[i+1] ==3) {
return false;
}
if ((nums[i]==3)) { //removed redundant condition and doesn't need to be an else
count ++;
}
}
// check the last index, you've already ensured the second to last is not also a 3
if(nums[nums.length-1] == 3) {
count++;
}
return count == 3;
}
Because you're not comparing the final value, you can't tell if the last array element is a three or not. What I would do (to guarantee going through each element as needed) is add a flag boolean that lets you know if the previous value was a three or not (resetting it back to false if the current value is not three).
My example:
public boolean haveThree(int[] nums) {
int count = 0;
boolean flag = false;
for(int i = 0; i < nums.length; i++) {
if(nums[i] == 3) { // The current value is a 3
if(flag) { // Previous value was a 3, rejecting.
return false;
}
else { // We have another 3, set the flag
count++;
flag = true;
}
}
else { // Since this wasn't a 3, we can set the flag back to false
flag = false;
}
}
return count == 3;
}
The for statement also has another form designed for iteration through Collections and arrays, and can be used to make your loops more compact and easy to read.
boolean haveThree(int[] nums) {
int count = 0, prevNum = 0;
for (int i : nums){
if (i==3) {
count++;
if (prevNum == i)
return false;
}
prevNum = i;
}
return count == 3;
}
As some people have already pointed out, you are not counting all the 3s that are present in the array. Your loop ends just before the last element in order to avoid ArrayIndexOutOfBoundsException.
It is a logical error. Your code fails for the test case that you've mentioned because first if condition returns false when i = 0. I wrote the following code snippet when I practiced. Hope it helps.
public boolean haveThree(int[] nums) {
int threeCount = 0;
boolean successive3s = false;
for (int i = 0; i < nums.length; i++) {
if (nums[i] == 3) {
threeCount++;
}
if (nums[i] == 3 && (i + 1) < nums.length && nums[i + 1] == 3)
successive3s = true;
}
return (!successive3s && threeCount == 3);
}
public boolean haveThree(int[] nums) {
int count = 0;
if(nums.length >= 1 && nums[0] == 3)
count++;
for(int i = 1; i < nums.length; i++) {
if(nums[i - 1] == 3 && nums[i] == 3)
return false;
if(nums[i] == 3)
count++;
}
return count == 3;
}
I made a trailing counter for mine.
public boolean haveThree(int[] nums)
{
//We check to see if it is possible to get 3 without being in a row.
//In this case, it is the smallest at five chars
//E.G 31313, so if we have any size less than this, we know it to be false.
if (nums.length >= 5)
{
//Create a counter to track how many 3's we have in a row,
//as well as how many we have total.
int counterInRow = 0;
int counterThrees = 0;
//Check for 3's
for (int i = 0; i < nums.length; i++)
{
//If a number is 3, we increment both;
if (nums[i] == 3)
{
counterInRow++;
counterThrees++;
}
//Otherwise, we reset the amount in a row to 0;
else
{
counterInRow = 0;
}
//If we have 2 or more in a row, we return false.
if (counterInRow >= 2)
{
return false;
}
}
//Return if the amount of the counterThrees equals 3 or not.
return (counterThrees == 3);
}
//If we have less than 5 characters, it isn't possible. We then,
//Return false;
else
{
return false;
}
}
This is, I imagine, a really simple problem to solve however I just can't figure it out.
An array contains a list of integers and I want to return true if every number 'x' in the array is followed by the number 'y'.
So arrays with {x,3,4,y} or {x,x,y,4,5} or {5,8,x,x} would be false.
Whereas arrays with {x,y,4,1} or {x,y,5,1,x,y} would be true.
This is what I have tried so far:
for (int i = 0; i < nums.length-1; i++)
{
if (nums[i] == x && nums[i+1] == y)
{
return true;
}
else
{
return false;
}
}
return false;
My code however will only work for the first two elements in the array (so 0 and 1). It won't detect any integers further down in the array, so how do I do this?
Thank you.
I want to return true if every number 'x' in the array is followed by the number 'y'.
You need to get rid of the else and modify the checks like so:
for (int i = 0; i < nums.length - 1; i++)
{
if (nums[i] == x && nums[i + 1] != y)
{
return false;
}
}
return true;
Caveats:
This returns true if x is not present in the array. It's unclear from the question whether this is the behaviour you want.
This does not check whether x is the last element of the array. Again, it's not entirely clear what you'd expect to happen if it is.
When the code reaches a return statement it stops executing the function and returns the specified value, that's why your for is only executed once.
Since you want the condition to apply to ALL the elements in the array, you have to return false when you find a 2 that isn't followed by a 3. If the 2 is followed by a 3, you just keep checking the next position.
Like this:
for (int i = 0; i < nums.length-1; i++)
{
if(nums[i] == 2 && nums[i+1] != 3)
{
return false;
}
}
return true;
for (int i = 0; i < nums.length-1; i++) {
if (nums[i] == 2 && nums[i+1] != 3) {
return false;
}
}
return true;
This code will return False iff the 'x' number is not followed by 'y'.
for (int i = 0; i < nums.length-1; i++)
{
if(nums[i] == 2 && nums[i+1] != 3) {
return false;
}
}
return true;
for (int i = 0; i < nums.length-1; i++)
{
if(nums[i] == 2 && nums[i+1] == 3)
{
return true;
}
}
return false;
Your Code is returning in the first iteration always. because you have return written there in both If and else block.
remove the else case or just the return; from else case if there is any other logic inside.
int x = 2;
int y=3;
for (int i = 0; i < nums.length-1; i++) {
if (nums[i] == x && nums[i+1] != y) {
return false;
}
}
return true;
If you do not have x in the array, it will return true. and if you have any x that does not have y after it, it will return false.
Try out Following
boolean flag = false;
for (int i = 0; i <= (nums.length-1); i++) {
if(nums[i] == x) {
if (i == (nums.length-1)) {
if(nums[i] == x) {
flag = false;
}
} else {
if(nums[i+1] == y) {
flag = true;
} else {
flag = false;
break;
}
}
}
}
return flag;
You can try out the following:
if(nums[nums.length - 1] == x)
{
return false;
}
else
{
boolean flag = false;
for(i = 0; i < nums.length - 1; i++)
{
if(nums[i] == x)
{
if(nums[i + 1] == y)
{
flag = true;
}
else
{
flag = false;
break;
}
}
}
return flag;
}