How to populate 2D array (Matrix) from input txt taken from args? - java

My brain has probably stopped working so I really need your help with this.
So, I have an input txt file formatted like this:
3 //Number of Heroes (nodes lets say)
43 43 // left int = hp, right int = damage etc...
22 444
12 43
2 //Number of enemies
20 39 //likewise with the heroes
//The latter (enemies) is not yet implemented, cause I am stuck with the
//first part (so let's say the part before '2' is present in the input
//txt at the moment
My main is this (I want to be able to take multiple files in the future):
public static void main(String[] args) {
Q2 ks = new Q2();
int length = args.length;
for (int i = 0; length > 0; i++) {
ks.readFile(args[i]);
break;
}
}
And this is my readFile(), where I am trying to populate the matrix with the data (but failing miserably because my brain has really stopped working):
public int[][] readFile(String inputName) {
BufferedReader reader;
int Matrix[][] = null;
try {
reader = new BufferedReader(new FileReader(inputName));
String line = reader.readLine();
int numberOfHeroes = Integer.parseInt(line);
Matrix = new int[numberOfHeroes][2];
line = reader.readLine();
System.out.println(numberOfHeroes);
for (int i = 0; i < numberOfHeroes; i++) {
int hitpoints = 0;
int damage = 0;
//while (line != null) {
String splittedLine[] = line.split(" ");
//while (splittedLine[1] != null){
hitpoints = Integer.parseInt(splittedLine[0]);
damage = Integer.parseInt(splittedLine[1]);
Matrix[i][0] = hitpoints;
Matrix[i][i+1] = damage;
line = reader.readLine();
//}
//}
}
System.out.println("====GRAPH====");
for (int i = 0; i < numberOfHeroes; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(Matrix[i][j] + " ");
}
System.out.println();
}
System.out.println("============");
} catch(IOException e) {
return null;
}
return Matrix;
}

You put the damage value into the wrong cell. Instead of Matrix[i][i+1] = damage; you want to do Matrix[i][1] = damage;.

Related

Keep getting run Time error in Kattis. Using Java as a language

