Why is the last line not being scanned - java

I want to scan some lines of number. The lines with single number num represent how many rows there will be for the 2d array, and the next num lines will consist of 2 numbers and they should be recorded in the array called townCord.
An example input looks like this:
4
1 2
2 1
1 1
2 2
3
3 1
2 2
1 3
The last line, 1 3, is not in the 2d array though. I think the reason is because I split by the pattern " ". I wonder how I can fix this bug and record all of them in the array? Thanks in advance
public static boolean checkWin(int x1,int y1, int x2, int y2){
if(y1==y2){
return false;
} else{
if(Math.toDegrees(Math.atan((Math.abs((double)(y1-y2)))/(Math.abs((double)(x1-x2)))))==45){
return true;
}else{
return false;
}
}
}
Scanner sc = new Scanner(System.in);
while (sc.hasNextLine()) {
int num = Integer.parseInt(sc.nextLine());
int townCord[][] = new int[num][2];
for (int i = 0; i < townCord.length; i++) {
if(sc.hasNext()){
String[] line = sc.nextLine().trim().split(" ");
for (int j = 0; j < line.length; j++) {
townCord[i][j] = Integer.parseInt(line[j]);
}
}else{
break;
}
}
double overallCount = 0;
double winCount = 0;
for (int i = 0; i<num;i++){
for(int j = 0;j<num;j++){
overallCount++;
if(checkWin(townCord[i][0],townCord[i][1],townCord[j][0],townCord[j][1])){
winCount++;
}
}
}
System.out.println(winCount/overallCount);
}
sc.close();
}
EDIT: I think this is not working properly, because unless I hit enter after entering these numbers, I do not get the correct result.
output should be 2 numbers, yet it only prints one. I think by hitting enter, I add an extra line after the last 1 3 input, which makes the code working. Without doing that I only get 0.25, one number.
The input must be fixed and I cannot add anything to it. If you try to directly copy&paste the whole input thingy, it probably won't work.
EDIT 2: I posted full code and hopefully I did not make any stupid mistakes on the part that's not relevant to the scanner

Related

split the numbers and add them together code is not working properly, What is it am doing wrong?

