Java print multiple lines after reading multiple lines - java

(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

Related

My loop is ending wrong, it's exceeding the limit I've given

I'm trying to resolve this problem: Given integer N. Print all the squares of natural numbers, not exceeding N, in ascending order.
For example, lets say N = 50, it prints =
1
4
9
16
25
36
49
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int b = 0;
while (N > b){
b++;
int m = b*b;
System.out.println(m);
if (N < m){
break;
}
With my code I'm getting
1
4
9
16
25
36
49
64
So, it's kinda working but it's exceeding my int N for some reason. Even though the condition states that if N < m, it should break.
What you should do is to, break from loop if condition is met, else print the value. I have rearranged the code below by moving the print statement below the condition -
if (N < m){
break;
}
System.out.println(m);
Your logic is a bit off, you want b + 1 <= Math.sqrt(N). Like,
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int b = 0;
while (b + 1 <= Math.sqrt(N)) {
b++;
System.out.println(b * b);
}

Is there something wrong with my id array?

This program pulls two columns from the input.txt file where the first column indicates the value of the object, and the second column represents the weight. The values are imported and placed into two arrays: the value array and the weight array. The knapsack calculations are then made. There are 23 objects in total represented by the rows of the arrays. My code correctly calculates the total value that is being held in the knapsack, and will print out the correct IDs if the weight capacity entered is 5, but for any other weight the IDs being held in the id array are not correct, but the total value printed out is. Here is my code for both files, and if anyone is able to figure out how to correctly save and print the IDs being held in the knapsack please let me know . . .
input.txt file:
17 5
12 8
15 22
17 11
33 21
43 15
15 4
44 35
23 19
10 23
55 39
8 6
21 9
20 28
20 13
45 29
18 16
21 19
68 55
10 16
33 54
3 1
5 9
knapsack.java file:
//We did borrow concepts from:
//http://www.sanfoundry.com/java-program-solve-knapsack-problem-using-dp/
import java.util.Scanner;
import java.util.*;
import java.lang.*;
import java.io.*;
public class knapsack
{
static int max(int a, int b)
{
if(a > b)
{
//System.out.println(a);
return a;
}
else
//System.out.println(b);
return b;
}
static int knapSack(int maxCapacity, int weight[], int value[], int n)
{
int track = 0;
int i, w;
int foo1 = 0;
int foo2 = 0;
K = new int[n+1][maxCapacity+1];
// Build table K[][] in bottom up manner
for (i = 0; i <= n; i++)
{
for (w = 0; w <= maxCapacity; w++)
{
if (i==0 || w==0)
K[i][w] = 0;
else if (weight[i-1] <= w)
{
//K[i][w] = max(value[i-1] + K[i-1][w-weight[i-1]], K[i-1][w]);
if(value[i-1] + K[i-1][w-weight[i-1]] > K[i-1][w])
{
K[i][w] = value[i-1] + K[i-1][w-weight[i-1]];
//System.out.println("A: "+i);
}
else
{
K[i][w] = K[i-1][w];
id[track++] = i;
//System.out.println("B: "+i);
}
}
else
{
K[i][w] = K[i-1][w];
}
}
//System.out.println(K[foo1][foo2]);
}
return K[n][maxCapacity];
}
public static void main(String args[])throws java.io.FileNotFoundException
{
Scanner sc = new Scanner(System.in);
int n = 23;
File file = new File("input.txt");
Scanner scanner = new Scanner(file);
id = new Integer [n];
//knapval = new int[n];
//knapweight = new int [n];
int []value = new int[n];
int []weight = new int[n];
for(int i=0; i<n; i++)
{
value[i] = scanner.nextInt();
weight[i] = scanner.nextInt();
}
System.out.println("Enter the maximum capacity: ");
int maxCapacity = sc.nextInt();
System.out.println("The maximum value that can be put in a knapsack with a weight capacity of "+maxCapacity+" is: " + knapSack(maxCapacity, weight, value, n));
System.out.println();
System.out.println("IDs Of Objects Held In Knapsack: ");
//System.out.println();
for(int z = 0; z < n && id[z] != null; z++)
{
System.out.println(id[z]);
}
if(id[0] == null)
System.out.println("All objects are too heavy, knapsack is empty.");
sc.close();
scanner.close();
}
protected static Integer [] id;
protected static int [][]K;
}
Your way of recording your solution in the id array is flawed. At the time you do id[track++] = i;, you don’t yet know whether i will be in your final solution. Because of the nested loops you may even add i more than once. This in turn may lead to overflowing the array with a java.lang.ArrayIndexOutOfBoundsException: 23 (this happens for max capacity 12 and above).
I suggest instead of using id, after your solution is complete you track your way backward through the K array (by Java naming conventions, it should be a small k). It holds all the information you need to find out which objects were included in the maximum value.
private static void printKnapsack(int maxCapacity, int weight[], int value[], int n) {
if (K[n][maxCapacity] == 0) {
System.out.println("No objects in knapsack");
} else {
int w = maxCapacity;
for (int i = n; i > 0; i--) {
if (K[i][w] > K[i - 1][w]) { // increased value from object i - 1
System.out.format("ID %2d value %2d weight %2d%n", i, value[i - 1], weight[i - 1]);
// check that value in K agrees with value[i - 1]
assert K[i - 1][w - weight[i - 1]] + value[i - 1] == K[i][w];
w -= weight[i - 1];
}
}
}
}
The above prints the objects backward. Example run:
Enter the maximum capacity:
13
The maximum value that can be put in a knapsack with a weight capacity of 13 is: 36
ID 13 value 21 weight 9
ID 7 value 15 weight 4
If you want the objects in forward order, inside the for loop put them into a list (you may for instance use id from your old attempt), and then print the items from the list in opposite order.

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[])

generation of random output 3n+1 pblm

I have been trying to solve the 3n+1 question in java.However my output seems to be very random. The question is
Consider the following algorithm:
1. input n
2. print n
3. if n = 1 then STOP
4. if n is odd then tex2html_wrap_inline44
5. else tex2html_wrap_inline46
6. GOTO 2
Given the input 22, the following sequence of numbers will be printed 22 11 34 17 52 26 13 40 20 10 5 16 8 4 2 1
It is conjectured that the algorithm above will terminate (when a 1 is printed) for any integral input value. Despite the simplicity of the algorithm, it is unknown whether this conjecture is true. It has been verified, however, for all integers n such that 0 < n < 1,000,000 (and, in fact, for many more numbers than this.)
Given an input n, it is possible to determine the number of numbers printed (including the 1). For a given n this is called the cycle-length of n. In the example above, the cycle length of 22 is 16.
For any two numbers i and j you are to determine the maximum cycle length over all numbers between i and j.
The Input
The input will consist of a series of pairs of integers i and j, one pair of integers per line. All integers will be less than 1,000,000 and greater than 0.
You should process all pairs of integers and for each pair determine the maximum cycle length over all integers between and including i and j.
You can assume that no operation overflows a 32-bit integer.
The Output
For each pair of input integers i and j you should output i, j, and the maximum cycle length for integers between and including i and j. These three numbers should be separated by at least one space with all three numbers on one line and with one line of output for each line of input. The integers i and j must appear in the output in the same order in which they appeared in the input and should be followed by the maximum cycle length (on the same line).
My code is as given below
class CC
{
int c,f,l,m;
int returnCount(int i,int j)
{
f=0;
for(int k=i;k<=j;k++)
{
l=k;
c=0;
while(l>1)
{
if(l%2==0)
{
l=l/2;
c++;
}
else
{
l=3*l+1;
c++;
}
}
if(f<c)
f=++c;
}
return f;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int i,j;
CC obj=new CC();
while(sc.hasNextInt())
{
i=sc.nextInt();
j=sc.nextInt();
System.out.println(i+" "+j+" "+obj.returnCount(i,j));
}}}
Now my Input is
605293 606510
956739 956006
826611 825983
756134 756776
478642 479101
815892 815933
719220 719135
929349 929040
And expected output is
605293 606510 341
956739 956006 352
826611 825983 313
756134 756776 362
478642 479101 338
815892 815933 269
719220 719135 274
929349 929040 339
However my output is
605293 606510 341
956739 956006 0
826611 825983 0
756134 756776 362
478642 479101 338
815892 815933 269
719220 719135 0
929349 929040 0
Please help me find the mistake
The problem is that your in your first line the first number is smaller than the second one, but in the second line the first number is bigger than the second one. You have to switch the numbers or find out the bigger one upfront like that:
import java.util.Scanner;
public class CC {
int c, f, l, m;
int returnCount(int i, int j) {
int smaller = Math.min(i, j);
int bigger = Math.max(i, j);
f = 0;
for (int k = smaller; k <= bigger; k++) {
l = k;
c = 0;
while (l > 1) {
if (l % 2 == 0) {
l = l / 2;
c++;
} else {
l = 3 * l + 1;
c++;
}
}
if (f < c)
f = ++c;
}
return f;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int i, j;
CC obj = new CC();
while (sc.hasNextInt()) {
i = sc.nextInt();
j = sc.nextInt();
System.out.println(i + " " + j + " " + obj.returnCount(i, j));
}
}
}
The input and output looks then like that:
956739
956006
956739 956006 352

Equal Spacing In print statements

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.

Categories