Hello I've been getting this error in Kattis, 'Run time error' while all my test cases are correct in my own machine. Tested everything but as soon as i run this in kattis i get a run time error. Can you guys help me figure this out? Ive been debugging for hours but i am struggling.
https://open.kattis.com/problems/throwns?editsubmit=9372235 :Link of the problem
import java.util.*;
import java.io.*;
public class GOT{
public static void main(String[] args)throws IOException{
BufferedReader bi = new BufferedReader(new I
nputStreamReader(System.in));
int[] parseLine1 = new int[2];
String[] strLine1;
strLine1 = bi.readLine().split(" ");
//Parsing of 1st line of inputs i.e. N and K
for (int i = 0; i < strLine1.length; i++) {
parseLine1[i] = Integer.parseInt(strLine1[i]);
}
//init of Kids array
int[] nKids = new int[parseLine1[0]];
String[] commands = new String[parseLine1[1]];
int i;
for(i = 0; i < nKids.length; i++){
nKids[i] = i;
}
//parsing of 2nd line which are the commands
String strLine2;
String[] nCommands;
Scanner sc = new Scanner(System.in);
strLine2 = sc.nextLine();
nCommands = strLine2.split(" ");
int holder=0;
ArrayList<Integer> tracker = new ArrayList<Integer>();
int exit;
int throwns;
int undoCtr=0;
for(i = 0; i<nCommands.length; i++){
if(nCommands[i].equals("undo")){
nCommands[i] = nCommands[i].replaceAll("undo","101");
}
}
exit = nCommands.length;
i = 0;
while(exit != 0){
//System.out.println(Integer.parseInt(nCommands[i]));
if(Integer.parseInt(nCommands[i]) > 0){
for(int k = 0; k< Integer.parseInt(nCommands[i]); k++){
holder++;
if(holder==nKids.length){
holder = 0;
}
}
}if(Integer.parseInt(nCommands[i]) < 0){
for(int k = Integer.parseInt(nCommands[i]); k<0 ; k++){
holder--;
if(holder==0){
holder = nKids.length;
}
}
}else if(Integer.parseInt(nCommands[i]) == 101){
i++;
undoCtr = Integer.parseInt(nCommands[i]);
while(undoCtr!=0){
tracker.remove(tracker.size()-1);
undoCtr--;
}
exit--;
}
tracker.add(holder);
exit--;
i++;
}
System.out.println(tracker.get(0));
}`
}`
Your approach is too complex for a 2.8 difficulty problem. If you find yourself writing more than 25 lines of code, it's usually time to take a step back and re-think your approach.
Here's the algorithm that worked for me:
Make a list of "final" throw commands, initially empty.
Loop over the input tokens and analyze each command:
If a command is a number, append to the command list.
If a command is an undo n, pop the command list n times.
Now sum the commands in the list and print the mod of this sum, taking care to keep the mod positive.
Here's the spoiler:
public class Throwns {
public static void main(String[] args) {
var sc = new java.util.Scanner(System.in);
int n = Integer.parseInt(sc.nextLine().split(" ")[0]);
var line = sc.nextLine().split(" ");
var commands = new java.util.ArrayList<Integer>();
int sum = 0;
for (int i = 0; i < line.length; i++) {
if (line[i].matches("^-?\\d+$")) {
commands.add(Integer.parseInt(line[i]));
continue;
}
for (int j = Integer.parseInt(line[++i]); j > 0; j--) {
commands.remove(commands.size() - 1);
}
}
for (int c : commands) {
sum += c;
}
System.out.println(Math.floorMod(sum, n));
}
}

How come .equals isn't working in this scenario? Even the Debugger is not making sense

This is my first post, so I'm sorry if I didn't do it correctly.
I'm trying to do this USACO problem but basically, my code is throwing an error every time for this particular test case for some reason on the .equals line
I know it's alot of code, but it's a really simple problem
Here's the code:
public class gift1 {
public static void main(String[] Args) throws IOException {
Scanner sc = new Scanner(new File("gift1.in"));
int peeps = sc.nextInt();
String[][] chart = new String[2][peeps];
sc.nextLine();
for(int i = 0; i < peeps; i++) {
chart[0][i] = sc.nextLine();
chart[1][i] = "0";
}
while(sc.hasNextLine()) {
String giver = sc.next(); //we need to find giver
int indexOfgiver = -1;
for(int i = 0; i < peeps; i++) { //finds indexOfgiver
if(giver.equals(chart[0][i])) {
indexOfgiver = i;
break;
}
}
int moneyTogive = sc.nextInt();
chart[1][indexOfgiver] = Integer.toString(Integer.parseInt(chart[1][indexOfgiver]) - moneyTogive);
int numReceivers = sc.nextInt();
if(numReceivers == 0) {
chart[1][indexOfgiver] = Integer.toString( Integer.parseInt(chart[1][indexOfgiver]) );
}
else {
chart[1][indexOfgiver] = Integer.toString( Integer.parseInt(chart[1][indexOfgiver]) + (int) Math.floor(moneyTogive%numReceivers) );
}
String[] receivers = new String[numReceivers];
for(int i = 0; i < numReceivers; i++) { //list the receivers' names in an array
receivers[i] = sc.next();
}
for(int i = 0; i < numReceivers; i++) { //give money to the receivers
for(int j = 0; j < peeps; j++) {
if(chart[0][j].equals(receivers[i])) {
chart[1][j] = Integer.toString( Integer.parseInt(chart[1][j]) + (int) Math.floor(moneyTogive/numReceivers));
}
}
}
}
PrintWriter fW = new PrintWriter("gift1.out");
for(int i = 0; i < peeps; i++)
System.out.println(chart[0][i] + " " + chart[1][i]);
}
}
The error is occurring on line 31 (it's the ugly one that starts with chart[1][indexOfgiver]) and it's saying its an ArrayOutOfBoundsException, which means that the if statement line that is changing the value of variable indexOfgiver for some reason isn't working despite the file being correct.
Here's the file("gift1.in") I'm reading from with the scanner:
10
mitnik
Poulsen
Tanner
Stallman
Ritchie
Baran
Spafford
Farmer
Venema
Linus
mitnik
300 3
Poulsen
Tanner
Baran
Poulsen
1000 1
Tanner
Spafford
2000 9
mitnik
Poulsen
Tanner
Stallman
Ritchie
Baran
Farmer
Venema
Linus
Tanner
Even the debugger is showing that during the first run of the while loop, ~giver~ is equal to "mitnik" and so is ~chart[0][0]~ , but the loop isn't setting ~indexOfgiver~ to ~i~. What is exactly happening?
You have space in names in input file, hence entry in chart array is "Spafford " instead of "Spafford" which you are trying to match.
Since it doesnt match index remains as -1 and causes IndexOutofBoundsException.

save contents from void method to variable

I am trying to print write the contents from void method to a file but I cant seem to get it to work. I call my method in the main and it prints to the console just fine. I have tried many different approaches but not one worked. Can anyone help/guide me in the right direction?
I have pasted my code below for reference. In my main function I call dijkstra(M, SV - 1) that prints my array to the screen, my goal is to have that same array printed to a file.
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.Scanner;
public class Main_2 {
static int SV = 0; // source vertex
static int N = 0;
static int M[][];
public static int distance[];
static int minDistance(int dist[], Boolean shortestPath[]) {
int min = Integer.MAX_VALUE, minI = -1;
for (int i = 0; i < N; i++)
if (shortestPath[i] == false && dist[i] <= min) {
min = dist[i];
minI = i;
}
return minI;
}
public static void printArr(int dist[], int n) {
// System.out.println("vertex distance");
for (int i = 0; i < N; i++)
System.out.println("[" + dist[i] + "]");
}
public static void dijkstra(int graph[][], int src) {
// The output array. dist[i] will hold
// the shortest distance from src to i
int dist[] = new int[N];
// sptSet[i] will true if vertex i is included in shortest
// path tree or shortest distance from src to i is finalized
Boolean shortestPath[] = new Boolean[N];
// Initialize all distances as INFINITE and stpSet[] as false
for (int i = 0; i < N; i++) {
dist[i] = Integer.MAX_VALUE;
shortestPath[i] = false;
}
// Distance of source vertex from itself is always 0
dist[src] = 0;
// Find shortest path for all vertices
for (int i = 0; i < N - 1; i++) {
// Pick the minimum distance vertex from the set of vertices
// not yet processed. u is always equal to src in first
// iteration.
int u = minDistance(dist, shortestPath);
// Mark the picked vertex as processed
shortestPath[u] = true;
// Update dist value of the adjacent vertices of the
// picked vertex.
for (int j = 0; j < N; j++)
// Update dist[v] only if is not in sptSet, there is an
// edge from u to v, and total weight of path from src to
// v through u is smaller than current value of dist[v]
if (!shortestPath[j] && graph[u][j] != 0 && dist[u] != Integer.MAX_VALUE
&& dist[u] + graph[u][j] < dist[j])
dist[j] = dist[u] + graph[u][j];
}
// print the constructed distance array
printArr(dist, N);
}
public static void main(String[] args) {
try {
int i = 0, j = 0; // counters
FileInputStream textFile = new FileInputStream("EXAMPLE(2).txt"); // name of input file must go in here
Scanner scan = new Scanner(textFile);
N = scan.nextInt(); // read in the size
String flush = scan.nextLine(); // gets rid of linefeed
System.out.println(N);
M = new int[N][N]; // instantiates array
// this loop reads in matrix from input file
String line;
while (i < N && (line = scan.nextLine()) != null) {
j = 0;
String delim = " ";
String tokens[] = line.split(delim);
for (String a : tokens) {
M[i][j] = Integer.parseInt(a);
j++;
}
i++;
}
if (i > N)
;
SV = scan.nextInt();
} catch (Exception e) {
e.printStackTrace();
}
printMatrix(M);
System.out.println(SV);
System.out.println();
dijkstra(M, SV - 1);
try {
FileWriter fw = new FileWriter("Shortest_path.txt"); // writes transitive closure to file
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < N; i++) {
// bw.write(dist[i]);
}
} catch (Exception e) {
System.out.println(e);
}
}
public static void printMatrix(int[][] Matrix) {
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
System.out.print(Matrix[i][j]);
System.out.print(" ");
}
System.out.println();
}
}
}
try (FileWriter fileWriter = new FileWriter("YourFileName.txt");
PrintWriter printWriter = new PrintWriter(fileWriter)) {
for (int i=0; i<N; i++) {
printWriter.printf(Integer.toString(dist[i]));
}
} catch (Exception e) {
System.out.println(e);
}
"A" simple solution, would be to pass the PrintStream you want to use to the method, for example...
public static void printArr(int dist[], int n, PrintStream ps) {
for (int i = 0; i < N; i++) {
ps.println("[" + dist[i] + "]");
}
}
This will then require you to pass a PrintStream instance to the method when ever you call it. Since dijkstra also calls printArr, you will need to pass the instance of the PrintStream to it as well...
public static void dijkstra(int graph[][], int src, PrintStream ps) {
//...
// print the constructed distance array
printArr(dist, N, ps);
}
Then you just create an instance of the PrintStream you want to use and pass it to the methods...
public static void main(String[] args) {
try (FileInputStream textFile = new FileInputStream("EXAMPLE(2).txt")) {
int i = 0, j = 0; // counters
Scanner scan = new Scanner(textFile);
N = scan.nextInt(); // read in the size
String flush = scan.nextLine(); // gets rid of linefeed
System.out.println(N);
M = new int[N][N]; // instantiates array
// this loop reads in matrix from input file
String line;
while (i < N && (line = scan.nextLine()) != null) {
j = 0;
String delim = " ";
String tokens[] = line.split(delim);
for (String a : tokens) {
M[i][j] = Integer.parseInt(a);
j++;
}
i++;
}
if (i > N)
;
SV = scan.nextInt();
try (PrintStream ps = new PrintStream("EXAMPLE(2).txt")) {
printMatrix(M);
System.out.println(SV);
System.out.println();
dijkstra(M, SV - 1, ps);
}
} catch (Exception e) {
e.printStackTrace();
}
}
I restructured your main method slightly, as the output is depended on the success of the input ;). Also see The try-with-resources statement for more details
This means you could do something like...
dijkstra(M, SV - 1, System.out);
and it would once again print the output to the console :)

