I was doing a simple fizzbuzz problem in Java and encountered a bug that I cannot find for the life of me. The "fizz" is not added to the result unless the number is also divisible by 5.
actual: ["1","2","3","4","buzz","6","7","8","9","buzz","11","12","13","14","fizzbuzz"]
expected: ["1","2","fizz","4","buzz","fizz","7","8","fizz","buzz","11","fizz","13","14","fizzbuzz"]
public List<String> fizzBuzz(int n) {
List<String> result = new ArrayList<>();
for (int i = 1; i <= n; i++) {
String word = "";
if (i % 3 == 0) {
word += "fizz";
} if (i % 5 == 0) {
word += "buzz";
} else {
word = String.valueOf(i);
}
result.add(word);
}
return result;
}
You have two if block instead of one.
if (i % 3 == 0) {
word += "fizz";
} if (i % 5 == 0) {
word += "buzz";
} else {
word = String.valueOf(i);
}
In the above block first condition is if the i is divisible by 3 and immediately it will check if the i is divisible by 5 else it will execute the else part.
In case of i being divisible 3 and not divisible by 5 you will always get the i value.
for your requirement you could do as follows
if (i % 3 == 0 && i % 5 == 0) {
word = "fizzbuzz";
} else if (i % 3 == 0) {
word = "fizz";
} else if (i % 5 == 0) {
word = "buzz";
} else {
word = String.valueOf(i);
}
This way first you are check if the value is both divisible by 3 and 5 if not then divisible by 3 if not then divisible by 5 and finally else part.
public static List<String> fizzBuzz(int n) {
List<String> res = new ArrayList<>(n);
for (int i = 1; i <= n; i++) {
boolean mulThree = i % 3 == 0;
boolean mulFive = i % 5 == 0;
if (mulThree && mulFive)
res.add("FizzBuzz");
else if (mulThree)
res.add("Fizz");
else if (mulFive)
res.add("Buzz");
else
res.add(String.valueOf(i));
}
return res;
}
Related
I cannot figure out how to make it so it only calls check4 once... this was for a homework assignment last semester and I got 5 points off for calling it multiple times but I would not like to know how to do it (the professor never said how).
I tried moving the check4 to after the if block but it really needs to go in between the last else if and the else which is not possible. The ONLY way the number should print is if all of the steps do not print out a word instead.
public class CheeseCakeFactory_ajh187 {
public static void main(String[] args) {
int counter = 0;
int printNumber = 0; //number that will get changed to one of the terms
while (counter != 15 & printNumber < 210) { //as long as the counter is not 15 and print number is lesss than 210 it will keep looping.
printNumber++;
if (printNumber % 3 ==0 && printNumber % 5 == 0 && printNumber % 7 == 0) {
System.out.print("cheesecakefactory");
}
else if (printNumber % 3 == 0 && printNumber % 5 == 0){
System.out.print("cheesecake");
check4(printNumber);
}
else if (printNumber % 3 == 0 && printNumber % 7 == 0){
System.out.print("cheesefactory");
check4(printNumber);
}
else if (printNumber % 5 == 0 && printNumber % 7 == 0){
System.out.print("factorycake");
check4(printNumber);
}
else if (printNumber % 3 == 0){
System.out.print("cheese");
check4(printNumber);
}
else if (printNumber % 5 ==0){
System.out.print("cake");
check4(printNumber);
}
else if (printNumber % 7 ==0){
System.out.print("factory");
check4(printNumber);
}
else { //if the number is not divisible by any of the other numbers we still have to check for the 4
if (Integer.toString(printNumber).contains("4")) {
System.out.print("hoho");
}
else {
System.out.print(printNumber); //if its not divisible by 4, we just print the number
}
}
System.out.print(" ");
counter++;
if (counter == 15) { //once the counter is 15 we need to put the new items on a new line
System.out.print("\n");
counter = 0; //resets the counter so that we can accomplish this every 15 passes.
}
}
}
public static void check4(int printNumber) {
if (Integer.toString(printNumber).contains("4")) {
System.out.print("hoho");
}
}
}
First, I would update check4 to return a boolean (which you can save). Something like,
public static boolean check4(int printNumber) {
return String.valueOf(printNumber).contains("4");
}
Then you can also save your tests into boolean variables. Something like
boolean mod3 = printNumber % 3 == 0;
boolean mod5 = printNumber % 5 == 0;
boolean mod7 = printNumber % 7 == 0;
if (mod3 || mod5 || mod7) {
if (mod3 && mod5 && mod7) {
System.out.print("cheesecakefactory");
} else {
boolean isCheck4 = check4(printNumber); // <-- call it once
if (mod3 && mod5) {
System.out.print("cheesecake");
} else if (mod3 && mod7) {
System.out.print("cheesefactory");
} else if (mod5 && mod7) {
System.out.print("factorycake");
} else if (mod3) {
System.out.print("cheese");
} else if (mod5) {
System.out.print("cake");
} else if (mod7) {
System.out.print("factory");
} else {
if (!isCheck4) { // <-- it doesn't have a 4, print it.
System.out.print(printNumber);
}
}
if (isCheck4) {
System.out.print("hoho"); // <-- it does have a 4.
}
}
}
I hope I got your problem right so:
you create a global boolean variable named say isMethodCalled witch is false, then in the check4 method you make it true, and simple check if the isMethodCalled is false before calling the method.
boolean isMethodCalled = false;
if(!isMethodCalled) {
check4() // do wathever you need to do to call check4()
}
public static void check4(int printNumber) {
if (Integer.toString(printNumber).contains("4")){
System.out.print("hoho");
}
isMethodCalled = true;
}
Simply use a flag, set it to true initially.
Then, wherever you dont want the check4 to run, set it to false.
after the if-else, check if the flag istrue. if it is, execute 'check4(printNumber)'
public class CheeseCakeFactory_ajh187 {
public static void main(String[] args) {
int counter = 0;
int printNumber = 0; //number that will get changed to one of the terms
int flag=true;
while (counter != 15 & printNumber < 210) { //as long as the counter is not 15 and print number is lesss than 210 it will keep looping.
printNumber++;
if (printNumber % 3 ==0 && printNumber % 5 == 0 && printNumber % 7 == 0) {
System.out.print("cheesecakefactory");
flag=false;
}
else if (printNumber % 3 == 0 && printNumber % 5 == 0){
System.out.print("cheesecake");
}
else if (printNumber % 3 == 0 && printNumber % 7 == 0){
System.out.print("cheesefactory");
}
else if (printNumber % 5 == 0 && printNumber % 7 == 0){
System.out.print("factorycake");
}
else if (printNumber % 3 == 0){
System.out.print("cheese");
}
else if (printNumber % 5 ==0){
System.out.print("cake");
}
else if (printNumber % 7 ==0){
System.out.print("factory");
}
else { //if the number is not divisible by any of the other numbers we still have to check for the 4
if (Integer.toString(printNumber).contains("4")) {
System.out.print("hoho");
}
else {
System.out.print(printNumber); //if its not divisible by 4, we just print the number
}
flag=false;
}
if(flag)
check4(printNumber);
System.out.print(" ");
counter++;
if (counter == 15) { //once the counter is 15 we need to put the new items on a new line
System.out.print("\n");
counter = 0; //resets the counter so that we can accomplish this every 15 passes.
}
}
}
public static void check4(int printNumber) {
if (Integer.toString(printNumber).contains("4")) {
System.out.print("hoho");
}
}
}
Here's my code so far
public class DivisibleBy5and6
{
public static void main (String []args)
{
for (int i = 100; i <= 200; i++)
{
boolean num = (i % 5 == 0 || i % 6 == 0) && !(i % 5 == 0 && i % 6 == 0);
if (num == true)
System.out.println(i + " is divisible");
}
}
}
Like stated previously how can I get the output to print out 10 items per line separated by a space?
How about:
int count = 0;
for (int i = 100; i <= 200; i++) {
boolean num = (i % 5 == 0 || i % 6 == 0) && !(i % 5 == 0 && i % 6 == 0);
if (num == true) {
count++;
System.out.print(i + " is divisible ");
if(count >= 10) {
System.out.println();
count -= 10;
}
}
}
I am writing a simple java program to find the smallest number which is divisible by all the numbers from 1 to 20.
I have written the following code:
package smallmultiple;
public class SmallMultiple {
public static void main(String[] args) {
int sml = 0;
outerloop:
for (int i = 40; i < 100000; i++) {
int j=1;
do {
if(i%j==0)
j++;
} while(j<21);
if(j==20) {
sml=i;
break outerloop;
}
}
System.out.println(sml);
}
}
It is not giving any error but it is not giving any output.
You can try this which is a bit faster than yours solution:-
for(int i = 190; ; i += 190) {
if(i % 3 == 0
&& i % 4 == 0
&& i % 6 == 0
&& i % 7 == 0
&& i % 8 == 0
&& i % 9 == 0
&& i % 11 == 0
&& i % 12 == 0
&& i % 13 == 0
&& i % 14 == 0
&& i % 15 == 0
&& i % 16 == 0
&& i % 17 == 0
&& i % 18 == 0
&& i % 20 == 0) {
System.out.println(i);
break;
}
}
You can also check out this article.
You are incrementing j only if i is perfectly divisible by j. Shouldn't you break or exit the do.. while loop of atleast one number is not divisible? Not doing so is causing infinite loop I believe. It should be something like
if(i%j==0) {
j++;
}
else {
break;
}
its simple. Let me explain your loop. First, i = 40 and j = 1, its ok. Then j++.Next i = 40 and j = 2, its still correctly. Then j++ again. Now i = 40, j = 3 and i%j !=0 => j cannot ++ and j still equal 3. And you see, j = 3 is still satisfy your loop ( j < 21) then it loop and loop forever. This is the reason why you cant get any output. You can use your IDE debugging to find this mistake. Sorry my English not good.
In java, to respect the object oriented best practise, it's not advised to user labels, try this :
public class NumberTool {
public static void main(String[] args) {
System.out.println("Smallest number is : " + getSmallestNumberDividedByOneToTwnety());
}
public static int getSmallestNumberDividedByOneToTwnety() {
for ( int i = 40; i <= 2147483647; i++) {
if (isNumberDivdedByOneToTwenty(i)) {
return i;
}
}
return 0;
}
public static boolean isNumberDivdedByOneToTwenty(int numberToTest) {
for (int i = 1; i <= 20; i++) {
if (numberToTest % i != 0) {
return false;
}
}
return true;
}
}
Output is:
Smallest number is : 232792560
This question already has answers here:
Conditional statement true in both parts of if-else-if ladder
(4 answers)
Closed 2 years ago.
For those who don't know, FizzBuzz is the following problem:
Write a program that prints the numbers from 1 to 100. But for
multiples of three print "Fizz" instead of the number and for the
multiples of five print "Buzz". For numbers which are multiples of
both three and five print "FizzBuzz".
Every FizzBuzz solution I find is either some crazy esoteric solution made for the sake of being original, or your basic if-else chain:
for(int i = 1; i <= 100; i++) {
if(i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
I am looking for a simple solution that aims to take out the "FizzBuzz" if statement. I have this in mind:
for(int i = 1; i <= 100; i++) {
if (i % 3 == 0)
System.out.print("Fizz");
if (i % 5 == 0)
System.out.println("Buzz")
else
System.out.println(i);
}
But this doesn't work. I assume it would be able to print FizzBuzz by entering both ifs, for Fizz and for Buzz, but if the number is, for example, 3, it would print Fizz3. How do I avoid this?
What you're trying to do is
if (a)
...
if (b)
...
else // if neigther a nor b
...
This is simply not possible. An else can only belong to a single if. You have to go with the slightly longer variant.
To avoid doing redundant evaluations of the modulo operator, you could formulate the loop body as
boolean fizz = i % 3 == 0;
boolean buzz = i % 5 == 0;
if (fizz)
System.out.print("Fizz");
if (buzz)
System.out.print("Buzz");
if (!(fizz || buzz))
System.out.print(i);
System.out.println();
Another one would be
String result = "";
if (i % 3 == 0) result = "Fizz";
if (i % 5 == 0) result += "Buzz";
if (result == "") result += i;
System.out.println(result);
Your first if statement is all alone.
So, your code hits the first statement, which is ONLY an if statement, and then goes on to the next, which is an if/else statement.
RosettaCode has a good example without using AND operators.
int i;
for (i = 0; i <= 100; i++) {
if ((i % 15) == 0)
cout << "FizzBuzz" << endl;
else if ((i % 3) == 0)
cout << "Fizz" << endl;
else if ((i % 5) == 0)
cout << "Buzz" << endl;
else
cout << i << endl;
}
If your only goal is to avoid using &&, you could use a double negation and DeMorgan's laws:
for(int i = 1; i <= 100; i++) {
if(!(i % 3 != 0 || i % 5 != 0)) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
You can avoid && using the fact that i % 3 == 0 and i % 5 == 0 implies i % 15 == 0, as per RFC1337's answer.
Another solution is to use a switch on the remainder (mod 15, which is 5 times 3):
for(int i = 1; i <= 100; i++) {
final int mod = i % 15;
switch (mod) {
case 0:
case 3:
case 6:
case 9:
case 12:
System.out.print("Fizz");
if (mod != 0) break;
case 5:
case 10:
System.out.print("Buzz");
break;
default:
System.out.print(i);
}
System.out.println();
}
This is my solution. Granted, it's a bit convoluted (as in roundabout), but I believe it suits your requirement.
int main()
{
char fizzpass=0;
unsigned short index=0;
for(index=1;index<=100;index++)
{
if(0 == (index%3))
{
printf("Fizz");
fizzpass = 1;
}
if(0 == (index%5))
{
if(1 == fizzpass)
{
fizzpass = 0;
}
printf("Buzz\n");
continue;
}
if(1 == fizzpass)
{
fizzpass = 0;
printf("\n");
continue;
}
printf("%d\n",index);
}
return 0;
}
Regards.
Just add a flag variable and use System.out.print:
package com.stackoverflow;
public class FizzBuzz {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
boolean printed = false;
if (i % 3 == 0) {
printed = true;
System.out.print("Fizz");
}
if (i % 5 == 0) {
printed = true;
System.out.print("Buzz");
}
if (printed) {
System.out.println();
} else {
System.out.println(i);
}
}
}
}
This doesn't take out the if statements but does not use the && (and) operator, you could flip the binary operators.
//FizzBuzz Case
if(!(a % 3 != 0 || a % 5 != 0)){ //flips
result[index] = "FizzBuzz";
index++;
}
Don't use an if statement at all.
import java.util.*;
import java.lang.*;
import java.io.*;
class FizzBuzz
{
public static void main (String[] args) throws java.lang.Exception
{
String[] words = {"", "Fizz", "Buzz"};
String[] nwords = {"", ""};
for(int i = 1; i < 101; ++i)
{
int fp = (i % 3 == 0) ? 1 : 0;
int bp = ((i % 5 == 0) ? 1 : 0) * 2;
int np = ((fp > 0 || bp > 0) ? 1: 0);
nwords[0] = Integer.toString(i);
System.out.print(words[fp]);
System.out.print(words[bp]);
System.out.println(nwords[np]);
}
}
}
See it on ideone.
public class fizzbuzz
{
public static void main(String[] args)
{
String result;
for(int i=1; i<=100;i++)
{
result=" ";
if(i%3==0)
{
result=result+"Fizz";
}
if(i%5==0)
{
result=result+"Buzz";
}
if (result==" ")
{
result=result+i;
}
System.out.println(result);
}
}
}
This is the most efficient way I could come up with. Hope it helps! :)
Crazy albeit unrelated solution done in Python3
#!/usr/bin/python3
for i in range(1,100):
msg = "Fizz" * bool(i%3==0)
msg += "Buzz" * bool(i%5==0)
if not msg:
msg = i
print(msg)
Im stuck with the below problem.
Problem Statement:
Given a non-negative int n, return the count of the occurrences of 8 as a digit, except that an 8 with another 8 immediately to its left counts double, so 8818 yields 4.
Note: mod (%) by 10 yields the rightmost digit (126 % 10 is 6), while divide (/) by 10 removes the rightmost digit (126 / 10 is 12).
The above problem has to be solved without using Recursion and without the usage of any formulas.
The function signature is public int count8(int n)
Examples are:
count8(8) → 1
count8(818) → 2
count8(8818) → 4
I got this problem from one of the Programming Forums. I dont know how to start with this problem, I want to solve it, but I am really confused on where to begin.
the way to do this using the mod operator is to use %10 to get the last digit and /10 to remove the last digit in essence iterating through the number. If you %10 and get an 8 you can incremement a count, you can also keep a flag that lets you know if the last digit you saw was an 8 or not so you know how to increment your count
boolean lastWas8 = false;
int count = 0;
while (n != 0)
{
int digit = n % 10;
if (digit == 8)
{
if (lastWas8) count++;
count++;
lastWas8 = true;
}
else lastWas8 = false;
n/=10;
}
return count;
As none of the answers until now was recursive, here is my try at a recursive solution.
public int count8(int n) {
return
n <= 0 ? 0 :
( n%100 == 88 ? 2 :
n%10 == 8 ? 1 : 0)
+ count8(n/10);
}
Here the same program in a longer version:
public int count8(int n) {
Numbers without digits have no eights in them.
if(n <= 0) {
return 0;
}
Count the last digit:
int last;
If the last digit is an 8 and the digit before, too, count the last 8 doubled:
if(n % 100 == 88) {
last = 2;
}
If the last digit is an 8 (and the one before not), count it once.
else if(n % 10 == 8) {
last = 1;
}
Otherwise, the last digit is not an 8:
else {
last = 0;
}
The number without the last digit:
int withoutLast = n/10;
The number of eights in n is the number of eights in the last digit + the number of eights in the number without its last digit:
return last + count8(withoutLast);
}
Since I misread the question, here a iterative version of the same algorithm:
public int count8(int n) {
int count = 0;
while(n > 0) {
count += ( n%100 == 88 ? 2 : n%10 == 8 ? 1 : 0);
n/= 10;
}
return count;
}
Or with a for-loop:
public int count8(int n) {
int count = 0;
for( ; n > 0; n/=10) {
count += ( n%100 == 88 ? 2 : n%10 == 8 ? 1 : 0);
}
return count;
}
I saw that all the other solutions have used mods or divs but you could also just process it as a String I guess (I don't see anything in the question that says you can't despite the hints they give you). This is just an alternative solution.
I apologise in advance if I have missed some of the "rules" around the answer to this question but here we go anyway:
private int count8(int n) {
String nString = Integer.toString(n);
boolean isPrevChar8 = false;
int total = 0;
for (int i = 0; i < nString.length(); i++) {
char nextChar = nString.charAt(i);
if (nextChar == '8') {
total += (isPrevChar8 ? 2 : 1);
isPrevChar8 = true;
} else {
isPrevChar8 = false;
}
}
return total;
}
try this :
public static int count8(int num) {
int count=0;
boolean doubl = false;
while(true) {
int n = num%10;
num = num/10;
if(n==8) {
if(doubl) {
count = count+2;
} else {
count++;
}
doubl=true;
}
else {
doubl=false;
}
if(num == 0) break;
}
return count;
}
EDIT: Check this out for no recursion and no formula.
public static int count8(int num) {
int count=0;
boolean doubl = false;
String str = "" + num;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == '8') {
if (doubl) {
count = count + 2;
} else {
count++;
}
doubl = true;
} else {
doubl = false;
}
}
return count;
}
Here is my solution:
public int count8(int n) {
int count = 0;
if(n == 0)
return 0;
if(n % 100 == 88)
{
count = 3;
return count + count8(n/100);
}
else if(n % 10 == 8)
{
count++;
return count + count8(n/10);
}
else
return count8(n/10);
}
However, for the case: count8(88888) → 9, I get 7, and I can't figure out why.
What I also find strange is that a double 8 yields 3 so for the case: count8(8818) → 4 instead of 5, which is what I thought it would be. Hence, why I have count = 3 for the (n % 100 == 88)
Here is my code . The solution to this problem is very simple . I have done it with pure recursion . :)
public int count8(int n) {
if (n==8) return 1;
if (n<10) return 0;
if (n%100==88)
return 2 + count8(n/10);
if (n%10==8)
return 1 + count8(n/10);
return count8(n/10);
}
The catch of the problem is that when a pair of 88 comes total count = 1 + 2 ; 1 for 8 at right and 2 for 8 at left because the previous digit(which is digit at its adjacent right) was also 8 .
So for 88 the total occurances of 8 is equal to 3. For implementing this logic (n%100 ==88) condition is added .
This is the another recursion technique which I have used to solve this problem :-
public int count8(int n) {
int a,b;
if(n==0)
return 0;
a=n%10;
b=(n/10)%10;
if(a==8&&b==8)
return 2+count8(n/10);
else if(a==8&&b!=8)
return 1+count8(n/10);
else
return count8(n/10);
}
This code also works;
public int count8(int n) {
if(n/10 == 0 && n%10 != 8){
return 0;
}
if(n % 10 == 8 && (n/10)%10 == 8){
return 2 + count8(n/10);
}
if(n/10 == 0 && n%10 == 8){
return 1 + count8(n/10);
}
if(n % 10 != 8){
return 0 + count8(n/10);
}else{
return 1 + count8(n/10);
}
}
Here is simple solution
public int count8(int n) {
//base case if n becomes 0 then return 0
if(n==0) return 0;
//checking for two consecutive 8's in a row
if((n%10) == 8 && (n/10)%10 == 8){
return 2 + count8(n/10);
}
else if(n%10 == 8){ // there is only one 8
return 1 + count8(n/10);
}
//no 8 found
return count8(n/10);
}
Here's my solution, albeit the function names aren't nicely named, just think of them as abstract (not in the Java abstract keyword sense) functions that perform their task.
public int count8(int n) {
return g(n, 0);
}
public int g(int n, int prev) {
int rest = n/10;
int digit = n % 10;
if (rest == 0) {
return h(digit, prev);
}
int toAdd = h(digit, prev);
return toAdd + g(rest, digit);
}
public int h(int digit, int prev) {
return prev == 8 && digit == 8 ?
2 : digit == 8 ?
1 : 0;
}