Counting Inversion hangs in the terminal - java

The code runs for a small file size.But it hangs when i use a file of huge size say 100000.The code used is:
import java.util.Scanner;
import java.util.Formatter;
import java.util.NoSuchElementException;
import java.lang.IllegalStateException;
import java.io.FileNotFoundException;
import java.io.*;
import java.lang.*;
public class mergesort1
{
private int arr[];
private int length;
private Scanner sc;
private Formatter f;
public static int inversion=0;
public mergesort1()
{
try
{
sc=new Scanner(new File("IntegerArray.txt"));
}
catch(FileNotFoundException fe)
{
System.err.println("File not found");
}
arr=new int[100000];
length=arr.length;
int i=0;
try
{
while(sc.hasNext())
arr[i++]=sc.nextInt();
}
catch (NoSuchElementException ne)
{
System.err.println("File formed wrong");
sc.close();
System.exit(1);
}
catch(IllegalStateException stateException)
{
System.err.println("Error reading from the file.");
System.exit(1);
}
split(0,length-1);
writeback();
}
private void split(int low,int high)
{
int mid;
if ((high-low)>=1)
{
mid=(low+high)/2;
split(low,mid);
split(mid+1,high);
merge(low,mid+1,high);
}
}
private void merge(int low,int mid,int high)
{
int count=low;
int lcount=low;
int rcount=mid;
int[] merged=new int[length];
while (lcount<=mid-1 && rcount<=high)
{
if (arr[lcount]<arr[rcount])
merged[count++]=arr[lcount++];
else
{
merged[count++]=arr[rcount++];
inversion=inversion+(mid-1-low);
}
}
if (lcount!=mid)
{
while (lcount<=mid-1)
{
if (arr[count]!=count)
merged[count++]=arr[lcount++];
}
}
else
{
while (rcount<=high)
{
if (arr[count]!=count)
merged[count++]=arr[rcount++];
}
}
System.out.println("The inversions counted till now is "+inversion);
for(int i=low;i<=high;i++)
arr[i]=merged[i];
}
private void writeback()
{
try
{
f=new Formatter("output.txt");
}
catch(FileNotFoundException fe)
{
System.err.println("File Not found");
}
for(int i=0;i<arr.length;i++)
f.format("%d\n",arr[i]);
System.out.println("The number of inversions is:"+inversion);
sc.close();
f.close();
}
}
Now the code runs fine for a input of 2 4 1 3 5 and the number of inversions is 3.But for a code of counting inversions of a input of size:100000 it hangs after counting till 103782637.

Try running with high memory
java -Xms512m -Xmx1024m yourclass

Related

How to end a infinite while loop with user input

I am trying to create a loading sequence of 3 dots that repeats itself until input from the user breaks the loading sequence specifically the enter key. i connot for the life of me get the infinite while loop to end with input
public class loop {
public static void AnyKey() {
try {
System.in.read();
loading(false);
} catch (Exception e){}
}
public static void pause(long duration) {
try{
Thread.sleep(duration);
} catch (InterruptedException e){}
}
public static void loading(boolean status){
if (status == true) {
while (status) {
pause(500);
int i;
for (i = 0; i <3; i++){
System.out.print(".");
pause(500);
}
System.out.print("\b\b\b");
}
}
}
public static void main(String[] args) {
loading(true);
AnyKey();
}
}
In your current code, the main method calls loading and never leaves the function. If you go through loading(true) step by step, you find that since while(status) is always true you are stuck there and AnyKey() is never called.
Also, System.in.read(); is a blocking call. This means that you will wait for user input but will be unable to print the '...'. Instead I recommend your read the documentation for input stream, there you will find the .read() function but also the .available() function which will let you know if any characters have been entered in the input buffer.
Those should be all the tools you need to figure this one out (I think).
Hope this helps!
I figured it out i needed to learn about and use Threads and global variables check out my code below im fairly pleased with myself i was working on this for 3 days now lol
import java.util.Scanner;
class AnyKey extends Thread {
public void run() {
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
loadingDots.loadingStatus = false;
}
}
public class loadingDots {
public static boolean loadingStatus;
public static void pause(long duration) {
try {
Thread.sleep(duration);
} catch (InterruptedException e) {}
}
public static void loading(){
loadingStatus = true;
while (loadingStatus) {
pause(500);
int i;
for (i = 0; i < 3; i++) {
if (!loadingStatus){
break;
}
System.out.print(".");
pause(500);
}
System.out.print("\b\b\b");
}
}
public static void main(String[] args) {
AnyKey anykey = new AnyKey();
anykey.start();
loading();
}
}