I wrote the below code to split the numbers and add them together, it is working fine if my number is not starting with 1 eg, 123456 -- not working, 234567 -- working, can anyone tell me what I am doing wrong here?
public class Basic {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
int sum =0;
for (int i = 0; i <input; i++) {
int A = input%10;
System.out.println("test1 " +A);
input = input/10;
System.out.println("test " +input);
sum = sum + A;
}
System.out.println(sum);
}
It's the loop:
for (int i = 0; i <input; i++) {
You are dividing the int input into its digits. So the loop should run until all digits are eaten up:
while (input > 0) {
That should fix it
In every iteration, you're updating input, so for example, step by step:
input = 123
i = 0
sum = 0
input = 12
i = 1
sum = 3
input = 1
i = 2
sum = 5
Then check the condition i < input it's 2 < 1, it's not, so it's skipping the last digit, the same happens for 234 it returns 7 rather than 9, because of the same thing.
You could change your for-loop for a do-while:
do {
//Your code here
} while (input > 0);
The problem is in i < input; i++ in your loop. It's not problem with only numbers starting with 1, for example 23445352 isn't work correctly too. I see 26 instead of 28.
Check the next steps in the loop, for 123 input, after two steps, you have sum = 5, input = 1 and... i = 2. So the condition for exiting the loop returns true without considering the last digit.

Plus Multiply | December Long Challenge Division 2

The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.
The first line of each test case contains a single integer N.
The second line contains N space-separated integers A1,A2,…,AN.
Output
For each test case, print a single line containing one integer ― the desired number of pairs.
Example Input
2
3
2 4 2
3
0 2 3
Example Output
1
0
My solution looks like:
class Codechef {
public static void main (String[] args) throws java.lang.Exception {
ArrayList<Integer> resultList = new ArrayList<Integer>();
Scanner scanner = new Scanner(System.in);
int T;
T = scanner.nextInt();
for(int i = 0; i < T; i++) {
int N;
N = scanner.nextInt();
int A[] = new int[N];
for(int j = 0; j < N; j++) {
A[j] = scanner.nextInt();
}
quick_sort(A, 0, N-1);
int pos = 0, pairs = 0;
while(pos < A.length - 1) {
if(A[pos] == A[pos + 1]) {
pos += 2;
pairs += 1;
} else {
++pos;
}
}
resultList.add(pairs);
}
for(int pairCount : resultList) {
System.out.println(pairCount);
}
scanner.close();
}
}
It successfully runs the example test cases but fails on submission, My question is, if the input is something like 1 1 2 2 1, then what should be the answer, 3? as there are 2 pairs of 1, and 1 of 2's.
Also, what will be the suggested data structure to be used for this purpose, Java with primitive data types is taking too much longer to execute it with 40,000 input values. What's wrong with my solution
To answer your first question, I'd say yes that each pair of 1's would count separately so you'd get 3.
I think your code is failing since you're only counting touching pairs after you sort.
For example,
1 1 1, you find the first pair at index 0/1, but then advance pos += 2.This means you're missing the two other pairs of 1's.
Your solution seems to be O(nlogn) because of sorting but I can think of a O(n) solution.
int[] backing = new int [10];
for (int j = 0; j < N; j++) {
int x = scanner.nextInt();
backing[x]++;
}
//At this point, you have a backing array with the frequency of each integer
You'll want something similar to this to calculate the number of pairs. It's the frequency of each integer choose 2, since you want to choose each occurrence of a pair.
So for example if you know you have 5 1's, then you'll compute:
5!/(2!*3!) = 10

Java Scanner .nextInt() skipping inputs

Java novice here, trying to scan through the input in the form below:
3
3 3
101
000
101
1 2
11
5 5
10001
00000
00000
00000
10001
(The first digit is the number of test cases, followed by row and column, and 0s and 1s is the state of the world, and so on. Basically, like any typical BFS questions)
Below is a part of my Java code where I'm trying to get the input from the console. The comments are the values I see in the watch section while debugging:
public static void main(String[] args) {
Scanner in = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
int t = in.nextInt(); // t: 3, in.nextInt(): 3 as expected
for (int i = 1; i <= t; i++) { // i: 1, t: 3, in.nextInt(): 3 (not sure which "3")
int row = in.nextInt();
// after this line in.nextInt(): 101 and row: 0 which are all WEIRD
int column = in.nextInt();
// now here it's in.nextInt(): 2 and column: 2
int world[][] = new int[row][column];
// in.nextInt(): 11 now and as we see it changed its value when I didn't even call it
TreeMap<Integer, ArrayList<int[]>> distancesRandAcc = new TreeMap<Integer, ArrayList<int[]>>();
distancesRandAcc.put(0, new ArrayList<int[]>());
for (int j = 0; j < row; j++) {
int temp = in.nextInt();
char[] s = Integer.toString(temp).toCharArray();
for (int k = 0; k < column; k++){
world[j][k] = Character.getNumericValue(s[k]);
}
}
int result = calculateDeliveryTime(world, row, column, distancesRandAcc);
System.out.println("Case #" + i + ": " + result);
}
}
This does something weird that goes beyond 'common sense'. I was debugging line by line after putting all the inputs in the IntelliJ console and it seemed like in.nextInt() can't stop getting a random number of tokens at random lines regardless of whether I even called it or not.
When I tried to put the inputs line by line as well while debugging line by line and it seemed like one call of .nextInt is asking for two int values. (I typed in a number and entered but it still waited for another input while staying in the same line where .nextInt() is just called just once)
At this point, I'm getting the feeling that my debugging process is wrong or at least it's some external problems rather than the code itself. I might be wrong as I still consider myself a novice...
Please, could somebody more experienced teach me how to get around this problem? I found a few questions having similar-looking problems with .nextLine() and .nextInt() but not exactly this. I apologise in advance if it's really a duplicate, though...
(I'll add more info if needed)
You are calling nextInt(), so input 000 is parsed as the number 0 and the int return value is therefore 0. Integer.toString() will therefore return the string "0". Why are you surprised about that?
Since you don't actually care about the input as a number, just use next:
for (int j = 0; j < row; j++) {
String s = in.next();
for (int k = 0; k < column; k++) {
world[j][k] = Character.getNumericValue(s.charAt(k));
}
}
UPDATE
That is the only problem with the question code for reading the input. Whether there is a problem in the calculateDeliveryTime is unknown.
See IDEONE for proof. The calculateDeliveryTime method simply prints the 2D array, so it can be seen that the input has been handle ok.

Negative Arrays and Error Messages

//MY TASK IS TWO MERGE TO ARRAYS INTO ASCENDING ORDER.Your program will accept each array as input from the keyboard. You do not know ahead of time how many values will be entered, but you can assume each array will have a maximum length of 10,000 elements. To stop entering values enter zero or a negative number. You should disregard any non-positive numbers input and not store these in the array.
The elements of the two input arrays should be in increasing order. In other words, each array element must have a value that is greater than or equal to the previous element value. An array may contain repeated elements.
import java.util.Scanner;
import java.lang.Math;
class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
int one[]= new int[10000];
int two[]= new int[10000];
int lengthShort=0;
int lengthLong=0;
int a =0;
int b =0;
System.out.println("Enter the values for the first array, "
+ "up to 10000 values, enter a negative number to quit");
for(int i=0; i<one.length && scan.hasNext(); i++){
one[i] = scan.nextInt();
a++;
if(one[i]<0){
one[i]=0;
break;
}
}
int length1 = a-1;
System.out.println("Enter the values for the second array, "
+ "up to 10000 values, enter a negative number to quit");
for(int i=0; i<two.length && scan.hasNext(); i++){
two[i] = scan.nextInt();
b++;
if(two[i]<0){
two[i]=0;
break;
}
}
int lengthTwo = b-1;
int mergeOne[] = new int[length1];
for (int i = 0; i<mergeOne.length; i++){
mergeOne[i]=one[i];
}
int mergeTwo[] = new int[lengthTwo];
for (int i = 0; i<mergeTwo.length; i++){
mergeTwo[i]=two[i];
}
System.out.println("First Array:");
for(int i=0; i<mergeOne.length; i++){
System.out.print(mergeOne[i] + " ");
}
System.out.println("\nSecond Array:");
for(int i=0; i<mergeTwo.length; i++){
System.out.print(mergeTwo[i] + " ");
}
if(mergeOne.length<=mergeTwo.length){
lengthLong = mergeTwo.length;
lengthShort = mergeOne.length;
}
else if(mergeOne.length>=mergeTwo.length){
lengthShort = mergeTwo.length;
lengthLong = mergeOne.length;
}
int merged[] = new int[length1 + lengthTwo];
for(int i = 0; i<lengthShort; i++){
if(i==0){
if(mergeOne[i]<=mergeTwo[i]){
merged[i] = mergeOne[i];
merged[i+1] = mergeTwo[i];
}
else if(mergeTwo[i]<=mergeOne[i]){
merged[i] = mergeTwo[i];
merged[i+1]= mergeOne[i];
}
}
else if(i>0){
if(mergeOne[i]<=mergeTwo[i]){
merged[i+i] = mergeOne[i];
merged[i+i+1] = mergeTwo[i];
}
else if(mergeTwo[i]<=mergeOne[i]){
merged[i+i] = mergeTwo[i];
merged[i+i+1]= mergeOne[i];
}
}
}
if(mergeOne.length<mergeTwo.length){
for(int k=lengthShort; k<lengthLong; k++){
merged[k]=mergeTwo[k];
}
}
if(mergeOne.length>mergeTwo.length){
for(int k=lengthShort; k<lengthLong; k++){
merged[k]=mergeOne[k];
}
}
for(int i = 0; i<merged.length; i++){
if((i+1)==merged.length)
break;
if(merged[i]>merged[i+1]){
int temp = merged[i+1];
merged[i+1]=merged[i];
merged[i]= temp;
}
}
System.out.println("\nMerged array in order is: ");
for(int i = 0; i<merged.length; i++){
System.out.print(merged[i] + " ");
}
}
}
//My code compiles in drjava but I have two issues:
1) It doesn't order the numbers in ascending order
2) When I run it through the site I have to submit this on it gives me the message as follows:
Runtime Error
Exception in thread "main" java.lang.NegativeArraySizeException
at Main.main(Main.java:281)
at Ideone.assertRegex(Main.java:94)
at Ideone.test(Main.java:42)
at Ideone.main(Main.java:29)
You'll need to rethink your merge algorithm. Suppose you input arrays are
1 5 10 50 100 500
2 4 6 8 10 12 14 16
You'll need to repeatedly decide which element is smaller to put into the output. So after selecting N elements, your output will look like
1 2 4 5 6 8 10 10 12 14
And you will need to have indexes pointing at the place in the input arrays you'll need to look at next:
1 5 10 50 100 500
^^
2 4 6 8 10 12 14 16
^^
As you can see, the indexes could be at very different places in the input arrays. However, your code does a lot of this:
if(mergeOne[i]<=mergeTwo[i]){
which means it's only comparing elements from the input that are in the same location. This doesn't work, and trying to swap elements in the output after the fact isn't good enough to get the job done.
Basically, instead of having one index and comparing the elements of the two input arrays at the same index, you'll need two indexes. I'll let you take it from there, but I think you can figure it out.
(And I have no idea why you're getting NegativeArraySizeException.)

Java Random Utility Generating Too Many 0's And Static Numbers

The line birthdays[j] = rnd.nextInt(365); seems to generate extra 0's in the int[] birthdays array. It also seems to add an EXTRA 0 into the array and generate static values depending on how many simulations I run and how many birthdays I generate. For instance, if I do 5 simulations and enter a 3 for the number of people in each simulation's "birthday pool" I always get an array of [0, 0, 289, 362].
Any help understanding the problem would be greatly appreciated.
public static void main(String[] args) {
System.out.println("Welcome to the birthday problem Simulator\n");
String userAnswer="";
Scanner stdIn = new Scanner(System.in);
do {
int [] userInput = promptAndRead(stdIn);
double probability = compute(userInput[0], userInput[1]);
// Print results
System.out.println("For a group of " + userInput[1] + " people, the probability");
System.out.print("that two people have the same birthday is\n");
System.out.println(probability);
System.out.print("\nDo you want to run another set of simulations(y/n)? :");
//eat or skip empty line
stdIn.nextLine();
userAnswer = stdIn.nextLine();
} while (userAnswer.equals("y"));
System.out.println("Goodbye!");
stdIn.close();
}
// Prompt user to provide the number of simulations and number of people and return them as an array
public static int[] promptAndRead(Scanner stdIn) {
int numberOfSimulations = 0;
while(numberOfSimulations < 1 || numberOfSimulations > 50000) {
System.out.println("Please Enter the number of simulations to do. (1 - 50000) ");
numberOfSimulations = stdIn.nextInt();
}
int sizeOfGroup = 0;
while(sizeOfGroup < 2 || sizeOfGroup > 365) {
System.out.println("Please Enter the size of the group of people. (2 - 365) ");
sizeOfGroup = stdIn.nextInt();
}
int[] simulationVariables = {numberOfSimulations, sizeOfGroup};
return simulationVariables;
}
// This is the method that actually does the calculations.
public static double compute(int numOfSims, int numOfPeeps) {
double numberOfSims = 0.0;
double simsWithCollisions = 0.0;
int matchingBirthdays = 0;
int[] birthdays = new int[numOfPeeps + 1];
int randomSeed = 0;
for(int i = 0; i < numOfSims; i++)
{
randomSeed++;
Random rnd = new Random(randomSeed);
birthdays = new int[numOfPeeps + 1];
matchingBirthdays = 0;
for(int j = 0; j < numOfPeeps; j++) {
birthdays[j] = rnd.nextInt(365);
Arrays.sort(birthdays);
}
for(int k = 0; k < numOfPeeps; k++) {
if(birthdays[k] == birthdays[k+1]) {
matchingBirthdays++;
}
}
if(matchingBirthdays > 0) {
simsWithCollisions = simsWithCollisions + 1;
}
}
numberOfSims = numOfSims;
double chance = (simsWithCollisions / numberOfSims);
return chance;
}
}
The line "birthdays[j] = rnd.nextInt(365);" seems to generate extra 0's in the int[] birthdays array.
Well, it doesn't. The array elements where zero to start with.
What that statement actually does is to generate a single random number (from 0 to 364) and assign it to one element of the array; i.e. the jth element. That is not what is required for your problem.
Now, we could fix your code for you, but that defeats the purpose of your homework. Instead I will give you a HINT:
The birthdays array is supposed to contain a COUNT of the number of people with a birthday on each day of the year. You have to COUNT them. One at a time.
Think about it ...
int arrays are by default initialized to 0 unless explicitly specified. Please see this Oracle tutorial about Arrays.
I found the problem myself. The issue was that having the "Arrays.sort(birthdays);" statement inside of a loop. That generated extra 0's.

Categories

Resources