I am writing a Java program that let user input a number, then the program combine 5,8,and 9 to get user's input number.
I want to achieve following samples:
1.
what is your number that you what to find the combination?
8
your number has 1 eights
2.
what is your number that you what to find the combination?
13
your number has 1 fives and 1 eights
3.
what is your number that you what to find the combination?
11
invalid number
Here are codes that I wrote:
import java.util.Scanner;
class combine {
public static void main (String[] args){
System.out.println("what is your number that you what to find the combination? ");
Scanner scan = new Scanner(System.in);
if (num < 5){
System.out.println("invalid number");
System.exit(0);
}
//Begin Looping
for (int g=0; g<=1000000;g++){
//Find the the number left after minus g*5
int left = num - g*5;
//Check the combination of 5 and 8
if (left%8 == 0){
System.out.format("your number has %d fives and %d eights\n",g,left/8);
System.exit(0);
}
//Check the combination of 5 and 9
if (left%9 == 0){
System.out.format("your number has %d fives and %d nines\n",g,left/9);
System.exit(0);
}
//Check the combination of 8 and 9
while (false){ //This while loop doesn't work. It fails compile.
int left2 = nuggets_num - g*8;
try{
if (left%8 == 0){
System.out.format("your number has %d eights and %d nines\n",g,left/8);
System.exit(0);
}
if (left%8 != 0){
System.out.println("invalid number");
}
}
}
}
System.out.println("invalid number");
}
}
//I am a beginner and I know that reading my codes might be painful, sorry about that:(
As I mentioned, my while loop doesn't work. So my program could't find the combination of "17", which should be 1 eight and 1 nine. How to fix it?
Also, my program's outputs are not clean enough. For example, if user input "8", my program would output"your number has 0 fives and 1 eights". How to add checkers to avoid these conditions? Like output "your number has 1 eights" instead of the former output.
You are using while(false) which means that this loop will never be executed. Java compiler is intelligent enough to stop you to compile something that it knows will not run.
As for your logic, when you deduct maximum multiple of 5's from some number (which means that you are doing modulus by 5), the remainder will never be more than 4! So, you should do something like below:
Divide the input by 9. This will give you the count of 9's in that input.
Modulus the input by 9. This will give you the remainder, which will be less than or equal to 8.
Perform step 1 and 2 with 8 and 5, respectively.
Use the output of above algorithm to format your output string.
You have a basic misunderstanding of the division and modulus operators.
You're trying to divide a number by a specific digit to "get rid" of it, but that only works when you're diving by multiplications of 10 (assuming you're working in the decimal system).
For example, (1985 / 10) = 198, but 888 / 8 does not equal 88!
The same goes for the % operator - (350 % 3) will not return 50! It's actually equal to 2
Related
I have to check whether a number is an Armstrong number or not, using a recursive method.
public class ArmStrong {
public static void main(String[] args) {
System.out.println(isArm(407, 0, 0));
}
static boolean isArm(int n,int last,int sum) {
if (n <= 0 ) {
if (sum == n) {
return true;
} else {
return false;
}
}
return isArm(n / 10, n % 10,sum + last * last * last);
}
}
When I debug, in the last call of isArm when n is 4, the base statement is skipped.
Your code will instantly jump to the answer (if (n <= 0)) before applying the cube of the last digit.
For example, trivially, let's try 9, which obviously isn't armstrong.
Your code will first check if 9 is 0 - it's not. So, we recurse, which will go with self(0, 9, 0+0). The next run is supposed to then recurse once more, so that the sum + last*last*last can actually get some cubing done. But it'll never get there - n is 0, so, you jump into the if.
As your variable name kinda gives away last is referring to the digit that the previous run lopped off, and yet you aren't cubing it.
The solution is to simply get the cubing in before checking if n is null:
The first thing your method should do is
sum += last*last*last;
Then, the second problem shows up: This correctly calculates your sum to be 407, but you check this against n, which is, obviously, 0 - you are 'destroying' n as you go through. One trivial way to solve that is to pass the original n, unmolested, through, as a 4th parameter. I'll leave that as an exercise for the reader.
Although #rzwitserloot has pointed at an issue which is rooted in the way you've designed the recursion, the problem is still not resolved.
Yes, the recursive calls go "one step ahead" the calculation of the sum of digits, which happens in the Recursive case, and the left-most digit of the given number doesn't contribute the sum, since n is zero and recursion hits the Base case. That's true, but it's not the only thing you need to fix.
Here's the definition of so-called Narcissistic numbers (aka Armstrong numbers):
In number theory, a narcissistic number (also known as a pluperfect digital invariant (PPDI), an Armstrong number (after Michael F. Armstrong)or a plus perfect number) in a given number base b b is a number that is the sum of its own digits each raised to the power of the number of digits.
Therefore, a method with hard-coded power of 3 is capable to validate only three-digit Armstrong numbers. There are only few of them, for other valid Armstrong numbers it would produce an incorrect result.
So, before calculating the sum you need to know the numbers of digits there's no workaround. If you want to address the problem only by using Recursion, the numbers of digits can be also calculated recursively. If we take this route, the solution boils down to implementing two recursive methods.
That's how it might look like:
public static boolean isArm(int n) {
return n == getSum(n, getDigitCount(n));
}
public static int getSum(int n, int power) {
return n == 0 ? 0 : (int) Math.pow(n % 10, power) + getSum(n / 10, power);
}
public static int getDigitCount(int n) {
return n == 0 ? 0 : 1 + getDigitCount(n / 10);
}
main()
public static void main(String[] args) {
System.out.println(isArm(10)); // is not an Armstrong number
System.out.println(isArm(21)); // is not an Armstrong number
System.out.println(isArm(407)); // is an Armstrong number
System.out.println(isArm(153)); // is an Armstrong number
System.out.println(isArm(9)); // is an Armstrong number
}
Output:
false // 10
false // 21
true // 407
true // 153
true // 9
My code requires me to create an array (from user input), display it backwards, and find the sum of each number. So far I have been able to accomplish all requirements. However, if the array is more than 8 numbers, then when it is displayed the program must create a new line every 8th number. I'm having difficulty accomplishing this goal. Here is my code so far:
import java.util.Scanner;
public class arrayCreator {
public static void main(String[] args) {
int length;
double sumArray = 0;
Scanner input = new Scanner(System.in);
System.out.print("How many elements in the array? ");
length = input.nextInt();
}
for(int j = currentArray.length-1; j >= 0; j-- )
{
System.out.printf("%.3f \t", currentArray[j]);
if(currentArray.length - 8 == j) // here is where I'm having the problem
{
System.out.print("\n");
}
input.close();
}
}
What should go inside of the if statement in order to create a new line each time 8 inputs are displayed?
This is what output should look like :
How many elements in the array? 20
Please enter the next value 1
Please enter the next value 2
Please enter the next value 3
Please enter the next value 4
Please enter the next value 5
Please enter the next value 6
Please enter the next value 7
Please enter the next value 8
Please enter the next value 9
Please enter the next value 10
Please enter the next value 11
Please enter the next value 12
Please enter the next value 13
Please enter the next value 14
Please enter the next value 15
Please enter the next value 16
Please enter the next value 17
Please enter the next value 18
Please enter the next value 19
Please enter the next value 20
20.000 19.000 18.000 17.000 16.000 15.000 14.000 13.000
12.000 11.000 10.000 9.000 8.000 7.000 6.000 5.000
4.000 3.000 2.000 1.000
The Sum of the array's elements is : 210.000
The other answer isn't working correctly because you're backing up through the list from the end back to the beginning, but the mod operator causes line breaks as if you were moving from the beginning to the end. However, the idea of using the modulo operator is definitely correct. Do this in your if statement:
if((length - j) % 8 == 0) {
System.out.print("\n");
}
Usually when you want to do something every n times, you want to use modulo division: %.
Change this
if(currentArray.length - 8 == j) // here is where I'm having the problem
{
System.out.print("\n");
}
To this
if (j % 8 == 0) // here is where I'm having the problem
{
System.out.print("\n");
}
This question already has answers here:
How can I improve this code for Project Euler 7?
(4 answers)
Closed 7 years ago.
Alright, let us start off, by showing my question.
The Problem:
10001st prime
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
This is what I currently have down. I'm pretty bad at creating algorithms, but I truly have the desire to follow in my Father's path of being a IT. I enjoy doing this a lot, but I'm struggling right now.
public class PrimeNumber
{
public static void main(String[] args)
{
int primeNum = 2;
for (int count = 0; count < 10002; count++)
{
if (primeNum / 2 == && primeNum / primeNum == 1)
{
primeNum++;
}
else
{
System.out.println("Error.");
}
}
System.out.println(primeNum);
}
}
The / symbol means 'divided by'. So your code says 'if primeNum divided by 2 = 1 and primeNum divided by primeNum = 1 then increase primeNum.' This is unnecessary; all this is asking is if primeNum is 2.
The % symbol means 'remainder when divided by'. So 2%3 = 1. 4%2=0. This will probably be useful in your program, because it will allow it to check to see if your number is prime by seeing if it is divisible by any numbers.
(With if (a%b==0), you can check to see if b is a factor of a.)
There are a few shortcuts your program could take: it only needs to check every prime number up to the square root of the number it is checking.
So you may want to keep an array of all prime numbers you have found, so that you can check if a number you want to know if it's prime is divisible by any of them.
(This can be done with a loop on the outside, going through every number, and a loop inside that loop, checking to see if that number is divisible by any of the previously discovered prime numbers.)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
The Siruseri Sports Club organises an annual billiards game where the top two players of Siruseri play against each other. The Manager of Siruseri Sports Club decided to add his own twist. In his version, at the end of each round the leader and her current lead are calculated. Once all the rounds are over the player who had the maximum lead at the end of any round in the game is declared the winner.
The total scores of both players, the leader and the lead after each round for this game is given below:
Round Player 1 Player 2 Leader Lead
1 140 82 Player 1 58
2 229 216 Player 1 13
3 319 326 Player 2 7
4 431 432 Player 2 1
5 519 522 Player 2 3
The winner of this game is Player 1 as he had the maximum lead (58 at the end of round 1) during the game.
Your task is to help the Manager find the winner and the winning lead. You may assume That is, there are no ties.
Input
The first line of the input will contain a single integer N (N ≤ 10000) indicating the number of rounds in the game. Lines 2,3,...,N+1 describe the scores of the two players in the N rounds. Line i+1 contains two integer Si and Ti, the scores of the Player 1 and 2 respectively, in round i. You may assume that 1 ≤ Si ≤ 1000 and 1 ≤ Ti ≤ 1000.
Output
Your output must consist of a single line containing two integers W and L, where W is 1 or 2 and indicates the winner and L is the maximum lead attained by the winner.
My code:
import java.util.Scanner;
class billardsDemo {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int rounds = in.nextInt();
int i = 0;
int lead = 0;
int flag = 0;
while (i < rounds) {
int score1 = in.nextInt();
int score2 = in.nextInt();
if (score1 > score2 && score1 - score2 > lead) {
flag = 1;
lead = score1 - score2;
} else if (score2 > score1 && score2 - score1 > lead) {
flag = 2;
lead = score2 - score1;
}
i++;
}
System.out.println(flag +" "+ lead);
in.close();
}
}
I am getting the right output in eclipse, but code chef says wrong answer.
One thing that immediately stands out is your println statement at the end. You're printing one integer instead of two since flag and lead get combined. The correct code should be:
System.out.println(flag + " " + lead);
In my opinion, you should try to parse the input line by line as intended, not nextInt by nextInt as this might lead to unknown complications. You should read the whole line, then tokenize it and get the first two integers.
Also, online judges are usually very finicky about class and method names so make sure you name your class how they want you to (for example on HackerRank your class must be named Solution for the code to work).
Finally, how do you handle ties in the lead? In your problem statement it says there are no ties but does this mean no ties in the round or no ties in the leads as well? What I mean is this: suppose player 1 wins the first round with a lead of 1. Then player 2 wins the second round also with a lead of 1. What should your flag be, 1 or 2?
It seems your input doesn't total the scores, but replace the last score with the new scan.
I would suggest declaring the variable score1 and score2 before the loop and change the code inside the loop to:
score1 += in.nextInt();
which is equal to
score1 = score1 + in.nextInt();
The same goes for score2, of course.
See this accepted solution on their website for a complete code:
https://www.codechef.com/viewsolution/8684978
//edit: I think you should also add a space character between the integers in the output. Otherwise the output will be "158" instead of "1 58".
Why did you solve it this way? Please explain. And is it a problem with code chef of with your programming?
My way of solving would be this:
create helper class that hold the matches, with the values:
Player1 score, Player2 score, difference in score.
make an array of said matches and iterate thou them to find the
largest value.
now you have the winning match, go and find the player who won it.
Print the winning player and the points.
I've been searching for the source code of this game and found this one. However, I didn't understand the hasDupes method at the end of the code.
Could you explain it to me?
Source code - here
public static boolean hasDupes(int num){
boolean[] digs = new boolean[10];
while(num > 0){
if(digs[num%10]) return true;
digs[num%10] = true;
num/= 10;
}
return false;
So let's step through it:
boolean[] digs = new boolean[10];
In Java, all the items in an array declaration are given a default value. In the case of boolean, it is false. So this creates an array of 10 elements where each element is false
while(num > 0){
if(digs[num%10]) return true;
digs[num%10] = true;
num/= 10;
}
Modding a number by 10 (num % 10) and then dividing by 10 (num/= 10) is a common way to "pop" off the last digit from a number. For example,
int someNum = "1357";
int lastDigit = mod % 10; // lastDigit is 7
someNum /= 10; // someNum is now 135
As you can see, the 7 gets removed. So the while loop is just popping of each digit of num until all the digits are processed. Now, for each digit that is being removed, digs[num%10] = true; is simply keeping track of the digits already removed. By keeping track of these, if(digs[num%10]) return true; will return true from the method if a digit has already been processed.
So, in much simpler words, this method just checks to see if a number contains more than 1 of the same digit.
12345 will return false
12341 will return true
Just make a pen & paper test. Our number system has 10 digits: 0 to 9. digs represents, whether a digit has occured already. with num % 10 you get the last digit of num. So let's say num has an 1 at the least significant position. That means: digs[i] will be set to true (digs[num%10] = true;). Now let's look on: with num /= 10 you remove the last digit from an integer. For example, 3211 /= 10 will be 321 (integer arithmetics, I know you cannot apply /= to literals, but it is only a demonstration to explain the semantics). Since num is > 0, the loop is executed again. This time, the if-condition will be true (because we set digs[1] to true one iteration before), we found a duplicate digit. If the method is able to leave the loop without entering the if, num has pairwise unequal digits. That's it.
It's checking if any value in base 10 has duplicated digits.
So 9019 has duplicated digits (9) when written as a decimal value. 123 does not.
In the context of the game, it basically checks to see if the given integer, num, has duplicated digits. It does so by creating an array of 10 boolean values, such that two digits that are duplicated will be dropped into the same cell in the array. The algorithm uses
An array of 10 boolean values to represent each digit in our base 10 number system. So if you are dealing with base 16 number system, you will need an array of 16 boolean values.
num modulo 10 to extract the least significant digit of num until all digits have been examined. Again, it uses modulo 10 because it is assuming a base 10 number system.
The moment that duplicated digits are detected, the method returns true:
if(digs[num%10]) return true;
If you look at the main() method in your sample codes, the algorithm will attempt to keep generating random number, until one with no duplicated digits is found.
while(hasDupes(target= (gen.nextInt(9000) + 1000)));