Java: issue calculating average from txt file

Hello everybody first post on here!
i'm currently having some issues with my readfromfile() to calculate an average my issue is that its printing the ten numbers "stuck together"
like 12345678910 i dont understand how i can calculate an average like this i tried token/10 and it returns 0000000000
any suggestions getting an average from this mess?
i tried returning token with %n%s which looks better but still when i divide by 10 it doesnt give me a correct number what am i doing wrong
package average;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Formatter;
import java.util.InputMismatchException;
import java.util.Scanner;
public class average {
private static Formatter output;
private static Scanner input;
public static void main(String[] args) {
openFileWrite();
writeToFile();
closeFile();
openFileRead();
readFromFile();
closeFileRead();
}
public static void openFileRead() { // gets file for "read"
try {
input = new Scanner(Paths.get("Numbers.txt"));
} catch (IOException e) {
System.out.println("Unable to read file");
}
}
public static void openFileWrite() { // gets file for "write"
try {
output = new Formatter("Numbers.txt");
} catch (FileNotFoundException e) {
System.out.println("Unable to open file");
}
}
public static void readFromFile() {
while (input.hasNextInt()) {
int token = input.nextInt();
System.out.print(token);
}
}
public static void writeToFile() {
Scanner input = new Scanner(System.in);
System.out.println("Enter 10 numbers");
try {
for (int i = 0; i < 10; i++) {
System.out.println("Another Number Please");
int total = input.nextInt();
output.format("%s%n", total);
}
} catch (InputMismatchException e) {
System.out.println("Please do not enter any letters");
writeToFile();
}
}
//required to close file for write
public static void closeFile() {
output.close();
}
//required to close file for read
public static void closeFileRead() {
input.close();
}
}
Just change your readFromFile method as:-
public static void readFromFile() {
double average = 0;
while (input.hasNextInt()) {
int token = input.nextInt();
average+=token;
}
System.out.println("Average ="+average/10);
}

Unidentifiable NZEC Error in Code-ENTEXAM