Java - NumberFormatException when using .parseInt(String)

I am trying to run a loop to see if an int is sorted. however the int has to be converted from a string. here is my code.
public static void main(String[] args) {
// TODO code application logic here
Scanner maxVal = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("enter the max value of ordered squares:");
int max = maxVal.nextInt();
for(int i = 0; i*i <= max; i++){
int L = String.valueOf(i*i).length();
String sq = String.valueOf(i*i);
String [] digits = new String[L];
for(int a = 0; a < L; a++){
digits [a] = Character.toString(sq.charAt(a));
if(L == 1){
System.out.print(sq + "");
}else if(Integer.parseInt(digits [a]) < Integer.parseInt(digits[a+1])){
System.out.print(sq);
}else{
}
}
}
}
when I run it, I get an error :
Exception in thread "main" java.lang.NumberFormatException: null
0149 at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
why does Integer.parseInt() not work
Your problem is that digits[a+1] hasn't been defined yet. I see that on line 2 you have
digits[a] = Character.toString(sq.charAt(a));
and you're iterating over a in a for loop, so I daresay that digits[a+1] hasn't been assigned yet.
UPDATE 1
Check out this solution, it shows how to properly catch that exception and how to avoid it:
Java: Good way to encapsulate Integer.parseInt()
UPDATE 2
I decided to add a fixed version of your code:
public static void main(String[] args) {
// TODO code application logic here
Scanner maxVal = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("enter the max value of ordered squares:");
int max = maxVal.nextInt();
for(int i = 0; i*i <= max; i++){
int L = String.valueOf(i*i).length();
String sq = String.valueOf(i*i);
String [] digits = new String[L];
for(int a = 0; a < L; a++){
digits [a] = Character.toString(sq.charAt(a));
if(L == 1 || a == 0){
System.out.print(sq + "");
}else if(Integer.parseInt(digits [a]) < Integer.parseInt(digits[a+1])){
System.out.print(sq);
}else{
}
}
}
}
While I don't know the utility of your code, but this implementation might be simpler:
public static void main(String[] args) {
// TODO code application logic here
Scanner maxVal = new Scanner(new BufferedReader(new InputStreamReader(System.in)));
System.out.println("enter the max value of ordered squares:");
int max = maxVal.nextInt();
for(int i = 0; i*i <= max; i++){
long sq = i*i;
if(sq > 9){
String[] digits = sq.toString().split("");
//Notice that I start at index 1, so I can do [a-1] safely
for(int a = 1; a < digits.length; a++){
if(Integer.parseInt(digits [a-1]) < Integer.parseInt(digits[a])){
System.out.print(sq);
//I guess we don't want a number like 169 (13*13) to be displayed twice, so:
break;
}
}
} else {
System.out.print(sq);
}
}
}

