How to print a warning every set number of times (Java) - java

(If there is already a question asking this please just send me the link in the comments. I did not find anything)
I was doing a small app, like MasterMind (but way simpler and not like it) and I wanted to help the user if he tried for example 5 times and didn't succeed.
int counter = 1;
while (flag){
System.out.println("Counter");
int guess = input.nextInt();
counter++;
if (counter>=5 && ) {
System.out.println("I'm helping");
}
}
if (counter>=5 && ) How do I tell it to help the user every 3 attempts how the fifth? Thanks

Every three attempts after the fifth, including the fifth?
if (counter >= 5 && (counter - 5) % 3 == 0 ) {
So say it was the 8th time, the if statement would be true because 8 - 5 = 3 and 3 % 3 == 0
If it was the 11th time, it would also be true because 11 - 5 = 6 and 6 % 3 == 0
The mod function (%) returns the remainder of the first number divided by the second number. If the remainder is 0, then the first number is divisible by the second.
For example: 8 % 3 is 2 because 3 goes into 8 twice, with a remainder of 2.
And 9 % 3 is 0 because 3 goes into 9 three times evenly.
Edit:
The reason I had to change add the condition that counter >= 5 for the second part is because if the counter was 2 and you subtract 5 from that, you get -3. Then, -3 % 3 will be 0 and the condition would be true, but that's not what you want. It has to be greater than or equal to 5, and every third number after 5 (inclusive).

Related

Addition of two numbers, twist is that the length of number can be very large [duplicate]

This question already has answers here:
How to add two numbers of any length in java?
(8 answers)
Closed 5 years ago.
Today I had an interview and the interviewer asked to make a program for addition of two numbers, I get shocked how can he give a simple question but the question is different
the length of two number can be anything (10,20,30 or even 1000 etc.)
if you convert it to int,double,long double if the number is greater than their range than the answer can be wrong.
Please help me for the question.
You can always take the two numbers in arrays (i.e. arrays have digits of the numbers as elements) and add them as we add manually i.e. start from one's digit and store the carry if it's present then do the same for ten's digit, then hundred's digit and so on.
Say you want to add 123 and 329.
X = 123, X[] = [1,2,3]
Y = 329, Y[] = [3,2,9]
You start with one's digit (the rightmost or last element) and add the elements of both X and Y arrays and add carry to it (initially set to 0). If the addition comes out to be greater than 10, set carry = sum / 10 (since we are adding each element, this carry shall always be either 0 or 1) and the addition to add [i] = sum % 10. Repeat till all the elements of smaller array are over. Then add the carry to remaining elements of larger array continuing the above logic.
carry = 0
Step 1 : 3 + 9 + carry (0) = 5, carry => 12 / 10 = 1, add => 12 % 10 = 2
Step 2 : 2 + 2 + carry (2) = 6, carry => 6 / 10 = 0, add => 6 % 10 = 6
Step 3 : 3 + 1 + carry (0) = 4, carry => 4 / 10 = 0, add => 4 % 10 = 4
Ans = 462
Obviously the array storing sum may have one digit extra so take care of that as well.

Effiecient Algorithm for Finding if a Very Big Number is Divisible by 7

So this was a question on one of the challenges I came across in an online competition, a few days ago.
Question:
Accept two inputs.
A big number of N digits,
The number of questions Q to be asked.
In each of the question, you have to find if the number formed by the string between indices Li and Ri is divisible by 7 or not.
Input:
First line contains the number consisting on N digits. Next line contains Q, denoting the number of questions. Each of the next Q lines contains 2 integers Li and Ri.
Output:
For each question, print "YES" or "NO", if the number formed by the string between indices Li and Ri is divisible by 7.
Constraints:
1 ≤ N ≤ 105
1 ≤ Q ≤ 105
1 ≤ Li, Ri ≤ N
Sample Input:
357753
3
1 2
2 3
4 4
Sample Output:
YES
NO
YES
Explanation:
For the first query, number will be 35 which is clearly divisible by 7.
Time Limit: 1.0 sec for each input file.
Memory Limit: 256 MB
Source Limit: 1024 KB
My Approach:
Now according to the constraints, the maximum length of the number i.e. N can be upto 105. This big a number cannot be fitted into a numeric data structure and I am pretty sure thats not the efficient way to go about it.
First Try:
I thought of this algorithm to apply the generic rules of division to each individual digit of the number. This would work to check divisibility amongst any two numbers, in linear time, i.e. O(N).
static String isDivisibleBy(String theIndexedNumber, int divisiblityNo){
int moduloValue = 0;
for(int i = 0; i < theIndexedNumber.length(); i++){
moduloValue = moduloValue * 10;
moduloValue += Character.getNumericValue(theIndexedNumber.charAt(i));
moduloValue %= divisiblityNo;
}
if(moduloValue == 0){
return "YES";
} else{
return "NO";
}
}
But in this case, the algorithm has to also loop through all the values of Q, which can also be upto 105.
Therefore, the time taken to solve the problem becomes O(Q.N) which can also be considered as Quadratic time. Hence, this crossed the given time limit and was not efficient.
Second Try:
After that didn't work, I tried searching for a divisibility rule of 7. All the ones I found, involved calculations based on each individual digit of the number. Hence, that would again result in a Linear time algorithm. And hence, combined with the number of Questions, it would amount to Quadratic Time, i.e. O(Q.N)
I did find one algorithm named Pohlman–Mass method of divisibility by 7, which suggested
Using quick alternating additions and subtractions: 42,341,530
-> 530 − 341 = 189 + 42 = 231 -> 23 − (1×2) = 21 YES
But all that did was, make the time 1/3rd Q.N, which didn't help much.
Am I missing something here? Can anyone help me find a way to solve this efficiently?
Also, is there a chance this is a Dynamic Programming problem?
There are two ways to go through this problem.
1: Dynamic Programming Approach
Let the input be array of digits A[N].
Let N[L,R] be number formed by digits L to R.
Let another array be M[N] where M[i] = N[1,i] mod 7.
So M[i+1] = ((M[i] * 10) mod 7 + A[i+1] mod 7) mod 7
Pre-calculate array M.
Now consider the expression.
N[1,R] = N[1,L-1] * 10R-L+1 + N[L,R]
implies (N[1,R] mod 7) = (N[1,L-1] mod 7 * (10R-L+1mod 7)) + (N[L,R] mod 7)
implies N[L,R] mod 7 = (M[R] - M[L-1] * (10R-L+1 mod 7)) mod 7
N[L,R] mod 7 gives your answer and can be calculated in O(1) as all values on right of expression are already there.
For 10R-L+1 mod 7, you can pre-calculate modulo 7 for all powers of 10.
Time Complexity :
Precalculation O(N)
Overall O(Q) + O(N)
2: Divide and Conquer Approach
Its a segment tree solution.
On each tree node you store the mod 7 for the number formed by digits in that node.
And the expression given in first approach can be used to find the mod 7 of parent by combining the mod 7 values of two children.
The time complexity of this solution will be O(Q log N) + O(N log N)
Basically you want to be able to to calculate the mod 7 of any digits given the mod of the number at any point.
What you can do is to;
record the modulo at each point O(N) for time and space. Uses up to 100 KB of memory.
take the modulo at the two points and determine how much subtracting the digits before the start would make e.g. O(N) time and space (once not per loop)
e.g. between 2 and 3 inclusive
357 % 7 = 0
3 % 7 = 3 and 300 % 7 = 6 (the distance between the start and end)
and 0 != 6 so the number is not a multiple of 7.
between 4 and 4 inclusive
3577 % 7 == 0
357 % 7 = 0 and 0 * 10 % 7 = 0
as 0 == 0 it is a multiple of 7.
You first build a list of digits modulo 7 for each number starting with 0 offset (like in your case, 0%7, 3%7, 35%7, 357%7...) then for each case of (a,b) grab digits[a-1] and digits[b], then multiply digits[b] by 1-3-2-6-4-5 sequence of 10^X modulo 7 defined by (1+b-a)%6 and compare. If these are equal, return YES, otherwise return NO. A pseudocode:
readString(big);
Array a=[0]; // initial value
Array tens=[1,3,2,6,4,5]; // quick multiplier lookup table
int d=0;
int l=big.length;
for (int i=0;i<l;i++) {
int c=((int)big[i])-48; // '0' -> 0, and "big" has characters
d=(3*d+c)%7;
a.push(d); // add to tail
}
readInt(q);
for (i=0;i<q;i++) {
readInt(li);
readInt(ri); // get question
int left=(a[li-1]*tens[(1+ri-li)%6])%7;
if (left==a[ri]) print("YES"); else print("NO");
}
A test example:
247761901
1
5 9
61901 % 7=0. Calculating:
a = [0 2 3 2 6 3 3 4 5 2]
li = 5
ri = 9
left=(a[5-1]*tens[(1+9-5)%6])%7 = (6*5)%7 = 30%7 = 2
a[ri]=2
Answer: YES

Simple Modulo expression [duplicate]

This question already has answers here:
Modulus division when first number is smaller than second number
(6 answers)
Closed 7 years ago.
I understand that a mod operator finds the remainder of two numbers. However, I am having trouble understanding the concept when the numbers are reversed. Meaning, a smaller number comes first in the operation.
int x = 4 % 3 ; // prints out 1
However, can someone explain this to me:
int y = 1 % 4 ; // prints out 1
int z = 2 % 3 ; // prints out 2
Thanks in advance!
Whether the left-hand side of the operator is larger than the right is irrelevant. There is always a remainder for any division operation, it's just that sometimes it's 0.
So 5 % 2 returns 1, just like 4 % 3 returns 1.
The value of any modulo operation of the form x % n will be 0 to n - 1 inclusive, for positive x. It will be -1(n-1) to 0 inclusive for negative x.
Are you sure about the int y that prints out 2?
The int z though seems normal :
2= 0*3 + 2
int y = 1 % 4 should print 1 because:
1=0*4 + 1
It works the same as when a bigger number comes first, you just take the remainder of the division of the first one by the second one.

Modulus division when first number is smaller than second number

I apologize if this is a simple question but I'm having trouble grasping the concept of modulus division when the first number is smaller than the second number. For example when 1 % 4 my book says the remainder is 1. I don't understand how 1 is the remainder of 1 % 4. 1 / 4 is 0.25. Am I thinking about modulus division incorrectly?
First, in Java, % is the remainder (not modulo) operator, which has slightly different semantics.
That said, you need to think in terms of integer-only division, as if there were no fractional values. Think of it as storing items that cannot be divided: you can store zero items of size 4 in a storage of overall capacity one. Your remaining capacity after storing the maximum number of items is one. Similarly, 13%5 is 3, as you can fit 2 complete items of size 5 in a storage of size 13, and the remaining capacity is 13 - 2*5 = 3.
If you divide 1 by 4, you get 0 with a remainder of 1. That's all the modulus is, the remainder after division.
I am going to add a more practical example to what "Jean-Bernard Pellerin" already said.
It is correct that if you divide 1 by 4 you get 0 but, Why when you do 1 % 4 you have 1 as result?
Basically it is because this:
n = a / b (integer), and
m = a % b = a - ( b * n )
So,
a b n = a/b b * n m = a%b
1 4 0 0 1
2 4 0 0 2
3 4 0 0 3
4 4 1 0 0
5 4 1 4 1
Conclusion: While a < b, the result of a % b will be "a"
Another way to think of it as a representation of your number in multiples of another number. I.e, a = n*b + r, where b>r>=0. In this sense your case gives 1 = 0*4 + 1. (edit: talking about positive numbers only)
I think you are confused between %(Remainder) and /(Division) operators.
When you say %, you need to keep dividing the dividend until you get the remainder 0 or possible end. And what you get in the end is called Remainder.
When you say /, you divide the dividend until the divisor becomes 1. And the end product you get is called Quotient
Another nice method to clear things up,
In modulus, if the first number is > the second number, subtract the second number from the first until the first number is less than the second.
17 % 5 = ?
17 - 5 = 12
12 % 5 = ?
12 - 5 = 7
7 % 5 = ?
7 - 5 = 2
2 % 5 = 2
Therefore 17 % 5, 12 % 5, 7 % 5 all give the answer of 2.
This is because 2 / 5 = 0 (when working with integers) with 2 as a remainder.

Tennis tournament algorithm

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.

Categories