I was working on one of the problems on codechef.com https://www.codechef.com/problems/ENTEXAM
Here is my solution for the problem-
import java.io.*;
class Entrance_Final
{
static BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
static int test_case=0;//Test cases
static int students=0;
static int qualifiers=0;
static long result=0;
static int exams=0;
static long max_marks=0;
static long[]sigma_res;
static long sergey_score=0;
public static void main(String[]args)throws IOException
{
try
{
//System.out.println("Enter number of test cases.");
test_case=Integer.parseInt(in.readLine());
for(int lv=1;lv<=test_case;lv++)
comp_min_marks();
}
catch(Exception e)
{
System.err.println(e);
}
}
public static void comp_min_marks()throws IOException
{
try
{
//System.out.println("Enter students,enrollees,exams and maximum marks.");
String a=in.readLine();
a=a.trim();
int flag=0;
int times=1;
for(int lv=0;lv<a.length();lv++)
{
if(a.charAt(lv)==' '&&(times==1))
{
students=Integer.parseInt(a.substring(0,lv));
flag=lv+1;
times++;
}
else if(a.charAt(lv)==' '&&(times==2))
{
qualifiers=Integer.parseInt(a.substring(flag,lv));
flag=lv+1;
times++;
}
else if(a.charAt(lv)==' '&&(times==3))
{
exams=Integer.parseInt(a.substring(flag,lv));
flag=lv+1;
times++;
max_marks=Long.parseLong(a.substring(flag));
break;
}
}
sigma_res=new long[students-1];
//System.out.println("Enter the marks of all the students during their exams,each ones in one line");
for(int lv=0;lv<students-1;lv++)
{
String b=in.readLine();
sigma_res[lv]=int_sum(b);
}
//System.out.println("Now enter Sergey's scores");
if(exams==1)
{
//String b=in.readLine();
sergey_score=0;
}
else
{
String b=in.readLine();
sergey_score=int_sum(b);
}
sigma_res=doQuickSort(0,students-2);
result=sigma_res[students-qualifiers-1]-sergey_score+1;
if(result<0)
System.out.println("0");
else if(result<=max_marks)
System.out.println(result);
else
System.out.println("Impossible");
}
catch(Exception e)
{
System.err.println(e);
}
}
public static long int_sum(String b)throws IOException
{
try
{
b=b.trim();
long res=0;
int flag=0;
for(int lv=0;lv<b.length();lv++)
{
if(b.charAt(lv)==' ')
{
res+=Long.parseLong(b.substring(flag,lv));
flag=lv+1;
}
}
res+=Long.parseLong(b.substring(flag));
return res;
}
catch(Exception e)
{
System.err.println(e);
return -1;
}
}
private static long[] doQuickSort(int low,int high)throws IOException
{
try
{
if(high-low<1)
return sigma_res;
int wall=low;
int pivot_pos=(int)(Math.random()*(high-low))+low;
long pivot=sigma_res[pivot_pos];
long temp=sigma_res[high];
sigma_res[high]=pivot;
sigma_res[pivot_pos]=temp;
pivot_pos=high;
for(int lv=low;lv<=high-1;lv++)
{
if(pivot>sigma_res[lv])
{
temp=sigma_res[lv];
sigma_res[lv]=sigma_res[wall];
sigma_res[wall]=temp;
wall++;
}
}
temp=sigma_res[wall];
sigma_res[wall]=pivot;
sigma_res[pivot_pos]=temp;
pivot_pos=wall;
doQuickSort(low,wall-1);
doQuickSort(wall+1,high);
return sigma_res;
}
catch(Exception e)
{
System.err.println(e);
return sigma_res;
}
}
}
As you have probably noticed, I have enclosed all the code within my program in rather redundant try-catch blocks returning arbitrary exceptions. This is because I am always getting an NZEC-Error for my code (when I submit it online) and despite using these blocks, the error is persisting. I have repeatedly had a look at the constraints of the problem but had no luck figuring out what the issue is.
P.S I do not have access to the test cases of this problem.
Since there is no response here and I was able to figure out the issue, I suppose I might as well as answer my question. So first of all there was no exception at all, instead I was getting a VirtualMachineError in the line
sigma_res=new long[students-1];
(No idea why this was happening,all I know is the value of 'students' exceeded its constraint-defined limits).
After looking at a few solutions, I figured the issue was caused by taking the println statements out of the main() method and placing them in another one.
The moment I put the println statement back into main(), the solution was accepted.
P.S I still don't know why the program wouldn't terminate when the println statements where in another method.

Custom Exceptions String Array