How can I avoid repetition of the same number?

This is what I want :
Let the user enter as many numbers as they want until a non number is entered (you may
assume there will be less than 100 numbers). Find the most frequently entered number. (If
there are more than one, print all of them.)
Example output:
Input: 5
Input: 4
Input: 9
Input: 9
Input: 4
Input: 1
Input: a
Most common: 4, 9
I have got to the point in my code where I have managed to find out which are the most common numbers. However, I don't want to print out the same number over and over again; example from above: Most common: 4, 9, 9, 4
What needs to be done?
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String[] input = new String[100];
System.out.print("Input: ");
input[0] = in.readLine();
int size = 0;
for (int i = 1; i < 100 && isNumeric(input[i-1]); i++) {
System.out.print("Input: ");
input[i] = in.readLine();
size = size + 1;
}
/*for (int i = 0; i < size; i++) { //testing
System.out.println(input[i]);
}*/
int numOccur;
int[] occur = new int[size];
for(int i = 0; i < size; i++) {
numOccur = 0;
for (int j = 0; j < size; j++) {
if(input[i].equals(input[j])) {
numOccur = numOccur + 1;
}
}
occur[i] = numOccur;
//System.out.println(numOccur); //testing
}
int maxOccur = 0;
for(int i = 0; i < size; i++) {
if(occur[i] > maxOccur) {
maxOccur = occur[i];
}
}
//System.out.println(maxOccur); //testing
for (int i = 0; i < size && !numFound; i++) {
if(occur[i] == maxOccur) {
System.out.println(input[i]);
}
}
}
//checks if s is an in, true if it is an int
public static boolean isNumeric (String s) {
try {
Integer.parseInt(s);
return true; //parse was successful
} catch (NumberFormatException nfe) {
return false;
}
}
Found the solution!
String[] mostCommon = new String[size];
int numMostCommon = 0;
boolean numFound = false;
for (int i = 0; i < size; i++) {
int isDifferent = 0;
if (occur[i] == maxOccur) {
for (int j = 0; j < size; j++) {
if (!(input[i].equals(mostCommon[j]))) {
isDifferent = isDifferent + 1;
}
}
if (isDifferent == size) {
mostCommon[numMostCommon] = input[i];
numMostCommon = numMostCommon + 1;
}
}
}
for (int i = 0; i < numMostCommon - 1; i++) {
System.out.print("Most common: " + mostCommon[i] + ", ");
}
System.out.println(mostCommon[numMostCommon - 1]);
you could use the hash table for this to store the frequenceis as the limit is very less i.e. less than 100.
pseudo code would be like:
vector<int> hash(101)
cin>>input
if(isnumeric(input))
hash[input]++
else{
max=max_element(hash.begin(),hash.end());
for(int i=0;i<100;i++)
if(hash[i]==max)
print i
}
Set<Integer> uniqueMaxOccur = new HashSet<Integer>();
for (int i = 0; i < size ; i++) {
if(occur[i] == maxOccur) {
//System.out.println(input[i]);
uniqueMaxOccur.add(input[i]);
}
}
and display the values in the set
You can use a Set and store the values already printed.
What about something like this?
public static void main(String[] args) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Map<string,int> numberLookup = new HashMap<string,int>();
Boolean doContinue = true;
while (doContinue)
{
System.out.print("Input: ");
String input = in.readLine();
if (isNumeric(input))
{
if (!numberLookup.containsKey(input))
numberLookup.put(input,1);
else
numberLookup.put(input, numberLookup.get(input) + 1);
}
else
doContinue = false;
}
maxOccur = numberLookup.values().max();
System.out.print("These numbers were all entered " + maxOccur + " times:");
Iterator it = numberLookup.entrySet().iterator();
while (it.hasNext())
{
(Map.Entry)it.next();
System.out.println(pairs.getKey());
}
}
Sorry, I'm a C# person and don't have a Java compiler on me, so this might need some tweaking.

Categories