How do I adapt this program to comply with the online judge? - java

I'm solving UVA's Edit Step Ladders on an uva sub-site named programming-challenges.com, but since I didn't get at all the format in which I'm supposed to test-input I simply took their sample input, put it into a text file and tested my code from there. Like this:
import java.io.*;
import java.util.*;
class Levenshtein {
private static int minimum(int a, int b, int c) {
if(a<=b && a<=c)
return a;
if(b<=a && b<=c)
return b;
return c;
}
public static int computeLevenshteinDistance(String str1, String str2) {
return computeLevenshteinDistance(str1.toCharArray(),
str2.toCharArray());
}
private static int computeLevenshteinDistance(char [] str1, char [] str2) {
int [][]distance = new int[str1.length+1][str2.length+1];
for(int i=0;i<=str1.length;i++)
distance[i][0]=i;
for(int j=0;j<=str2.length;j++)
distance[0][j]=j;
for(int i=1;i<=str1.length;i++)
for(int j=1;j<=str2.length;j++)
distance[i][j]= minimum(distance[i-1][j]+1,
distance[i][j-1]+1,
distance[i-1][j-1]+
((str1[i-1]==str2[j-1])?0:1));
return distance[str1.length][str2.length];
}
public static void main(String args[]){
ArrayList<String> theWords = new ArrayList<String>();
try {
String ruta="entradaLevenshtein.txt";
File myFile = new File (ruta);
FileReader fileReader = new FileReader(myFile);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
while ((line=reader.readLine())!=null){
System.out.println(line);
theWords.add(line);
}
reader.close();
}
catch (IOException ex){
ex.printStackTrace();
}
{}
// todo esto sólo para iniciar el arreglo
// ahora vienen las llamadas a Levenstein y las comparaciones
int maxEdit=0;
int actualEdit=0;
int wordsIndex1 =0, wordsIndex2=0;
while (wordsIndex1<= theWords.size())
{
while (wordsIndex2<= theWords.size()-1){
actualEdit=computeLevenshteinDistance(theWords.get(wordsIndex1),theWords.get(wordsIndex2));
if (actualEdit>maxEdit){maxEdit=actualEdit;}
wordsIndex2++;
}
wordsIndex1++;
}
System.out.println(maxEdit+1);
}
}
my input file being:
cat
dig
dog
fig
fin
fine
fog
log
wine
I'm supposed to make the code comply to the following pattern, thing is..I don't get where this thing is capturing its String:
import java.io.*;
import java.util.*;
class Modelo implements Runnable{
static String ReadLn(int maxLength){ // utility function to read from stdin,
// Provided by Programming-challenges, edit for style only
byte line[] = new byte [maxLength];
int length = 0;
int input = -1;
try{
while (length < maxLength){//Read untill maxlength
input = System.in.read();
if ((input < 0) || (input == '\n')) break; //or untill end of line ninput
line [length++] += input;
}
if ((input < 0) && (length == 0)) return null; // eof
return new String(line, 0, length);
}catch (IOException e){
return null;
}
}
public static void main(String args[]) // entry point from OS
{
Modelo myWork = new Modelo(); // Construct the bootloader
myWork.run(); // execute
}
public void run() {
new myStuff().run();
}
}
class myStuff implements Runnable{
public void run(){
try
{
/// PLACE YOUR JAVA CODE HERE
}catch(Exception e){
System.out.println("A Exception was generated");
}
}
// You can insert more classes here if you want.
}
Why should I place it where it says //place your code here and not here??
try{
while (length < maxLength){//Read untill maxlength
input = System.in.read();
if ((input < 0) || (input == '\n')) break; //or untill end of line input
line [length++] += input;
}
How do I manipulate the input??

I think the idea here is to write your program in the myStuff class, where it will be called in the run() method. From the run() method, you can use Modelo.ReadLn() to get your input.

Related

use a method to read numbers from a text file and return the prime numbers

the question says: Create a class named HW09. In this class implement a method named primeCounter
with the following signature, that takes a file name as string (for example “numbers.txt”) and returns the number of prime numbers in the text file. Assume the text file only contains integer numbers.
I tried to build the code for the program But I keep getting these error messages and I'm not sure how to fix them and get the program running again. My knowledge of the file access concept is very weak and my professor is horrible. I hope someone can help me understand what went wrong
import java.io.*;
import java.util.Scanner;
class HW09 {
public static int primeCounter(String fileName) throws IOException {
int count= 0;
int number;
String x= null;
File filename= new File("C:/Users/black/Desktop/file.txt");
Scanner s = new Scanner(filename);
BufferedReader data= null;
data= new BufferedReader (new FileReader(filename));
while (s.hasNextInt()) {
number= Integer.parseInt(x);
int see=0;
for (int i =1; i<=number; i++) {
if (number%i==0) {
see = see+1;
}
if (see>2) {
break;
}
}
if (see==2) {
count = count+1;
}
}
return count;
}
public static void main (String args []) {
try {
String file= ("C:/Users/black/Desktop/file.txt");
System.out.println(HW09.primeCounter(file));
}
catch (IOException e) {
System.out.println("Couldn't find file! ");
}
}
}
I see a number of issues with your current code, first and foremost is the lack of separation of concerns. I would start with a simple method to determine if a single number is prime. I wrote such a method here, and that looks like
private static boolean isPrime(int n) {
if (n == 2) {
return true;
} else if (n == 1 || n % 2 == 0) {
return false;
}
for (int i = 3; i * i <= n; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
Then you want to read numbers with your Scanner. And check if they are prime. And don't forget to close the Scanner when you're done. Using a try-with-resources takes care of that. Like,
public static int primeCounter(String fileName) throws IOException {
int count = 0;
try (Scanner s = new Scanner(new File(fileName))) {
while (s.hasNextInt()) {
int v = s.nextInt();
if (isPrime(v)) {
count++;
}
}
}
return count;
}
Finally, when constructing a path, it's better to use the system properties to get the home folder. That way, it can work on other people's machines more easily,
public static void main(String args[]) {
try {
String file = new File(
System.getProperty("user.home"), "Desktop/file.txt").getPath();
System.out.println(primeCounter(file));
} catch (IOException e) {
System.out.println("Couldn't find file! ");
}
}
And I created a file to test against,
$ cat ~/Desktop/file.txt
13
11
7
5
3
2
4
After running the program I get, as expected,
6

Java File I/O: What condition should i put to stop duplicate writing of letter frequency in a text file?

So I am getting close to finishing my code for character frequency in java. So the directions are to get a text file and save the character frequencies (From A-Z,a-z and 0-9) into another text file, but the number of frequencies are sorted there. Here's what I came up with:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
import javax.swing.JFileChooser;
public class Machine_Exer6 {
public void charfrequency() {
// TODO Auto-generated method stub
File infile = null;
File result = null;
Scanner myscan = null;
JFileChooser fc= new JFileChooser();
fc.showOpenDialog(null);
infile = fc.getSelectedFile();
fc.setSelectedFile(new File(""));
fc.showSaveDialog(null);
result = fc.getSelectedFile();
try {
myscan = new Scanner(infile);
while(myscan.hasNextLine()){
String str = myscan.nextLine();
Alphanumeric(str, result);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
myscan.close();
}
}
private void Alphanumeric(String str, File result) {
// TODO Auto-generated method stub
int ctr=0;
PrintWriter printtofile = null;
try {
printtofile = new PrintWriter(result);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try{
for(int j=0; j<str.length(); j++){
for (int i=0; i<str.length(); i++){
if((str.charAt(j)==str.charAt(i) || str.charAt(j)==Character.toUpperCase(str.charAt(i))) && (Character.isAlphabetic(str.charAt(j)) || Character.isDigit(str.charAt(j)))){
ctr++;
}
}
if (ctr!=0){
printtofile.println(str.charAt(j)+": "+ctr);
ctr=0;
}
}
}finally{
printtofile.close();
}
}
But then as I try to read a text file, say, that has its contents as:
"Whenever
Wherever wherever wherever
you are
i will love, love, love."
The created text file goes like this:
i: 2
w: 1
i: 2
l: 5
l: 5
l: 5
o: 3
v: 3
e: 3
l: 5
o: 3
v: 3
e: 3
l: 5
o: 3
v: 3
e: 3
also, the uppercase letters aren't included in the lowercase counter. Is there any way to fix this?
This might help:
import java.io.*;
import java.util.*;
public class Frequency {
private static final int DIGIT_START = 48;
private static final int DIGIT_END = 57;
private static final int UPPER_START = 65;
private static final int UPPER_END = 90;
private static final int LOWER_START = 97;
private static final int LOWER_END = 122;
private final BufferedReader reader;
private final Map<Character, Integer> frequencyCounter;
public Frequency(File file) throws FileNotFoundException {
reader = new BufferedReader(new FileReader(file));
frequencyCounter = new HashMap<>();
}
public void calculateFrequency() throws IOException {
int input;
while((input = reader.read()) != -1){
if(isAlphaNeumeric(input)){
char validInput = (char)Character.toLowerCase(input);
if(!frequencyCounter.containsKey(validInput)){
frequencyCounter.put(validInput, 1);
}
else{
frequencyCounter.put(validInput,
frequencyCounter.get(validInput) + 1);
}
}
}
}
public boolean isAlphaNeumeric(int toTest){
return isAlphaNewNeumericHelp(toTest, DIGIT_START, DIGIT_END) ||
isAlphaNewNeumericHelp(toTest, UPPER_START, UPPER_END) ||
isAlphaNewNeumericHelp(toTest, LOWER_START, LOWER_END);
}
private boolean isAlphaNewNeumericHelp(int toTest,
int lowerBound,
int upperBound){
return toTest >= lowerBound && toTest <= upperBound;
}
public void printFrequency(){
final List<Map.Entry<Character, Integer>> stringCounts =
new ArrayList<>(frequencyCounter.entrySet());
Collections.sort(stringCounts,
(o1, o2) -> o1.getKey().compareTo(o2.getKey()));
stringCounts.forEach(System.out::println);
}
public static void main(String[] args) throws IOException {
Frequency frequency = new Frequency(new File("file"));
frequency.calculateFrequency();
frequency.printFrequency();
}
}
The Map keeps track of all of the counts. After determining that a character is valid then force it to lower case and cast it to a char. If the Map does not have an entry that corresponds to the valid character then add one, otherwise update the Map value side. For now just print the sorted results to the console.
Hope it helps.

Getting wrong answer from Uva judge for the 3n+1problem

I tried to submit the 3n+1 problem several time but failed to get it accepted on the Uva judge.I wrote the program in java.Can anyone point out the mistake in my program.
Problem statement:-
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=29&page=show_problem&problem=36
My program:-
import java.io.*;
import java.util.*;
class Main
{
static String ReadLn (int maxLg) // utility function to read from stdin
{
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
String line = "";
try
{
while (lg < maxLg)
{
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
}
}
catch (IOException e)
{
return (null);
}
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
}
public static void main (String args[]) // entry point from OS
{
Main myWork = new Main(); // create a dinamic instance
myWork.Begin(); // the true entry point
}
void Begin()
{
String input;
while((input=Main.ReadLn(255))!=null){
StringTokenizer str=new StringTokenizer(input);
int n1=Integer.parseInt(str.nextToken());
int n2=Integer.parseInt(str.nextToken());
int max=0;
for(int i=n1;i<=n2;i++)
{
int no=calculate(i,0);
if(max<no){
max=no;
}
}
System.out.println(n1+" "+n2+" "+max);
}
}
static int calculate(int a,int sum){
if(a==1)
{
return sum+1;
}
else if(a%2==0)
{
sum+=1;
return calculate(a/2,sum);
}
else
{
sum+=1;
return calculate((3*a+1),sum);
}
}
}
I am very sorry for bad indentation of my code.
I think the problem is with the input/output. The code in your question reads one line and then prints one line. The input/ouput on the UVa page specifies to use a "series" for input and use "for each" as ouput. In other words: read all the input lines, calculate, and then write all the output lines.
Here is some code to help you read all the input-lines (the ReadLn method in your question looks overly complicated):
public static List<int[]> readCycleRanges() throws Exception {
List<int[]> cycleRanges = new ArrayList<>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
while (!(line == null || line.trim().length() == 0)) {
StringTokenizer st = new StringTokenizer(line, " ");
int i = Integer.valueOf(st.nextToken());
int j = Integer.valueOf(st.nextToken());
cycleRanges.add(new int[] { i, j, 0 });
line = br.readLine();
}
return cycleRanges;
}
I got it accepted by UVa judge. The problem was didn't considered that the second number can be smaller than the first number. You have to consider that case in which the second number is the starting of the series.

How to back up a line after a new line submitted by a user? Java

Suppose, you ask user to provide you some input via a console app in Java. They do and hit Enter. You get the string and do something in response. Say, you calculate some value based on the user's input and print it out.
How might I print out a response on the same line as user's input? I'd like to (possibly) delete a new line character and print out a response next to his input.
Please advise how to do this using Java.
Thank you.
You cannot control the Console through basic Java.I think you can use JLine to control the Console.In java 6 u have java.io.Console class through which you can echo asterisk *'s when password has to be read.
http://blogs.oracle.com/alanb/entry/java_io_console_is_finally
I have tried to implement this with the help of jcurses library and here is a demo of something you are looking for
import jcurses.system.CharColor;
import jcurses.system.InputChar;
import jcurses.system.Toolkit;
public class TestClass {
public static void main(String[] args) {
try {
CharColor printColor = new CharColor(CharColor.BLACK, CharColor.WHITE);
int i = 0;
int j = 0;
while (true) {
StringBuilder str = new StringBuilder();
InputChar c = null;
do {
c = Toolkit.readCharacter(); //Read each character
if (c.getCharacter() != 10) { //Do not print character if Return key
str.append(c);
Toolkit.printString(String.valueOf(c), i++, j, printColor); //Print character as you type
}
} while (c.getCharacter() != 10);
Toolkit.printString(processInput(str.toString()), i, j++, printColor);
i = 0;
if (j == Toolkit.getScreenHeight()) {
Toolkit.clearScreen(printColor);
j = 0;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String processInput(String input) {
return " Input processed";
}
}
You can with ANSI-Codes. In Linux I never had a problem to use them, but on Windows, you have to install ANSI.SYS first.
import java.util.Random;
public class AnsiMove
{
public AnsiMove ()
{
Random random = new Random ();
System.out.print ("ESC[2J");
for (int i = 0; i < 10000; ++i)
{
int y = random.nextInt (23) + 1;
int x = random.nextInt (79) + 1;
char c = (char) (random.nextInt (95) + 32);
gotoXY (x, y);
System.out.print (c);
pause (1);
}
}
void pause (int p)
{
try
{
Thread.sleep (p);
}
catch (InterruptedException e)
{
System.err.println (e);
}
}
void gotoXY (int x, int y)
{
System.out.print ("ESC[" + y + ';' + x + 'H');
}
/** */
public static void main (String args[])
{
new AnsiMove ();
}
}

StringIndexOutOfBoundsException

This program I'm making isn't compiling right, I keep getting the error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -9
at java.lang.String.charAt(String.java:687)
at pro1.main(pro1.java:161)
Here's my code:
import java.io.*;
import java.util.*;
public class pro1 {
static String str="";
static String str1="";
static int range=250;
static int length;
static String key="";
static String ep="";
static String pt="";
static char temp;
static int t,p,h;
static int r,x,y,z,w;
static Random generator = new Random();
static public String getContents(File aFile)
{
StringBuilder contents = new StringBuilder();
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null;
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
str1=contents.toString();
return str1;
}
public static void main (String args[]) throws IOException {
File testFile = new File("/home/amritha/Desktop/sam.txt");
System.out.println("Original file contents: " + getContents(testFile));
System.out.println("message:"+str1);
String sbox="abcdefghijklmnopqrstuvwxyz";
length=str1.length()-1;
for(int i=0;i<length;i++)
{
t=(int)str1.charAt(i);
if(t==32)
{
int t1=32;
temp=(char)t;
}
else
{
range=generator.nextInt(26)+1;
temp=sbox.charAt(range);
}
key+=""+temp;
}
System.out.println("Key:"+key);
for(int i=0;i<length;i++)
{
t=(int)str1.charAt(i);
{
if(t==32)
{
t=32;
temp=(char)t;
}
else
{
t-=97;
}
}
p=(int)key.charAt(i);
{
if(p==32)
{
p=32;
temp=(char)p;
}
else
{
p-=97;
}
}
if((t==32)&&(p==32))
{
int v=32;
temp=(char)v;
}
else
{
r=(t+p)%26;
temp=sbox.charAt(r);
}
ep+=""+temp;
}
System.out.println("Encrypted Text:"+ep);
for(int i=0;i<length;i++)
{
y=(int)ep.charAt(i);
{
if(y==32)
{
y=32;
temp=(char)y;
}
else
{
y-=97;
}
}
x=(int)key.charAt(i);
{
if(x==32)
{
x=32;
temp=(char)x;
}
else
{
x-=97;
}
}
if((x==32)&&(y==32))
{
int w=32;
temp=(char)w;
}
else
{
z=(y-x)%26;
temp=sbox.charAt(z);
}
pt+=""+temp;
}
System.out.println("deccrypted Text:"+pt);
}
}
Your code looks fishy in every way, and I cannot imagine anyone wanting to read 170 lines of this code.
Look at the exception: It tells you exactly what's going wrong: You pass -9 to charAt() as an index, which is - obviously - out of range, as you should only pass 0 ... (length-1) in there.
And it gives you the line number, too... so go to line number 161 and look what's in there and how it got there.
My guess would be it has something to do with this line:
z=(y-x)%26;
If x is larger than y the result of the % operation may be negative (or 0). And charAt (which is what z is given as parameter to) expects a positive value.
You should try:
z=Math.abs(y-x)%26;
Edit: As a side note, this shouldn't be to hard to figure out on your own, by looking at the exception as was pointed out by others, or in the worst case using a debugger and seeing exactly what values the different variables have and why when the exception occurs.

Categories

Resources