Equal Spacing In print statements - java

So I was just about finished with a small little program and when I ran it everything worked fine. I did have 1 small technical issue that I didnt like and it was an unevenly spaced "table" if you would. In a nutshell I want it so my outputs are aligned on both sides.
Original output:
How many numbers should be generated?
10
What is the number of values of each random draw?
1000
- 1 108
- 2 90
- 3 101
- 4 98
- 5 117
- 6 97
- 7 89
- 8 111
- 9 93
- 10 96
Code:
import java.util.Random;
import java.util.Scanner;
public class tester
{
public static void main(String[] args)
{
Random rnum = new Random();
Scanner in = new Scanner(System.in);
int x = 0;
int y = 0;
int num = 0;
int length = 0;
System.out.println("How many numbers should be generated?");
x = in.nextInt();
System.out.println("What is the number of values of each random draw?");
y = in.nextInt();
int[] roll = new int[x];
for(int i = 1; i<=y; i++){
num = rnum.nextInt(x);
roll[num] = roll[num] + 1;
}
length = (int) Math.log10(x) + 1;
for(int i = 0; i < x; i++){
System.out.println(i+1 + " " + roll[i]); //This is the code that prints the original output
/*
* This is the code I attempted that did not give the desired result
* a = i;
System.out.println(i+1);
while(Math.log10(i) < length){
System.out.print(" ");
length--;
}
System.out.print(roll[i]);*/
}
}
}

Take a look at the System.out.format (https://docs.oracle.com/javase/tutorial/essential/io/formatting.html) and in perticular the width option. This is probably what you are wanting.

Two ways to go about this:
1) As stated already, look at the System.out.format directory. It has a wide availability of methods to format your output
2) Change the spacing in a manual way, where the spacing depends on the amount of characters in the number to the left.

Related

time limit error exceeding due to modulo(10,9)+7 maybe?

There are N soldiers located on our X-AXIS. The point at which a soldier is located also has some number of bombs.
The war is near and every soldier wants to communicate with every other soldier.
If the i-th soldier has b number of bombs and is located at position X then the cost of communicating with any other soldier j having c number of bombs located at position Y is defined as |X-Y|*max(b,c).
Find the sum of costs of communication if every soldier wants to communicate with every other soldier.
NOTE :- You have to consider pair(i,j) only once in sum of costs.
Input Format:
First line consists of number of test cases T. Each test case consists of three lines. The first line indicates the number of soldiers (N). The second line indicates the coordinates of the N soldiers ( X[i] ). The third line contains the number of bombs at every soldiers location ( B[i] ) . The x-coordinates needn't be in increasing order in the input.
Constraints
1 <= T <= 20 1 <= N <= 200000 1 <= X[i] <= 1000000000 1 <= B[i] <= 10000
Output Format:
The total cost modulo 10^9+7.
Sample Input
1
3
1 3 6
10 20 30
Sample Output
280
Explanation
there are 3 pairs (1,2) -> cost = abs(3-1) * 20 = 40 (1,3) -> cost = abs(1-6) * 30 = 150 (2,3) -> cost = abs(3-6) * 30 = 90 sum = 40 + 150 + 90 = 280
I'm handling modulo (10^9+7) and everything using brute force but getting tle code below its also working for the case above however it one of those annoying tle/type conversion type of problem. Any response is truly appreciated-
import java.util.*;
public class Main {
public static void main(String args[]) {
Scanner sc= new Scanner(System.in);
int T=sc.nextInt();
for(int ctr=0;ctr<T;ctr++)
{
int N=sc.nextInt();
long [] x= new long[N];
long [] b= new long[N];
for(int i=0;i<N;i++)
{
x[i]=sc.nextLong();
}
for(int i=0;i<N;i++)
{
b[i]=sc.nextInt();
}
int cost=0;
double v;
for(int i=0;i<N-1;i++)
{
for(int j=i+1;j<N;j++)
{
v= x[i]%(Math.pow(10,9)+7)-x[j]%(Math.pow(10,9)+7);
v=Math.abs(v)%(Math.pow(10,9)+7);
cost+= v*Math.max(b[i],b[j]);
}
}
System.out.println(cost);
}
} }
As suggested by #Erwin, don't use Math.pow() to calculate (10^9)+7 thrice in each iteration of the for loop. Instead, take it outside the loop (maybe define it as a constant) and then execute your operations.
Also, you are doing modulo with (10^9)+7 constant twice in your operation. Are you sure that is the intended operation? You are doing it in the first computation of v and then again in the second computation of v. If you need it only for the final cost, you can remove it from the first step.
Here is my code that you can try:
import java.util.*;
public class Main {
public static void main(String args[]) {
double moduloNumber = (Math.pow(10,9)+7);
Scanner sc= new Scanner(System.in);
System.out.print("Enter the Number of Test Cases (1 <= T <= 20): ");
int T=sc.nextInt();
for(int ctr=0;ctr<T;ctr++)
{
System.out.print("\nEnter the Number of Soldiers (1 <= N <= 200000): ");
int N=sc.nextInt();
long [] x= new long[N];
long [] b= new long[N];
for(int i=0;i<N;i++)
{
System.out.print("Enter the Position of Soldier " + (i+1) + " (1 <= X[i] <= 1000000000): ");
x[i]=sc.nextLong();
}
for(int i=0;i<N;i++)
{
System.out.print("Enter the Number of Bombs with Soldier " + (i+1) + " (1 <= B[i] <= 10000): ");
b[i]=sc.nextInt();
}
int cost=0;
double v;
for(int i=0;i<N-1;i++)
{
for(int j=i+1;j<N;j++)
{
v=(x[i]-x[j]);
v=Math.abs(v)%(moduloNumber);
cost+= v*Math.max(b[i],b[j]);
}
}
System.out.println(cost);
}
}
}
I just added some print statements and moved the modulo constant outside the loop to reduce computation costs. You can check if this solves the purpose.
Regards,
AJ