I'm building a custom exception which basically is thrown if an array doesn't contain 5 strings. This is what I have so far. The only exception that really matters is the custom one as I just have to show that that exception is thrown if the array doesn't contain the 5 strings after the input file was split. Any help would be appreciated. Thanks!
package exceptions;
import java.io.File;
import java.util.Scanner;
public class Exceptions {
public static void main(String[] args) {
String input, formattedInt, field[];
int recordNumber = 0;
int length;
Scanner inputFile;
try {
inputFile = new Scanner(new File("data.txt"));
while (inputFile.hasNextLine()) {
recordNumber++;
formattedInt = String.format("%2d", recordNumber);
input = inputFile.nextLine();
field = input.split(",");
length = field.length;
if (field.length != 5) throw new CustomException(field.length);
System.out.println("Record #" + formattedInt + ": " + input);
}
} catch (Exception e) {
System.out.println("Error! Problem opening file.\nError was: " + e);
} catch (CustomException ce) {
System.out.println(ce);
}
}
}
CustomException.java
package exceptions;
public class CustomException extends Exception {
private int fieldcount;
public CustomException(int fieldCount) {
super("Invalid Count: " + fieldCount);
}
public int getCount() {
return fieldcount;
}
}
CustomException extends Exception so any CustomException will be caught in the first catch block.
Rearrange your blocks so the catch(CustomException e) block comes before the catch(Exception e) block

Java read file with scanner

I have this code that have some methods for creating a file, adding data to the file and then read the file with scanner.
My problem is that I want it to run my three methods at once but it stops
at the method number two and does not read the file with readFile() method
createFile();
addResponses(file);
readFile(file);
I can not run these three together. It does not read the file. But if I take
the other methods away like this
//createFile();
//addResponses(file);
readFile(file);
Then the read file method works.
I hope you did understand my problem. Is there something wrong with my code?
import java.io.*;
import java.util.Formatter;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Main {
static Formatter f;
static String sträng = " ";
static BufferedWriter output;
static File file;
static int nummer = 1;
static int counter = 0;
static private StringBuffer strBuff;
static InputStream is;
static FileWriter fw;
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
createFile();
addResponses(file);
readFile(file);
}
public static int addResponse() {
if (nummer == 6) {
try {
output.close();
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
System.exit(0);
}
sträng = JOptionPane.showInputDialog("Numbers 1-5 to number " + nummer");
try {
return Integer.parseInt(sträng);
} catch (NumberFormatException f) {
return 6;
}
}
public static File createFile() {
try {
file = new File("numbers.txt");
f = new Formatter(file);
f.close();
} catch (SecurityException se) {
System.err.println("You dont have write access to this file");
System.exit(1);
} catch (Exception ex) {
System.err.println("Error opening or creating file");
System.exit(1);
}
return file;
}
public static void readFile(File x) {
try {
x = new File("numbers.txt");
Scanner in = new Scanner(x);
while (in.hasNextLine()) {
System.out.println(in.nextLine());
}
in.close();
} catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public static void addResponses(File f) throws IOException {
try {
fw = new FileWriter(f, true);
output = new BufferedWriter(fw);
int x = addResponse();
if (nummer == 1) {
output.write(String.format("%s%10s\n", "Rating", " Frequency"));
}
while (x != -1) {
if (x > 0 && x < 6) {
output.write(String.format("%s%10s\n", nummer, sträng));
nummer++;
} else {
JOptionPane.showMessageDialog(null, "Input only numbers between 1-5");
}
x = addResponse();
}
output.close();
} catch (IOException io) {
JOptionPane.showMessageDialog(null, "Wrong");
}
}
}
after playing around with the code, I found out that in your addResponse() method , you have added System.exit(0); so baiscally program was terminating. I've change it to return -1 and it seems to be working.
by the way, this is a very bad coding practice, each method should do stuff seperately regarless of other method. in your case everything is so integerated that is very hard to root the problem. I recommend you looking at some coding convention.
this is how addResponse() method should be working:
public static File createFile() {
try {
file = new File("numbers.txt");
f = new Formatter(file);
f.close();
} catch (SecurityException se) {
System.err.println("You dont have write access to this file");
System.exit(1);
} catch (Exception ex) {
System.err.println("Error opening or creating file");
System.exit(1);
}
return file;
}

Categories

Resources