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.
Related
Problem
Turtles live long (and prosper). Turtles on the island Zanzibar are
even immortal. Furthermore, they are asexual, and every year they give
birth to at most one child. Apart from that, they do nothing. They
never leave their tropical paradise.
Zanzi Bar, the first turtle on Zanzibar, has one further activity: it
keeps track of the number of turtles on the island. Every New Year’s
Day it counts the turtles, and writes the total number in a small
booklet. After many years this booklet contains a non-decreasing
sequence of integers, starting with one or more ones. (After emerging
from its egg on Zanzibar’s beautiful beach, it took Zanzi some time to
start a family on its own.)
One day Zanzi realizes that it could also be the case that turtles
from abroad come to Zanzibar, by boat or plane. Now it wonders how
many of the inhabitants were not born on Zanzibar. Unfortunately, it
can only derive a lower bound from the sequence in the booklet.
Indeed, if the number of turtles in a year is more than twice as big
as the year before, the difference must be fully explained by import.
As soon as Zanzibar has 1000000 turtles, the island is totally covered
with turtles, and both reproduction and import come to a halt. Please
help Zanzi! Write a program that computes the lower bound of import
turtles, given a sequence, as described above.
Input
The input starts with a line containing an integer T(1≤T≤13), the
number of test cases. Then for each test case:
One line containing a sequence of space-separated, positive integers
(≤1000000), non-decreasing, starting with one or more ones. For
convenience, a single space and a 0 are appended to the end of the
sequence.
Output
For each test case, output a line containing a single integer: the
lower bound for the number of turtles not born on Zanzibar.
See question and sample input and output here
My approach
public Zanzibar() {
Scanner scan = new Scanner(System.in);
int iterations = scan.nextInt();
for (int i = 0; i < iterations; i++) {
int previous = -1;
int current = -1;
int lower = 0;
while (true) {
if (current != -1)
previous = current;
current = scan.nextInt();
if (current == 0)
break;
if (current > 2 * previous && previous != -1)
lower += current - previous;
}
System.out.println(lower);
}
}
I think I am understanding the problem wrong. Am I supposed to keep adding to the lower bound or should I find the biggest difference between two years? Also I don't understand how input 1 100 0 produces output 98 (from the link). Shouldn't it be 99?
This is what the problem setter wants us to understand:
The initial 1 for every test case means that the initial population on the island is always 1
So for an input like 1 1 1 0, it means that:
The initial population is 1. Then at the start of the 2nd year, the population is still 1. At the start of the 3rd year, the population is still 1.
As for your doubt about the input: 1 28 0, it means that:
At the start of the 2nd year, the population is 28, whereas the maximum that could have been is 2, as the only turtle could have given birth to one more turtle at max. So, it means that clearly, at least (28-2) = 26 turtles migrated!!!
Hope it helps...
Edit: This is the algorithm:
For every line of test case do the following:
Set initial to 1, migrated to 0
Start reading from the second number in the line, until we encounter a 0:
If the current number is greater than 2*initial: migrated = migrated + (current - 2*initial)
Else: do nothing
Set initial to current
Print migrated
Edit-2:
Here is the JAVA implementation:
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int iterations = scan.nextInt();
int i = 0;
int len,x;
int j,initial;
long migrated;
int arr[] = new int[1000005];
while(i<iterations)
{
len = 0;
while(true)
{
x = scan.nextInt();
if(x==0)
break;
arr[len++] = x;
}
initial = arr[0];
migrated = 0;
j = 1;
while(j<len)
{
if(arr[j]-(2*initial)>0)
{
migrated += arr[j]-(2*initial);
}
initial = arr[j];
j++;
}
System.out.println(migrated);
i++;
}
}
}
Input:
3
1 100 0
1 1 1 2 2 4 8 8 9 0
1 28 72 0
Output:
98
0
42
I've been working at an assignment for my intro to Java class, and I can't figure out how to accomplish the two things I need to do.
What I have now: I have created an array that rolls five dice, and displays the results. The code I have is as follows...
package operation.pkg7;
import java.util.Random;
import java.util.Scanner;
public class Operation7 {
public static void main(String[] args)
{
int[] dice = new int[5];
Random r = new Random();
//This makes the dice
for (int i = 0; i < 5; i++) {
dice[i] = r.nextInt(6) + 1;
}
//This displays the dice rolls
for (int i = 0; i < 5; i++) {
System.out.print("Roll " + (i+1) + ":" );
System.out.print(" " + dice[i] + " ");
}
System.out.println();
//..........................................
int[] counts = new int[6];
for (int i = 0; i < 6; i++){
counts[i] = 0;
}
//count up the values
for (int i = 0; i < 5; i++) {
int diceIndex = dice[i] - 1;
counts[diceIndex]++;
}
System.out.println();
for (int i = 0; i < 6; i++){
System.out.println("The number of " + (i+1) + "s is : " +
counts[i]);
}
}
}
Now, I successfully gives me the results of the die rolls, but I'm having problems figuring out how to do re-rolls. This is an example of what I'm wanting the program to ask for after displaying the initial die roll...
Roll 1: 2 Roll 2: 6 Roll 3: 1 Roll 4: 4 Roll 5: 2
Would you like to re-roll any dice? y/n
y
Which dice would you like to re-roll? 1-5
2, 3, 4
Roll 1: 2 Roll 2: 3 Roll 3: 2 Roll 4: 3 Roll 5: 2
Would you like to re-roll any dice? y/n
n
Roll 1: 2 Roll 2: 3 Roll 3: 2 Roll 4: 3 Roll 5: 2
That's the goal. Once I do that, I need to make the program display the best possible score... For example, if there are two threes and three twos, it needs to say it's a full house, or display yahtzee if there are five of the same number etc.
Anyone have any advice?
Put your code in a do-while loop with the condition of the user's input placed before the do-while loops condition check.
You have the results of your rolls store in the dice array you simply need to create new random results for the dice in those positions. E.g. if you re-roll #2 then put a new random in index 1.
As for determining the various types of rolls such as full house you will want to define generic logic for each. You might for example define a method like:
public static boolean isFullHouse(int[] diceRoll){
//return true if the roll is a full house, false otherwise
}
However, I think what you really want is not just to determine if a roll is a full house but to also calculate the total score using the scoring rules for that scenario.
EDIT #1:
Before going any further please, at a minimum, read the section on this page titled "Asking about homework".
I will try to illustrate how I think you could accomplish a re-roll without providing full code at this point. As I stated above, since you need to prompt the user for which dice they intend to re-roll you can process that input and use it as indicies into your dice array. So if the users 2,3,4 as in your example you use Scanner.getLine() to read that input and then use String methods to break it apart. Once you have the individual pieces you can convert them to int values using the Integer class. Finally, subtract 1 from them to adjust for the fact that your dice array indicies begin at 0.
Now you have an array containing indicies into your dice array. Each item in this new array is just used to refer to an index of the dice array. So let's call this second array userInput. Continuing the 2,3,4 example userInput[0]=1, userInput[1]=2, userInput[2]=3.
All you need to do is loop through userInput and each time through the loop generate a new random number. This random number is then stored in the dice array at the index stored in the current position of your userInput array.
As for determining the best possible score you could, as I suggested, write individual methods for each to determine if they are present and then another method to invoke each of them and report the greatest score possible.
Let's take one of them as an example like 3 of a Kind. Perhaps the simplest way to think about it would be to loop through all the possible rolls of the die (0 to 6) so that each time through the loop you're counting how many of each roll appear in the current dice roll. So in loop 1 you're looking for three 1's and in loop 2 you're looking for three 2's and so on.
Inside of this loop you create another loop to iterate through all of the dice in the current dice roll (your dice array) and each time through the loop you check to see if the current die is the number you're currently looking for from your outer loop. If it is the number from the outer loop then you increment a counter (which is defined and initialized in the outer loop but outside the inner loop so that it resets each time the outer loop increments) to represent how many of that number you have found so far.
If the counter reaches 3 before the inner loop ends you know you have 3 of a Kind, so have the method return true since you have no reason to continue (can't possibly have 2 different 3 of a Kind). Otherwise your method should return false to indicate there was no match.
Note that if you want to be ambitious you could exercise good programming practice and reuse code by making the limit of your counter a parameter to your method so that you can use the same logic for both 3 of a Kind and 4 of a Kind.
Hint there is a more clever way of doing this but I thought this approach would be more consistent with the constructs you already know.
I hope this helps to get you started!
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
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Improve this question
//I am supposed to do it with loops and decision statements, but it's not working. Help!
import java.util.Scanner;
public class main {
/**
* #param args
*/
public static void main(String[] args) {
//Declare variables
Scanner abc;
abc = new Scanner (System.in);
int input;
int divide = 2;
int count=0;
//Ask for input
System.out.println("Please enter an integer to determine if it is prime");
input = abc.nextInt();
//Do math
for (int x=1; x < input; x++) {
if ((input%divide) == 0)
count += 1;
divide = divide + 1;
}
if (count == 0)
System.out.println("It is a prime number");
else
System.out.println("It is not a prime number");
}
}
In your for loop, for the last iteration, x = input - 1, but that means divide = input (since divide was one greater in the beginning, and you increment both once per iteration of the loop), so count will actually be equal to 1 if the number is prime, not 0.
You're counting the number of divisors; all you need to do is determine if there is at least one divisor. Here's a better algorithm:
function isPrime(n)
if n is even
return n == 2
d := 3
while d * d <= n
if n % d == 0
return False
d := d + 2
return True
I discuss this algorithm, among others in the essay Programming with Prime Numbers at my blog, which includes implementations in Java.
It looks like count is supposed to count the number of factors of input not counting 1 and input. For readability, I'd recommend using a name like numOfFactors instead of count.
Given that, now look at your loop and answer these questions. I'm not going to give you the answer. (Yes, you can get the answer by looking at others' comments, but I think you will learn more by answering these questions anyway.)
(1) What are x and divide the first time you go through the loop, at the beginning of the loop?
(2) If you look at what happens to x and divide, there's a simple relationship between x and divide at the beginning of each time through the loop. What is it?
(3) What is x the last time you go through the loop?
(4) Based on the answers to #2 and #3, what is divide at the beginning of the last time through the loop? What will input%divide be equal to?
That's why it isn't working. Figure that out first. Then we can talk about how to can make it work more efficiently.
MORE: OK, I'll say one more thing. If all you care about is whether count is zero or not, you can quit your loop as soon as you find a factor. Like this:
if ((input%divide) == 0)
{
count += 1;
break;
}
(And if you do it that way, then instead of count you should use a boolean foundAFactor because all it says is whether you found a factor, not how many there are.)
But if you really want to know the exact number of factors, don't do that.
Hello do it like this:
for(int i = input-1; i > 0; i--) {
if((input % i) == 0) {
if(i == 1)
System.out.println("is a prime");
else
System.out.println("is not a prime");
break;
}
}
for (int x=2; x < input; x++) (change x=1 to x=2)
otherwise you end up trying to divide 5 by 5 to test if 5 is prime
After a tennis tournament each player was asked how many matches he had.
An athlete can't play more than one match with another athlete.
As an input the only thing you have is the number of athletes and the matches each athlete had. As an output you will have 1 if the tournament was possible to be done according to the athletes answers or 0 if not. For example:
Input: 4 3 3 3 3 Output: 1
Input: 6 2 4 5 5 2 1 Output: 0
Input: 2 1 1 Output: 1
Input: 1 0 Output: 0
Input: 3 1 1 1 Output: 0
Input: 3 2 2 0 Output: 0
Input: 3 4 3 2 Output: 0
the first number of the input is not part of the athletes answer it's the number of athletes that took part in the tournament for example in 6 2 4 5 5 2 1 we have 6 athletes that took part and their answers were 2 4 5 5 2 1.
So far this is what we wrote but didn't work that great:
import java.util.Scanner;
import java.util.Arrays;
public class Tennis {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String N;
int count;
int sum = 0;
int max;
int activeAthletes;
int flag;
System.out.printf("Give: ");
N = input.nextLine();
String[] arr = N.split(" ");
int[] array = new int[arr.length];
for (count = 0; count < arr.length; count++) {
array[count] = Integer.parseInt(arr[count]);
//System.out.print(arr[count] + " ");
}
for (count = 1; count < arr.length; count++) {
sum += array[count];
}
//System.out.println("\n" + sum);
activeAthletes = array[0];
for (count = 1; count < array.length; count++) {
if (array[count] == 0) {
activeAthletes--;
}
}
max = array[1];
for (count = 2; count < array.length; count++) {
if (array[count] > max) {
max = array[count];
}
}
// System.out.println(max);
if ((sum % 2 == 0) && (max < activeAthletes)) {
flag = 1;
} else{
flag = 0;
}
System.out.println(flag);
}
}
I do not want a straight solution just maybe some tips and hints because we really have no idea what else to do and I repeat even though I'll tag it as a homework (because I feel the moderators will close it again) it is not, it's just something my brother found and we are trying to solve.
Well many of you have answered and I'm really grateful but as I have work tomorrow I need to go to sleep, so I'll probably read the rest of the answers tomorrow and see what works
Not sure if it works 100%, i would go like:
Sort input
for each element going from right to left in array (bigger to smaller)
based on value n of element at index i decrease n left elements by 1
return fail if cant decrease because you reached end of list or value 0
return success.
This logic (if correct) can lead whit some modifications to O(N*log(N)) solution, but I currently think that that would be just too much for novice programmer.
EDIT:
This does not work correct on input
2 2 1 1
All steps are then (whitout sorting):
while any element in list L not 0:
find largest element N in list L
decrease N other values in list L by 1 if value >= 1 (do not decrease this largest element)
return fail if failure at this step
set this element N on 0
return OK
Here's a hint. Answer these questions
Given N athletes, what is the maximum number of matches?
Given athlete X, what is the maximum number of matches he could do?
Is this sufficient to check just these? If you're not sure, try writing a program to generate every possible matching of players and check if at least one satisfies the input. This will only work for small #s of atheletes, but it's a good exercise. Or just do it by hand
Another way of asking this question, can we create a symmetric matrix of 1s and 0s whose rows are equal the values. This would be the table of 'who played who'. Think of this like an N by N grid where grid[i][j] = grid[j][i] (if you play someone they play you) and grid[i][i] = 0 (no one plays themselves)
For example
Input: 4 3 3 3 3 Output: 1
Looks like
0 1 1 1
1 0 1 1
1 1 0 1
1 1 1 0
We can't do this with this one, though:
Input: 3 2 2 0 Output: 0
EDIT
This is equivalent to this (from Degree (graph theory))
Hakimi (1962) proved that (d1, d2, ..., dn) is a degree sequence of a
simple graph if and only if (d2 − 1, d3 − 1, ..., dd1+1 − 1, dd1+2,
dd1+3, ..., dn) is. This fact leads to a simple algorithm for finding
a simple graph that has a given realizable degree sequence:
Begin with a graph with no edges.
Maintain a list of vertices whose degree requirement has not yet been met in non-increasing order of residual degree requirement.
Connect the first vertex to the next d1 vertices in this list, and then remove it from the list. Re-sort the list and repeat until all
degree requirements are met.
The problem of finding or estimating the number of graphs with a given
degree sequence is a problem from the field of graph enumeration.
Maybe you can take the array of athletes' match qties, and determine the largest number in there.
Then see if you can split that number into 1's and subtract those 1's from a few other members of the array.
Zero out that largest number array member, and remove it from the array, and update the other members with reduced values.
Now, repeat the process - determine the new largest number, and subtract it from other members of the array.
If at any point there are not enough array members to subtract the 1's from, then have the app return 0. otherwise continue doing it until there are no more members in the array, at which point you can have the app return 1.
Also, remember to remove array members that were reduced down to zero.
Your examples can all trivially be solved by counting the matches and looking whether they divide by 2.
A problem not covered by your examples would be a player, who has more games than the sum of the other players:
Input: 4 5 1 1 1 Output: 0
This can be complicated if we add more players:
Input: 6 5 5 5 1 1 1 Output: 0
How to solve this question? Well, remove one game pairwise from the maximum and the minimum player, and see what happens:
Input: 6 5 5 5 1 1 1
Input: 5 5 5 4 1 1 -
Input: 4 5 4 4 1 - -
Input: 3 4 4 4 - - -
It violates the rule:
An athlete can't play more than one match with another athlete.
If 3 players are left, they can't have had more than 2 games each.
Edit: Below solution passes some invalid inputs as valid. It's a fast way to check for definite negatives, but it allows false positives.
Here's what a mathematician would suggest:
The sum of the number of matches must be even. 3 3 4 2 1 sums to 13, which would imply someone played a match against themselves.
For n players, if every match eliminates one player at least n-1 distinct matches must be played. (A knockout tournament.) To see this, draw a tree of matches for 2, 4, 8, 16, 32... players, requiring 1, 3, 7, 31... matches to decide a winner.
For n players, the maximum number of matches if everyone plays everyone once, assuming no repeat matches, is n choose 2, or (n!)/(2!)(n-2)! (Round robin tournament). n! is the factorial function, n! = n * n-1 * n-2 * ... * 3 * 2 * 1..
So the criteria are:
Sum of the number of matches must be even.
Sum of the number of matches must be at least 2n-2. (Note the multiplication by 2 - each match results in both players increasing their count by one.)
Sum of the number of matches must be at most 2 * n choose 2.
[Edit] Each player must participate in at least one match.
If your tournament is a cross between a knockout tournament and a round robin tournament, you could have somewhere between n-1 and n choose 2 matches.
Edit:
If any player plays more than n-1 matches, they played someone at least twice.
If your tournament is a knockout tournament ordered so that each player participates in as few matches as possible, then each player can participate in at most log_2(n) matches or so (Take log base 2 and round up.) In a tournament with 16 players, at most 4 matches. In a tournament of 1024 players, at most 10 matches.