Java code to find polygonal numbers based on input

I need a program that can do following example:
"What is the number of sides of your polygon?" "3"
"How many of these would you like to see?" "36"
"1 3 6 10 15 21 28 36 45 55"
"66 78 91 105 120 136 153 171 190 210"
"496 528 561 595 630 666"
-It has to be able to input the values from the first two questions and print then answers off 10 to a line. I've tried writing the code myself but constantly get stuck in the for loop.Thank you.
This is what I have so far:
Scanner input = new Scanner(System.in);
//Request number of sides the polygon must have
System.out.println("What is the number of sides of your polygon? ");
n = input.nextInt();
System.out.println("How many of these would you like to see? ");
k = input.nextInt();
long output = polygonalNumber(n,k);
for (k = 1; k < k; k++);
if (output % 10 == 0) {
System.out.println();
}
}
public static long polygonalNumber(long n, long k){
long p = (k * k) * (n-2) - (k * (n-4))/2;
return polygonalNumber(n,k);
Your code looks really messed up. But no worries, I wrote a version that supports from 3-6 sides.
Here it is:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Request number of sides the polygon must have
System.out.println("What is the number of sides of your polygon? ");
int sides = input.nextInt();
System.out.println("How many polygonal numbers do you want?");
int amount = input.nextInt();
input.nextLine();
input.close();
FindPolygonalNumbers(sides, amount);
}
static void FindPolygonalNumbers(int sides, int amount) {
String numbers = "";
for (int i = 1; i <= amount; i++) {
int number = 0;
if (sides == 3) {
number = (i * (i + 1)) / 2;
} else if (sides == 4) {
number = i * i;
} else if (sides == 5) {
number = (3 * i * i - i) / 2;
} else if (sides == 6) {
number = i * (2 * i - 1);
}
numbers = numbers + number + ", ";
}
System.out.println(numbers);
}
If you have any questions regarding the code, don't hesitate to ask about it.

Java print multiple lines after reading multiple lines

