I'm trying to write a piece of validation code for an input of numbers. The numbers have to contain 0 to 8. The order does not matter, but the digits cannot be repeated.
E.g. 1 4 7 8 0 2 5 3 6 //valid
1 1 3 6 3 8 0 5 4 //invalid as 1 is repeated
I have a regex so far that takes in 9 unique digits:
String pattern = "^(?!.*(.).*\\1)\\d{9}";
E.g. 123456780 //valid
112345678 //invalid as 1 is repeated
1 2 3 4 5 6 7 8 0 //invalid
All I need is to add the bit where it takes in the digits separated by a space!
Thanks.
This is really abuse of regex :D but
^(?!.*(\d).*\1)(?:[0-8] ){8}[0-8]$
should do it. Make sure only digits are taken into consideration in the part where you disallow repetition; then you can have eight digit-space pairs followed by a digit at the end (with correct digits).
I'm not sure you need a regex for this. Consider using a Set:
Scanner sc = new Scanner(System.in);
Set<Integer> set = new HashSet<>();
int count = 0;
while (count < 9) {
System.out.println("Enter a number:");
int num = sc.nextInt();
if (num >= 0 && num <= 8) {
set.add(num);
}
count++;
}
System.out.println(set.size() == 9);
Or if your input comes in one go:
String[] nums = sc.nextLine().split("\\s+");
for (String num : nums) {
set.add(Integer.parseInt(num));
}
You'll have to consider checking for invalid input. Or you could check the nums is 9 first before adding to set and return false then straight away.
Related
Tyson is all prepared for the Beyblade World Championship. The tournament is team-based and each team can have N members. A player can fight against a single player only. Team G-Revolution is all excited and pumped up as they have practised a lot. Kenny, the mind of team G-Revolution, has created a database where he has the data about the power of other teams’ members and his own team members. The tournament is going to start in some time and Kenny moves to the cafeteria to have a snack before the competition.
The team G-Revolution is to fight in some time and they are tensed up as someone has kidnapped Kenny from the cafeteria. They have made a police complaint and the police are searching for Kenny. Luckily, they have found his device with all the data. The problem is, the data is present randomly and not in the order they have to fight the opponent. Team G-Revolution wants to win at any cost and for that, they need the order in which they have to fight optimally to win the maximum number of battles.
A player can win only when his/her beyblade power is strictly greater than the opponents beyblade power.
Example:
Consider the team size is 3, N = 3
The 3 players of both the teams are shown with their beyblade powers.
Team G-Revolution is presented in the order: Tyson, Max, Ray
Team All Starz is presented in the order: Michael, Eddy, Steve
With the given arrangement, Team G-Revolution would be able to win only 1 fight. Team G-Revolution should be shuffled in an optimal manner as below:
The maximum number of fights Team G-Revolution can win is 2 when they are arranged optimally or fight in an optimal order.
Team G-Revolution needs help with the device. Tyson has heard about your skills and called you up to help them shuffle their positions in an order such that they would be able to win the maximum number of fights. Can you help Tyson and Team G-Revolution?
Input Format
The first line of input consists of the number of test cases, T
The first line of each test case consists of the number of members each team can have, N.
The second line of each test case consists of N space-separated integers representing the power of beyblades of Team G-Revolution members.
The third line of each test case consists of N space-separated integers representing the power of beyblades of opponent team members.
Constraints
1<= T <=100000
1<= N <=100000
0<= Power of Beyblade <= LLONG_MAX
Output Format
For each test case, print the maximum number of fights Team G-Revolution can win if they go to fight in an optimal manner.
Sample TestCase 1
Input
1
10
3 6 7 5 3 5 6 2 9 1
2 7 0 9 3 6 0 6 2 6
Output
7
Code:
import java.io.*;
import java.util.*;
import java.lang.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
import java.util.Arrays;
public class CandidateCode {
private static int testCase = 0;
private static int numOfMembers = 0;
private static int gRevolutionTeamSize = 0;
private static int opponentTeamSize = 0;
private static int numOfGRevolutionWins = 0;
private static final Integer initial_Index = 0;
private static final Integer second_Index = 1;
private static final Integer third_Index = 2;
private static final Integer fourth_Index = 3;
private static final Integer noOfIndex = 4;
private static final Integer testNumber = 100000;
private static String[] powerOpponentTeamArr = null;
private static String[] powerGRevolutionTeamArr = null;
public static void main(String args[] ) throws Exception {
List<Integer> gRevolutionWinsList = new ArrayList<Integer>();
Scanner scan = new Scanner(System.in);
String[] input = new String[noOfIndex];
try{
for(int i = 0; i < input.length; i++){
input[i] = scan.nextLine();
}
if (!validateInput(input[initial_Index],input[second_Index])) {
System.exit(initial_Index);
}
}
catch(Exception ex){
}
finally{
scan.close();
}
testCase = Integer.parseInt(input[initial_Index]);
numOfMembers = Integer.parseInt(input[second_Index]);
String gRevolutionMembers = input[third_Index];
powerGRevolutionTeamArr = gRevolutionMembers.split(" ");
String opponentMembers = input[fourth_Index];
powerOpponentTeamArr = opponentMembers.split(" ");
gRevolutionTeamSize = powerGRevolutionTeamArr.length;
long[] totalGRevolutionTeamArr = new long[gRevolutionTeamSize];
for (int i = 0; i < gRevolutionTeamSize; i++){
totalGRevolutionTeamArr[i] = Long.parseLong(powerGRevolutionTeamArr[i]);
validateInputPower(totalGRevolutionTeamArr[i]);
}
opponentTeamSize = powerOpponentTeamArr.length;
long[] totalOpponentTeamArr = new long[opponentTeamSize];
for (int i = 0; i < opponentTeamSize; i++){
totalOpponentTeamArr[i] = Long.parseLong(powerOpponentTeamArr[i]);
validateInputPower(totalOpponentTeamArr[i]);
}
Arrays.sort(totalGRevolutionTeamArr);
Arrays.sort(totalOpponentTeamArr);
for(int i = 0; i < numOfMembers; i++){
if((totalGRevolutionTeamArr[i] - totalOpponentTeamArr[i]) > 0){
numOfGRevolutionWins = numOfGRevolutionWins + 1;
}
}
int numCount = numOfGRevolutionWins;
int moveMembers = numOfMembers - numCount - 1;
if(moveMembers >= 0){
for(int i = 0; i < moveMembers; i++){
long teamMember = totalOpponentTeamArr[numCount];
int j;
int numOfGRevolutionWins_1 = 0;
for (j = 0; j < moveMembers; j++){
totalOpponentTeamArr[numCount + j] = totalOpponentTeamArr[numCount + j + 1];
}
totalOpponentTeamArr[numCount + j] = teamMember;
for(int k = numCount; k < numOfMembers; k++){
if((totalGRevolutionTeamArr[k] - totalOpponentTeamArr[k]) > 0){
numOfGRevolutionWins_1 = numOfGRevolutionWins_1 + 1;
}
}
gRevolutionWinsList.add(numOfGRevolutionWins_1);
}
numOfGRevolutionWins = numOfGRevolutionWins + Collections.max(gRevolutionWinsList);
}
System.out.println(numOfGRevolutionWins);
}
private static boolean validateInput(String testCases, String noOfPlayers) {
int test1 = Integer.parseInt(testCases);
int numOfPlayers = Integer.parseInt(noOfPlayers);
if (second_Index <= test1 && test1 <= testNumber && second_Index <= numOfPlayers && numOfPlayers <= testNumber) {
return true;
}
return false;
}
private static void validateInputPower(long memberPower) {
if (!(initial_Index <= memberPower && memberPower <= Long.MAX_VALUE)) {
System.exit(initial_Index);
}
}
}
Result:
Input from line 1 = 1
Input from line 2 = 10
Input from line 3 = 3 6 7 5 3 5 6 2 9 1
Input from line 4 = 2 7 0 9 3 6 0 6 2 6
Scanner input job succeeded if we see some value here = 1
Finally block is called to free Scanner job
Value from first line and parsed string to int = 1
Value from second line and parsed string to int = 10
Value from third line = 3 6 7 5 3 5 6 2 9 1
Value from fourth line = 2 7 0 9 3 6 0 6 2 6
Parsed string number 1 to long : 3
Parsed string number 2 to long : 6
Parsed string number 3 to long : 7
Parsed string number 4 to long : 5
Parsed string number 5 to long : 3
Parsed string number 6 to long : 5
Parsed string number 7 to long : 6
Parsed string number 8 to long : 2
Parsed string number 9 to long : 9
Parsed string number 10 to long : 1
Parsed string number 1 to long : 2
Parsed string number 2 to long : 7
Parsed string number 3 to long : 0
Parsed string number 4 to long : 9
Parsed string number 5 to long : 3
Parsed string number 6 to long : 6
Parsed string number 7 to long : 0
Parsed string number 8 to long : 6
Parsed string number 9 to long : 2
Parsed string number 10 to long : 6
After sorting number 1 is : 1
After sorting number 2 is : 2
After sorting number 3 is : 3
After sorting number 4 is : 3
After sorting number 5 is : 5
After sorting number 6 is : 5
After sorting number 7 is : 6
After sorting number 8 is : 6
After sorting number 9 is : 7
After sorting number 10 is : 9
After sorting number 1 is : 0
After sorting number 2 is : 0
After sorting number 3 is : 2
After sorting number 4 is : 2
After sorting number 5 is : 3
After sorting number 6 is : 6
After sorting number 7 is : 6
After sorting number 8 is : 6
After sorting number 9 is : 7
After sorting number 10 is : 9
Number of G-Revolution wins are : 5
Number will be used is : 4
Number shifted is : 6
Number of wins afterwards : 1
Number shifted is : 6
Number of wins afterwards : 2
Number shifted is : 6
Number of wins afterwards : 2
Number shifted is : 7
Number of wins afterwards : 2
Number of wins afterwards in list : [1, 2, 2, 2]
Answer is = 7
You have fallen into the classic trap of constructing an algorithm based on the example rather than considering the general case. This is not a criticism, but something that we all have to be aware of in order to fight against.
Take a look at your loop here :
for (j = 0; j < moveMembers; j++){
totalOpponentTeamArr[numCount + j] = totalOpponentTeamArr[numCount + j + 1];
}
totalOpponentTeamArr[numCount + j] = teamMember;
So in the given example, a straight sort results in us winning the first numCount = 5 matches, so your algorithm looks to leave those 5 results and rearrange our team from position 6.
Trouble is, that's only for the supplied example.
Consider if the opposing team didn't have strengths 0 or 1, but replaced those with 3 - that is, their team was : 3 3 3 3 3 6 6 6 7 9.
In that case, on the initial straight-sorted matchups, we would lose the first 4 and only win 1 match (the 5-3).
Consider how your algorithm would behave in that scenario, rearranging the team after numCount = 1 ?
So a better algorithm would be :
1) Sort each team as you do at present
2) Starting with their weakest member, find our weakest member that would beat them
3) Continue with their next weakest member, finding our weakest member who would beat that one
etc
At each step, if we have to skip over one of our members, make a note of them (in a list or something). When we come come to the point that we run out of members to match against one of theirs, then just fill in the rest of the matches with this list of our skipped-over members - after all, they were never going to win a match anyway !
t=int(input())
while t>0:
n=int(input())
gr=[int(x) for x in input().split()]
op=[int(x) for x in input().split()]
gr.sort()
op.sort()
l=r=count=0
while l<n and r<n:
if gr[l]>op[r]:
l+=1
r+=1
count+=1
elif gr[l]<=op[r]:
l+=1
print(count)
t-=1
I also appear for the same contest and I got full marks.
Might my code be helpful for you.
to solve this you can sort both the list to reverse order and compare each other. Refer below a working example of in Python:
def main():
testCase=int(input())
while testCase>0:
count=0
numberOfPlayer=int(input())
firstPlayer=list(map(int,input().split()))
secondPlayer=list(map(int,input().split()))
firstPlayer.sort(reverse=True)
secondPlayer.sort(reverse=True)
p=0
for i in range(numberOfPlayer):
for j in range(p,numberOfPlayer):
if firstPlayer[i]>secondPlayer[j]:
p=j+1
count+=1
break
print(count)
testCase-=1
main()
# Made by Ankur Patel
For java based solution
refer
My logic:
// Logic for comparing team battles in optimum manner
while(gRev < numOfMembers){
if((totalGRevolutionTeamArr[gRev] - totalOpponentTeamArr[opp]) > 0){
gRev++;
opp++;
numOfWins++;
}
else{
gRev++;
}
}
I need to write a method that adds the two last elements of two arrays together and add the sum on another array. But if the two elements are more than 10, then I would need to carry that number to the next array.
This program should be similar to what an odometer does.
Here is my sample code.
int [] sum(int []number1, int []number2)
{
int [] total;
int carry = 0;
for ( int k = numbers1 - 1; k >= 0; k++)
{
sum = number1[k] + number2[k] + carry;
carry = sum/10;
total[k] = sum
}
return total;
}
An example output would be:
0 1 2 3 4
0 8 9 9 9
4 5 7 0 3
5 4 7 0 2
So the top array is just a visual aid that tells where the position for the number is.
The program is suppose to add the next two arrays together. i.e. 9 + 3 = 12
Since 12 is above 9, it carries over the 10 to the next set of arrays, that is why the third array only has a 2 in its place, and that is why the next array is 9 + 0 = 0; because the 10 was carried over.
I am not sure why my code won't work. I don't get the right numbers. Could anyone give any hints or solution to the problem?
-Thanks
I assume numbers1 is the number of elements in the array.
In this case it should be k-- instead of k++ because you are starting from the last element and moving backword.
Question : A set of numbers separated by space is passed as input. The program must print the largest snake sequence present in the numbers. A snake sequence is made up of adjacent numbers such that for each number, the number on the right or left is +1 or -1 of it's value. If multiple snake sequences of maximum length is possible print the snake sequence appearing in the natural input order.
Example Input/Output 1:
Input:
5 6 7 9 8 8
Output:
5 6 7 8 9 8
8 9 8 7 6 5
Example Input/Output 2:
Input:
9 8 7 5 3 0 1 -2 -3 1 2
Output:
3 2 1 0 1
void doPermute(int[] in, StringBuffer out, boolean[] used, int length, int level, StringBuffer max) {
if (level == length) {
int count = 0;
for (int i = 1; i < out.length(); i++) {
if (Math.abs(Character.getNumericValue(out.charAt(i)) - Character.getNumericValue(out.charAt(i - 1))) != 1) {
//System.out.println(Character.getNumericValue(i) - Character.getNumericValue(i - 1) + " " + i + " yes");
count++;
break;
}
}
if (count == 0) {
max.append(out + " ");
}
return;
}
for (int i = 0; i < length; ++i) {
if (used[i]) {
continue;
}
out.append(in[i]);
used[i] = true;
doPermute(in, out, used, length, level + 1, max);
used[i] = false;
out.setLength(out.length() - 1);
}
}
As i am using StringBuffer my code passed the test cases that contains positive value (first test case) but failed in test cases containing negative values(second test case).
Update:-
I replaced stringbuffer with Integer[] and made few changes.it works fine for smaller inputs of length 8 or 9. How to make it fast for larger inputs of length 13 to 15?
Have you tried doing the process using an array of integers?
Scanner sc = new Scanner(System.in);
String s = sc.nextLine(); //The numbers entered in string format separated by spaces
String ss = s.split(" "); //Numbers separated by space will be put as individual numbers in a String array but each number is still in string format
int l = ss.length, i = 0;
int[] n = new int[l]; //The integer array which will store the values
for(i = 0; i < l; i++)
{
n[i] = Integer.parseInt(ss[i]); //Has integers now instead of string numbers
}
There might be creation of a few extra arrays but then calling the Character.getNumericValue() function repeatedly can also reduce efficiency. Also might solve your StringBuffer problem.
But SkillRack is very annoying anyway.
Your comparison isn't finding adjacent numbers for negative values.
For example: Abs(-2) - (-3) = 5 but -2 and -3 should be adjacent.
Ok. I see you're parsing - and digit separately.
Given the requirement of what a snake sequence is, the longest snake sequence for "5 6 7 9 8 8" is "5 6 7". The output listed above does not correspond to the definition: " adjacent numbers such that for each number, the number on the right or left is +1 or -1 of it's value". How does "5 6 7 8 9 8" meet the definition of snake sequence for "5 6 7 9 8 8"? Sorry I couldn't help.
You might want to parse the code into Integers, store the longest sequences in a map).
#Test
public void testSnake(){
String t2 = "9 8 7 5 3 0 1 -2 -3 1 2";
List<String> numsStr = Arrays.asList(t2.split(" "));
List<Integer> nums = new ArrayList();
HashMap<Integer,List<Integer> > numMap = new HashMap();
numsStr.forEach((s) -> {
Integer val = Integer.decode(s);
nums.add(val);
});
nums.forEach((num) -> {
System.out.println("num: " + num);
// track longest sequence, store in numMap
});
// Print numMap
}
How to print the following output with only one for-loop in java?
1 2 3 4 5 6 7 8 9 1 0 9 8 7 6 5 4 3 2 1
Code snippet:
class Series{
public static void main(String args[]){
for(int i=1; i<=10; i++){
System.out.println(i);
}
System.out.println(i);
for(int j=9; j>=0; j--){
System.out.println(j);
}
}
My program's in the following manner. Can anyone correct it?
public static void main(String...strings ){
int dir = 1;
for(int i=1; i>0; i+=dir){
if(i == 10)
dir = -1;
System.out.print(i+" ");
}
}
Output:
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
The series in the question is wrong.
It should be: 1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
The code, in one loop, is as follows:
int ctr = 1;
for(int i = 1; i > 0; i += ctr)
{
if(i == 10)
{
ctr = -1;
}
System.out.print(i + " ");
}
Every sequence follows a pattern, Let's try finding one in this.
To work with this code, analyze What loop would print with the variable that you increment and What you want in the output?
In your problem, assuming that the number you are entering is entered by user i.e. n, you want 2*n - 1 numbers in your sequence. Hence we now have the limits of our loop
For n=5, Under no Conditions the loop would simply print a sequence like this
1 2 3 4 5 6 7 8 9 provided you are starting your loop from 1.
The sequence you want is 1 2 3 4 5 4 3 2 1.
Now looking at both the sequences you can see that the sequence is same till the mid point that is till the value of n is reached. Now if you observe the pattern further if you subtract 2 from 6 you get 4 that is the number you want in your sequence. Similarly when you subtract 4 from 7 you get 3 which is the next number in the sequence you required.
Hence the pattern this sequence follows is that after the loop reaches the value provided by the user you need to subtract (2 * k) from the next number where k starts from 1 and increases with every iteration
Now you know how to achieve the pattern which would be easy to achieve using conditional statements.
PS: let's assume an added constraint of using no conditional statements then we have to write an arithmetic expression to solve our problem.
Following the pattern again the expression must display i where i is the variable incremented in the loop
so our code looks like
for (i = 1; i<=2*n - 1;i++)
{
System.out.print(i);
}
Now to get the pattern we need to subtract multiples of 2 after the user provided integer n is reached. But whatever we subtract should also not affect out first n integers.
Since we know we have to subtract multiples of 2 we know the expression we have to subtract would look like 2 * (____). As we want a sequence of multiples we can obtain that using %. As soon as the number goes over n the % operator on i would give us back sequence from 0 to n-1 hence generating multiples of 2.
Now our expression comes to 2 * (i % n). But the problem is that it would also subtract from the first 4 integers which we don't want so we have to make changes such that this expression will work only after loop reaches the value provided by the user.
As we know the division / operator provides us with the quotient. Hence it would yield us 0 till we reach the value of user defined number and 1 for the rest of the sequence as we run our loop till 2*n -1. Hence multiplying this expression to our previous expression yields 2*(i%n)*(i/n)
And there we have it our final code to generate the sequence would be
for (int i = 1;i<2*r;i++)
{
System.out.print(i - 2 * (i%r)*(i/r));
}
Observe the above code for the first n-1 integers i/r would make subtracted expression 0 and for i = n, i % r would make the expression 0. For the rest of the sequence i / r would generate value 1 and hence we will get multiples of 2 from 2 *( i % r) to provide us with the sequence
try this
int j = 10;
for (int i = 1; i <= 10; i++) {
if(i<10)
System.out.print(" " +i);
if(i==10){
i--;
System.out.print(" " +j);
if(j==1){
i++;
}
j--;
}
}
OutPut
1 2 3 4 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
Something like this?
for(int i=0;i<20;i++) {
if((i/10)%2 == 0)
System.out.print(i%10 + " ");
else
System.out.print((10-(i%10)) + " ");
}
Try this code, You just need a if condition in for loop.
int i = 1;
for(int j=1; j<=20; j++)
{
if(j<11)
System.out.print(j+" ");
else
{
System.out.print((j - i == 10 ?" ": (j-i + " ")));
i = i+2;
}
}
public class forLoopTest {
public static void main(String[] args) {
for (int i = 1; i < 10; i++) {
System.out.print(i + " ");
}
for (int j = 10; j >= 1; j--) {
System.out.print(j + " ");
}
}
}
From Java Malik textbook- determine if an number is divisible by 11..
Code Solution provided:
import java.util.*;
public class Divby11
{
static Scanner console = new Scanner(System.in);
public static void main (String[] args)
{
int num, temp, sum;
char sign;
System.out.print("Enter a positive integer: ");
num = console.nextInt();
System.out.println();
temp = num;
sum = 0;
sign = '+';
do
{
switch (sign)
{
case '+' :
sum = sum + num % 10;
sign = '-';
break;
case '-' :
sum = sum - num % 10;
sign = '+';
}
num = num / 10; //remove the last digit
}
while (num > 0);
if (sum % 11 == 0)
System.out.println(temp + " is divisible by 11");
else
System.out.println(temp + " is not divisible by 11");
}
Why go through all the effort above and just say...
if (sum % 11 == 0)
System.out.println(temp + " is divisible by 11");
else
System.out.println(temp + " is not divisible by 11");
Can any of you experts see why the author would do it this way (long way)?
for the Divisibility Rule of 11:
form the alternating sum of the digits
if this sum is divisible for 11 then the number is divisible for 11
Examples
68090 = 0 - 9 + 0 - 8 + 6 = -11 => TRUE
493827 = 7 - 2 + 8 - 3 + 9 - 4 = 15 = 4 => FALSE
This code example isn't actually dividing by eleven. If you see, it's alternating between adding and subtracting each digit, then checks at the very end if the result is divisible by 11.
For example, look at the following number and how this algorithm works with it:
Start with sum=0, sign='+', num=517
First iteration: sum=7, sign='-', num=51
Second iteration: sum=6, sign='+', num=5
Final iteration: sum=11, sign='-', num=0
The final result is divisible by eleven.
EDIT: The algorithm does indeed look to be implementing the divisibility rule for 11 as dfa mentions in his answer.
You will have to provide more context from the book as to what the author was trying to demonstrate. This code example does not check to see if the number entered is divisible by 11. What it does is it adds every other digit, subtracts every other digit and then checks THAT number to see if it's divisible by 10.
EX
Entered number is 4938
It takes the 8 adds it to sum
Divides by ten giving 493
Takes the 3 subtracts it from sum: sum = 5
Divides by ten giving 49
Takes 9 and adds it to sum: sum = 14
Divides by ten giving 4
Takes 4 subtracts it from sum: sum = 10
THEN it checks if this is divisible by 11.
Ok, I know why now. He/she's trying to teach you something besides computing about numbers
I suspect it is simulating the manual test that digits in the odd positions and the digits in the even positions differ by a factor of 11. In practice using %11 would be the way to go.
EDIT: If the example were truly trying to avoid doing % 11, it should send the sum through again until it is 0.
It an example to show how to implement that particular check. Using your example would not demonstrate the same code methodologies.