I want to read all test cases in UVA Online Judge problem. Test cases are divided by a blank line. Example:
11
20
1
2
3
6
8
12
13
13
15
16
17
18
19
20
20
21
25
26
30
31
12
20
1
2
3
6
8
12
13
13
15
16
17
18
19
20
20
21
25
26
30
31
17
20
1
2
3
6
8
12
13
13
15
16
17
18
19
20
20
21
25
26
30
31
while(sc.hasNextLine())
{
numberOfYears = sc.nextInt();
numberOfPopes = sc.nextInt();
years = new ArrayList<Integer>();
for(int i = 0; i < numberOfPopes; i++)
{
years.add(sc.nextInt());
}
p = new ProblemPope(numberOfYears, numberOfPopes, years);
}
I know, that scanner waits for another line or wants CTRL+Z or CTRL+D. I just want to know if there is a way how to end it after reading all test cases.
Is there a way to do it by Scanner?
I think you are looking for this:
while (true) {
if(!sc.hasNext())
break;
...
}
or simply:
while(sc.hasNext()) {
...
}
you can use sc.close() to close the scanner from reading input
Your code might end in runtime error if you do not check hasNext(),hasNextLine() or hasnextInt() getting all inputs.
But
Normally the first most input will be the number of testcases in most of the online contests. so you can use it to your advantage like the following.
int testCaseCount= sc.nextInt();
for(int testCase=0; testcase < testCaseCount; testCase++){
numberOfYears = sc.nextInt();
numberOfPopes = sc.nextInt();
years = new ArrayList<Integer>();
for(int i = 0; i < numberOfPopes; i++)
{
years.add(sc.nextInt());
}
p = new ProblemPope(numberOfYears, numberOfPopes, years);
}
But if the input does not specify number of test cases, then it is not dynamically entered.
ie it is tested from a file. In such cases the sc.hasNextLine() should work.
if both are not working, please mention the link to the question, so that i can verify what the problem is.
Related
Can someone help me write the program in Java that prints the following triangle? I'm having trouble coming up with a solution.
Example User input:
Enter increment amount: 5
Enter number of terms in sequence: 7
The number of rows is always set at 10.
What I have written so far:
import java.util.Scanner;
public class Drawtriangle {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter increment amount:");
int incAmt=scanner.nextInt();
System.out.print("Enter number of terms in the sequence:");
int numOfTerms=scanner.nextInt();
int number=1;
for(int row=1; row<=10;row++) {
for(int col=1; col<=row; col++) {
System.out.print(number);
}
System.out.println();
}
scanner.close();
}
}
Output:
1
6 11
16 21 26
31 1 6 11
16 21 26 31 1
6 11 16 21 26 31
16 11 16 21 26 31 1
6 11 16 21 26 31 1 6
11 16 21 26 31 1 6 11 16
21 26 31 1 6 11 16 21 26 31
The triangle is simply a triangle where the next number is greater by +5 than the previous number. So we need to increment number by 5 each time something is printed out of the loop.
In your code, you took number = 1 before entering the loop, but then didn't mention any changes it must go through in order to print this triangle.
Mistake number 1 in the code
Now the output also has one error. In the 7th line of output you posted the first value the inner loop will print is 16. This is not true as, after printing 31, the loop will start again from 1 and increment by 5 again. I think there was a space between 1 and 6 of 16 in the 7th line. Here is the solution with just minor changes that I've come up with:
import java.util.Scanner;
public class Drawtriangle {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter increment amount:");
int incAmt=scanner.nextInt();
System.out.print("Enter number of terms in the sequence:");
int numOfTerms=scanner.nextInt();
int number=1;
for(int row=1; row<=10;row++) {
for(int col=1; col<=row; col++) {
System.out.print(number+" ");
number = number + 5 ;
if(number>31){
number = 1;
}
}
System.out.println();
}
scanner.close();
}
}
The output is also here:
CORRECT OUTPUT IN ACCORDANCE WITH THE CORERCTLOGIC
Hope you can are able to solve this now. I took the same inputs given at the start to avoid any problems. Anyways, All the best.
Simple logic to print the pattern using for loop
import java.util.Scanner;
public class DrawTriangle {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
var out = System.out;
System.out.print("Enter increment amount:");
int incAmt=scanner.nextInt();
System.out.print("Enter number of terms in the sequence:");
int numOfTerms=scanner.nextInt();
int number=1;
int count = 0;
for(int row=0; row<10;row++) {
for(int col = 0;col<=row;col++){
out.print(number+" ");
number += incAmt;
count ++;
if(count>=numOfTerms){
number = 1;//initialising number with 1 if number of terms it has reached
count = 0;//resetting counter
}
}
out.println();
}
scanner.close();
}
}
Output:
$ javac DrawTriangle.java && java DrawTriangle
Enter increment amount:5
Enter number of terms in the sequence:7
1
6 11
16 21 26
31 1 6 11
16 21 26 31 1
6 11 16 21 26 31
1 6 11 16 21 26 31
1 6 11 16 21 26 31 1
6 11 16 21 26 31 1 6 11
16 21 26 31 1 6 11 16 21 26
I am trying to make a number grid using a Java for-loop
but I have difficulty making it aligned and following the pattern.
The output that I want to see is:
5 4 3 2 1
6 7 8 9 10
15 14 13 12 11
16 17 18 19 20
25 24 23 22 21
I've been watching youtube tutorials and articles about Java for-loops
but I can't find any idea to solve this. I am currently stuck with this code:
int j=5;
int up1=14, up2=6;
for(int u=1; u<=5; u++)
{
for(int s=1; s<=5; s++)
{
System.out.print(j+"\t");
j--;
}
System.out.println("");
if(u%2==0){
j+=up1;
}else{
j+=up2;
}
}
Its output is:
5 4 3 2 1
6 5 4 3 2
15 14 13 12 11
16 15 14 13 12
25 24 23 22 21
I have heard about int update
but I have no idea how to apply it in my code.
You forgot to invert the increment(-1/+1) every line.
Then you need only to adjust up1 and you're fine
int j = 5;
int inc = -1;
int up1 = 4, up2 = 6;
for (int u = 1; u <= 5; u++) {
for (int s = 1; s <= 5; s++) {
System.out.print(j + "\t");
j += inc;
}
System.out.println("");
inc = -inc;
if (u % 2 == 0) {
j += up1;
} else {
j += up2;
}
}
Output:
5 4 3 2 1
6 7 8 9 10
15 14 13 12 11
16 17 18 19 20
25 24 23 22 21
Your problem with the alignment might be that you want leading spaces for the single digits, then use this for the print:
System.out.print(String.format("%2d\t", j));
Output
5 4 3 2 1
6 7 8 9 10
15 14 13 12 11
16 17 18 19 20
25 24 23 22 21
Easy way to say your pattern is correct. Now, you remove "tab" or spacing on output.
Look you wrote \t which means give me a spacing of "tab" size.
System.out.print(j+"\t");
You just have to remove \t. Than, give it a single space.
System.out.println(j+" ");
Done!
int k = 1;
for (int i = 1; i <= 5; i++) {
String accending = "",descending="";
for (int j = k; j < k+5; j++) {
accending+=j+"\t";
descending=j+"\t"+descending;
}
if (i % 2 != 0) {
System.out.println(descending);
k=Integer.parseInt(descending.split("\t")[0])+1;
}else{
System.out.println(accending);
k=Integer.parseInt(accending.split("\t")[4])+1;
}
}
I think it is easy to understand with this code.Simply turn ending digit in each line to a number.
Solution
Even Rows
The pattern for the even rows is that it increases always by 10, you can simply take your j indice and multiply it by factor 5 times the row number.
Important note Here in the example I started counting rows at zero 0 - 4, because first row is odd
Row || Column
1. 2. 3.
0. 5 + (5*0) -> 5 4 + (5*0) -> 4 3 + (5*0) -> 3
2. 5 + (5*2) -> 15 4 + (5*2) -> 14 3 + (5*2) -> 13 ....
4. 5 + (5*4) -> 25 4 + (5*4) -> 24 3 + (5*4) -> 23
Odd Rows
For the odd rows the pattern is more difficult
It increases the last column by ten and then go "backwards" the j value.
Here I defined an counter variable which I increment in every odd iteration.
Row || Column
1. 2.
1. 10*1 - 5 + 1 -> 6 10*1 - 4 + 1 -> 7
3. 10*2 - 5 + 1 -> 16 10*2 - 4 + 1 -> 17
5. 10*3 - 5 + 1 -> 26 10*3 - 4 + 1 -> 27 // this it how it would continue
Here the Full Solution
public static void main(String[] args) {
int counter = 1;
for(int i = 0; i < 5; i++) {
for(int j = 5; j > 0; j--){
if(i % 2 == 0) {
System.out.print(j+(5*i)+ " ");
}else {
System.out.print(10*counter -j+1 + " ");
}
}
if(i%2!=0) {
counter ++;
}
System.out.println();
}
Output is
5 4 3 2 1
6 7 8 9 10
15 14 13 12 11
16 17 18 19 20
25 24 23 22 21
The given pattern goes like this:
The pattern starts with a number e.g. X = 5.
When the main loop counter is an odd number, the print counter starts with start value and decreases by one X times. Finally, it sets start for the next row to start with the final value of the print counter - 1 + X.
When the main loop counter is an even number, the print counter starts with start value and increases by one X times. Finally, it sets start for the next row to start with start + 1.
Based on this property of the pattern, you can write it as
public class Main {
public static void main(String[] args) {
final int X = 5;
int start = X, j, k;
for (int i = 1; i <= X; i++) {
if (i % 2 == 0) {
k = 1;
for (j = start; k <= X; j++, k++) {
System.out.print(j + "\t");
}
start = j - 1 + X;
} else {
k = 1;
for (j = start; k <= X; j--, k++) {
System.out.print(j + "\t");
}
start++;
}
System.out.println();
}
}
}
Output:
5 4 3 2 1
6 7 8 9 10
15 14 13 12 11
16 17 18 19 20
25 24 23 22 21
Change the value of X to 10 and you will get the following pattern:
10 9 8 7 6 5 4 3 2 1
11 12 13 14 15 16 17 18 19 20
30 29 28 27 26 25 24 23 22 21
31 32 33 34 35 36 37 38 39 40
50 49 48 47 46 45 44 43 42 41
51 52 53 54 55 56 57 58 59 60
70 69 68 67 66 65 64 63 62 61
71 72 73 74 75 76 77 78 79 80
90 89 88 87 86 85 84 83 82 81
91 92 93 94 95 96 97 98 99 100
int j=5;
int up1=14, up2=6;
for(int u=1; u<=5; u++)
{
for(int s=1; s<=5; s++)
{
System.out.printf("%5d",j);
j--;
}
System.out.println("");
if(u%2==0) {
j+=up1;
} else {
j+=up2;
}
}
What do you think about this code?
I have a program which generates rows of 6 numbers (int arrays).
I am passing the output to another program that sorts it with the BubbleSort algorithm and writes it into a textfile.
If the first program is used without passing it works fine, no repeated numbers no zeroes. but when sorted there are repeated numbers and even i have seen zeroes, the case of the zeroes i could not reproduce atm, but the double occuring numbers. Could it have something to do with multithreading/parallel processing or the environment in whicht it is executed and which consist of a amd multicore win 10 host and deb jessie guest.
java LottoArray | java BubbleSort>test2.txt //terminal
test2.txt
2 13 16 20 27 40
9 14 17 21 25 41
6 11 11 19 27 44
4 10 25 34 39 47
11 12 17 36 44 48
1 15 23 31 39 40
3 22 22 23 33 45
1 25 26 26 35 49
11 14 24 25 41 49
6 6 14 17 38 46
4 19 19 28 35 39
As you can see the sixs in the row before the last row are double and the 22s and the 11s.
public class LottoArray{
public static void main (String [] args){
for(int o=0;o<=10;o++){
int Reihe [] = new int [6];
int zahl;
int j=0;
int i= 0;
while(j<Reihe.length){
zahl = (int) (Math.random()*50);
boolean schonda = false;
while ( i<j){
if(Reihe[i]== zahl)
schonda=true;
i++;
}
if(schonda==false && zahl !=0){
Reihe[j]=zahl;
j++;}
}
for(int z=0;z<6;z++){
System.out.print(Reihe[z]+" ");
}
System.out.println();
}
}
}
public class BubbleSort {
public static void main(String args[]) {
int arr[]= new int[6];
while(!StdIn.isEmpty()){
for(int i=0;i<6;i++)
arr[i]= StdIn.readInt();
boolean getauscht;
do {
getauscht= false;
for (int i=0; i<arr.length-1; i++) {
if ( arr[i] > arr[i+1]) {
int tmp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = tmp;
getauscht = true;
}
}
}while(getauscht);
for (int i=0; i<arr.length; i++)
System.out.print(arr[i]+" " );
System.out.println();
}
}
}
if i use the code without the bubbleSort and stream the output into a textfile, there are no repeated numbers and no zeroes, as it should be not possible because i coded the condition if(schonda==false && zahl !=0)
15 2 20 5 26 34
13 6 15 33 12 37
44 17 16 23 40 25
25 47 10 43 40 44
25 29 3 30 10 41
32 1 23 35 43 28
9 34 28 32 33 25
5 46 31 16 25 9
9 13 16 18 40 5
29 15 16 2 16 15
34 33 44 13 43 48
has someone experiences with that kind of occurring numbers that should not ?
You problem is in this block of LottoArray:
int j=0;
int i= 0;
while(j<Reihe.length){
zahl = (int) (Math.random()*50);
boolean schonda = false;
while ( i<j){
if(Reihe[i]== zahl)
schonda=true;
i++;
}
if(schonda==false && zahl !=0){
Reihe[j]=zahl;
j++;
}
}
The first time you enter in the while (i<j){ loop from above (for the first element), both i and j are 0, so the loop is not executed.
The second time (checking the second number), i is 0 and j is 1, so the loop is executed and i is increased.
The third time (checking the third number), i is 1 and j is 2.
Same for the rest, i is always j-1.
This is a bug, as you are not starting the check on the first element. I suppose you are only getting duplicates using the BubbleSort out of luck, as the error is not there.
To fix this, initialize i inside the first while, in the same place as the schonda var, not above with j.
I have a task to do and I am a little stuck.
I have to order some arrays from a file with 'selection sort' method and write the solution to the end of the file.
For example:
file.txt
9 3 1 12 8 6
22 3 1 8
78 61 19 5 99
is given. After sorting I should have something like that:
file.txt
9 3 1 12 8 6
22 3 1 8
78 61 19 5 99
----sorted----
1 3 6 8 9 12
1 3 8 22
5 19 61 78 99
I have to mention that I have to do it in PHP, Java, C# and Python.
I started coding it in PHP but I'm a little stuck. My code looks like this:
<?php
function selectionSort(array $array) {
$length = count($array);
for($i = 0; $i < $length; $i ++) {
$min = $i;
for($j = $i + 1; $j < $length; $j ++) {
if ($array[$j] < $array[$min]) {
$min = $j;
}
}
$tmp = $array[$min];
$array[$min] = $array[$i];
$array[$i] = $tmp;
}
return $array;
}
//CREATE ARRAYS FROM FILE LINES:
$file_handle = fopen("fisier.txt", "r+");
while (!feof($file_handle) ) {
$line_of_text = fgets($file_handle);
$parts = explode(' ', $line_of_text);
$parts_sorted = selectionSort($parts);
for ($n=0; $n<count($parts_sorted); $n++){
echo $parts_sorted[$n]." ";
}
echo "<br>";
}
fclose($file_handle);
The problem here is that it doesn't sort well, I mean my txt file is
9 12 5 4 13 8
3 7 12 44 22 4 13
70 1 12 55 34
22 13 7 50 3 1 9 14 27 77
56 2 9 45 35 12 7 63
and the result from the php code is
4 5 8 9 12 13
13 3 4 7 12 22 44
1 12 34 55 70
1 3 7 77 9 13 14 22 27 50
2 7 9 12 35 45 56 63
which is not a good sort. Can you tell why?
Do you know what should I do next to write the sorted arrays to the end of the file?
And a little help for java,c# and python would be great. Sorry for the long post but I am a noob here. Thank you!
fgets() returns the linefeed/carriage-return character that ends the line
So you're not comparing 13 to something but 13\r\n or 13\n or ....
You can either do something like
$line_of_text = trim(fgets($file_handle));
to get rid of any leading/trailing whitespace of the line read from the file and/or
$parts = array_map('intval', explode(' ', $line_of_text));
to convert every element to an integer.
(In case all elements are within the value range of a php integer, I advise using the array_map/intval thingy as the comparision of numers as number is apparently what you want. Otherwise you might be interested in strnatcmp() as your comparision function instead of the < operator)
Here is a short Java snippet.
What it does
read the file file.txt line by line
convert the values of a line into integer values
sort the integer values using method selectionSort(int[])
write the sorted values back to file file_sorted.txt
.
// equal to your PHP implementation
static void selectionSort(int[] ints) {
for (int i = 0; i < ints.length - 1; i++) {
int min = i;
for (int j = i + 1; j < ints.length; j++) {
if (ints[j] < ints[min]) {
min = j;
}
}
int temp = ints[min];
ints[min] = ints[i];
ints[i] = temp;
}
}
...
Path fileIn = Paths.get("file.txt");
Path fileOut = Paths.get("file_sorted.txt");
try (BufferedReader br = Files.newBufferedReader(fileIn);
BufferedWriter bw = Files.newBufferedWriter(fileOut,
StandardOpenOption.CREATE_NEW)) {
for (String l = br.readLine(); l != null; l = br.readLine()) {
String[] fields = l.split(" +");
int[] ints = Arrays.asList(fields) // convert to List
// convert the List into a Stream
.stream()
// map the entries to their integer values
.mapToInt(f -> Integer.valueOf(f))
// convert the stream to an array
.toArray();
selectionSort(ints);
for (int i = 0; i < ints.length; i++) {
bw.append(Integer.toString(ints[i]));
if (i < ints.length - 1) {
bw.append(' ');
}
}
bw.newLine();
}
}
input file.txt
9 12 5 4 13 8
3 7 12 44 22 4 13
70 1 12 55 34
22 13 7 50 3 1 9 14 27 77
56 2 9 45 35 12 7 63
output file_sorted.txt
4 5 8 9 12 13
3 4 7 12 13 22 44
1 12 34 55 70
1 3 7 9 13 14 22 27 50 77
2 7 9 12 35 45 56 63
I'm new to Java. I'm trying to make a triangular multiplication table that looks somewhat like this:
Enter # of rows 7
1 2 3 4 5 6 7
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
Each row/column has to be numbered, and I have no idea how to do this. My code is seemingly waaay off, as I get an infinite loop that doesn't contain the correct values. Below you will find my code.
public class Prog166g
{
public static void main(String args[])
{
int userInput, num = 1, c, d;
Scanner in = new Scanner(System.in);
System.out.print("Enter # of rows "); // user will enter number that will define output's parameters
userInput = in.nextInt();
boolean quit = true;
while(quit)
{
if (userInput > 9)
{
break;
}
else
{
for ( c = 1 ; c <= userInput ; c++ )
{ System.out.println(userInput*c);
for (d = 1; d <= c; d++) // nested loop required to format numbers and "triangle" shape
{
System.out.print(EasyFormat.format(num,5,0));
}
}
}
}
quit = false;
}
}
EasyFormat refers to an external file that's supposed to format the chart correctly, so ignore that. If someone could please point me in the right direction as far as fixing my existing code and adding code to number the columns and rows, that would be greatly appreciated!
Two nested for loops will do the trick:
for (int i = 1; i < 8; i++) {
System.out.printf("%d\t", i);
}
System.out.println();
for (int i = 1; i < 8; i++) {
for (int j = 1; j <= i; j++) {
System.out.printf("%d\t", i * j);
}
System.out.println();
}
OUTPUT
1 2 3 4 5 6 7
1
2 4
3 6 9
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49