(It's my homework task. So I can't make any changes to the task like changing the rules of input.)
I need to calculate
a^m mod n
and print out the result. (I've already figured out how to code the calculation.)
But the question said there'll be multiple lines of input:
IN:
12 5 47
2 4 89
29 5 54
and need to print all the results together after reading all the lines of input. (You can't print the results right after one line of input.)
OUT:
14
16
5
The code I've tried so far:
import java.util.Scanner;
public class mod {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
int count = 0;
while (input.hasNextLine()){
count++;
}
int[] array = new int[count];
for (int i = 0; i < count; i ++){
int a = input.nextInt();
int m = input.nextInt();
int n = input.nextInt();
int result = (int)((Math.pow(a, m)) % n);
array[i] = result;
}
for (int x : array){
System.out.println(x);
}
}
}
I tried to count the lines of input and build an array of that size to store the results.
But it seems my code fail to detect the end of input and keep looping.
You can store the user's input in the initial loop with a List<String>, I would suggest terminating the loop on an empty String and only adding lines that match the three numbers separated by whitespace characters. Also, I would print the result in the second loop. Then you don't need a result array. I would also prefer formatted io (i.e. System.out.printf). Like,
Scanner input = new Scanner(System.in);
List<String> lines = new ArrayList<>();
while (input.hasNextLine()) {
String line = input.nextLine();
if (line.isEmpty()) {
break;
} else if (line.matches("\\d+\\s+\\d+\\s+\\d+")) {
lines.add(line);
}
}
int count = lines.size();
for (int i = 0; i < count; i++) {
String[] tokens = lines.get(i).split("\\s+");
int a = Integer.parseInt(tokens[0]), m = Integer.parseInt(tokens[1]),
n = Integer.parseInt(tokens[2]);
int result = (int) ((Math.pow(a, m)) % n);
System.out.printf("(%d ^ %d) %% %d = %d%n", a, m, n, result);
}
I tested with your provided input,
12 5 47
2 4 89
29 5 54
(12 ^ 5) % 47 = 14
(2 ^ 4) % 89 = 16
(29 ^ 5) % 54 = 5

Java - Cant get it to work

I have been trying to finish this for a couple of hours now. My program is supposed to generate random numbers due to the users input. Then the program divide the numbers in two new even and odd arrays. I have solved the "generated random numbers" part but now i need too transfer the even and odd numbers into two new arrays.
This is what the output should look like:
How many random numbers between 0 - 999 do you want? **12**
Here are the random numbers:
145 538 56 241 954 194 681 42 876 323 2 87
These 7 numbers are even:
538 56 954 194 42 876 2
These 5 numbers are odd:
145 241 681 323 87
This is my code at the moment:
import java.util.Scanner;
public class SlumpadeTal {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Hur många slumptal i intervallet 0 - 999 önskas?");
int antal = input.nextInt();
System.out.println("Här är de slumpade talen:");
int[] arrayen = new int[antal];
for (int i = 0; i < arrayen.length; i++) {
arrayen[i] = (int) (Math.random() * 999 + 1);
System.out.print(arrayen[i] + " ");
if ((arrayen[i] % 2) == 0) {
}
}
}
}
NOTE that i can't use any class for this. such as Arraylist, Vector or others!
A simple solution would be to count to number of even numbers and odd numbers,
create arrays of those sizes, and once again iterate over your original array to put each number in it's place.
edit: something like this:
int evenCounter = 0;
int oddCounter = 0;
Scanner input = new Scanner(System.in);
System.out.println("Hur många slumptal i intervallet 0 - 999 önskas?");
int antal = input.nextInt();
System.out.println("Här är de slumpade talen:");
int[] arrayen = new int[antal];
for (int i = 0; i < arrayen.length; i++) {
arrayen[i] = (int) (Math.random() * 999 + 1);
System.out.print(arrayen[i] + " ");
if ((arrayen[i] % 2) == 0) {
evenCounter++;
}
else
oddCounter++;
}
}
int[] evenArray = new int[evenCounter];
int[] oddArray = new int[oddCounter];
evenCounter = 0;
oddCounter = 0;
for (int i =0; i < arrayen.length; i++){
if ((arrayen[i] % 2) == 0) {
evenArray[evenCounter] = arrayen[i];
evenCounter++;
}
else{
oddArray[oddCounter] = arrayen[i];
oddCounter++;
}
}
My solution will be divide the number into odd or even number after a number is generated. Using arraylist will be better than array because its capacity will be grow automatically and it is suitable for your case because you dont know how many even number or odd number will be generate for each time.
The if-statement you have in your code (if ((arrayen[i] % 2) == 0)) is correct.
What I suggest doing is instead of creating new arrays, create a collection type that has a dynamic length, such as an ArrayList. That way you don't have to worry about figuring out the size first, and thus don't have to iterate twice.
If you really need an array for whatever reason, you can always convert the ArrayList to an array with ArrayList#toArray(T[])

My logical program is not giving the correct output?

Question:
The Utopian tree goes through 2 cycles of growth every year. The first growth cycle occurs during the spring, when it doubles in height. The second growth cycle occurs during the summer, when its height increases by 1 meter.
Now, a new Utopian tree sapling is planted at the onset of the spring. Its height is 1 meter. Can you find the height of the tree after N growth cycles?
Input Format
The first line contains an integer, T, the number of test cases.
T lines follow. Each line contains an integer, N, that denotes the number of cycles for that test case.
Constraints
1 <= T <= 10
0 <= N <= 60
Output Format
For each test case, print the height of the Utopian tree after N cycles.
//FINALLY, HOPE so .. WHAT QUESTION IS SAYING..
INITIALLY VALUE IS 1 .. IF SPRING OCCURS.. IT'S VALUE WILL BE DOUBLED.. THAT MEANS .. IT WILL BE MULTIPLIED BY 2.. BUT IF SUMMER OCCUR IT'S VALUE WILL BE ADDED BY 1...
If i give input:
2 //here 2 is the number of question..
0
1
So, Output must be:
1
2
Another example,
sample of output:
2
3
4
So, Sample of input will be:
6
7
HOPE SO.. YOU UNDERSTAND WHAT QUESTION IS ASKING, HERE NOW WE HAVE TO MAKE A PROGRAM INTO JAVA....
Okay as further i made a program for this..
package com.logical03;
import java.util.Scanner;
public class MainProgram{
public static void main(String[] args){
int num=1;
int[] array=new int[100];
Scanner in=new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements=in.nextInt();
System.out.println("Enter the values now: ");
for(int i=1; i<=n_Elements; i++){
array[i]=in.nextInt();
}
for(int i=1; i<=n_Elements; i++){
if(array[i]==0){
System.out.println("\n1");
}
else{
for(int j=1; j<=array[i]; j++){
if(j%2!=0){
num=num*2;
}
else{
num=num+1;
}
}
System.out.println(num);
}
}
}
}
As i run into here .. it adds the second number of question into my output.. Suppose..
If i give input as:
2
3
4
So, output must suppose to be:
6
7
Which is correct!!
But My program gives the output as:
6
27 //which is incorrect..becoz it adds the sum of above number :(
Mistake - int num = 1; should be declared in inside parent loop to refresh it's value.
public static void main(String[] args) {
int[] array = new int[100];
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of Questions: ");
int n_Elements = in.nextInt();
System.out.println("Enter the values now: ");
for (int i = 1 ; i <= n_Elements ; i++) {
array[i] = in.nextInt();
}
for (int i = 1 ; i <= n_Elements ; i++) {
int num = 1;
if (array[i] == 0) {
System.out.println("\n1");
} else {
for (int j = 1 ; j <= array[i] ; j++) {
if (j % 2 != 0) {
num = num * 2;
} else {
num = num + 1;
}
}
System.out.println(num);
}
}
}
Output
Enter the number of Questions:
2
Enter the values now:
3
4
6
7
My approach is to take on account that first cycle (2 * height) occurs on odds indexes, and second cicle (1 + height) occurs on even indexes, from 1 to n (inclusive), starting index 0 is always 1.
return IntStream.rangeClosed(1, n)
.reduce(1, (acc, idx) -> idx % 2 != 0 ? acc * 2 : acc + 1);
This is my first contribution, only learning to code and solve algorithms, I had to find a workable solution with simple to follow code credit to http://www.javainterview.net/HackerRank/utopian-tree
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
//receive input
Scanner in = new Scanner(System.in);
//no of test cases
int T=in.nextInt();
//no of cycles
int[] N = new int[T];
for(int i=0;i<T;i++){
N[i]=in.nextInt();
}
int height=1;
for(int i=0;i<N.length;i++){
height=1;
for(int j=1;j<=N[i];j++){
if((j%2) ==1)
height=height*2;
else
height++;
}
System.out.println(height);
}
}
}//this the end of the class

Categories