What I need to do is to implement the 0-1 Knapsack problem. There is an input file named "In0302.txt" and an output file named "Out0302.txt". The program gets values from INPUT file and saves the results to OUTPUT file. I got my input values on paper from my "dr".
Putting them to the file seems to be ok in OUTPUT file. But... on classes "dr" tried to put other values in INPUT file, but the program didn't work. What is more there was no even an error, but the program was still compiling and compiling... and I can't get know where the problem is. Does anybody would try to change something in this code or tell me what is wrong ?
INPUT:
4 6
2 1
3 2
3 4
4 5
OUTPUT:
1 4
2 3
JAVA CODE:
public class Knapsack {
public static int max(int a, int b){
if (a > b){
return a;
}
else{
return b;
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args){
int n = 0, W = 0, p[] = null, w[] = null, S[][] = null, S_object[][] = null;
//s[][] = arrays with values
try {
FileReader fr = new FileReader("In0302.txt");
BufferedReader in = new BufferedReader(fr);
String line = in.readLine();
String[] cols = line.split(" ");
n = Integer.parseInt(cols[0]); W = Integer.parseInt(cols[1]);
p = new int[n+1]; w = new int[n+1];
int k = 1;
while ((line = in.readLine()) != null) {
cols = line.split(" ");
p[k] = Integer.parseInt(cols[0]);
w[k] = Integer.parseInt(cols[1]);
k++;
}
S = new int[W+1][n+1];
S_object = new int[W+1][n+1];
for(int weight = 0; weight <= W; weight++){
for(int i = 0; i <= n; i++){
if (i == 0){
S[weight][i] = 0;
S_object[weight][i] = 0;
}
else if (weight < w[i]){
S[weight][i] = S[weight][i-1];
S_object[weight][i] = S_object[weight][i-1];
}
else if (weight >= w[i-1]){
S[weight][i]=max(S[weight][i-1],S[weight-w[i]][i-1]+p[i]);
if ((max(S[weight][i-1], S[weight-w[i]][i-1] + p[i]) == (S[weight-w[i]][i-1] + p[i]))) {
S_object[weight][i]=i;
} //added new element to bag
else {
S_object[weight][i]=S_object[weight][i-1];
} //nothing has been added
}
}
}
in.close();
fr.close();
}
catch (IOException e){
System.out.println("Error: " + e.toString());
}
File outputFile;
FileWriter out;
try{
outputFile = new File("Out0302.txt");
out = new FileWriter(outputFile);
String line = "";
int max_value = S[W][n];
for (int m = n; m > 0; m--){
if (S[W][m] == max_value){
line = " " + S_object[W][m] + "";
int temp = W;
while ((temp-w[S_object[temp][m]]) > 0){
temp = temp - w[S_object[temp][m]];
line += " " + S_object[temp][m];
}
out.write(line + "\n");
out.write("\n\t");
}
}
out.close();
}
catch (IOException e) {
System.out.println("Error: " + e.toString());
}
System.out.println("Arrar of values:");
for(int weight = 0; weight <= W; weight++){
for(int i = 0; i <= n; i++){
System.out.print(S[weight][i] + " ");
}
System.out.println("");
}
System.out.println("Array of objects:");
for(int weight = 0; weight <= W; weight++){
for(int i = 0; i <= n; i++){
System.out.print(S_object[weight][i] + " ");
}
System.out.println("");
}
}
}
Related
I have a program that reads input from two text files:
answersA.txt
10
US Independence
French Revolution
WW I
Great Depression
WW II
Korean War
British Invasion
Vietnam War
Gulf War
Dot Com Era
myanswers1.txt
7
Korean War
British Invasion
WW I
Vietnam War
Great Depression
US Independence
French Revolution
The first line is the how many values there will be. I'm trying to find the longest pattern between the two files. For these cases, the longest pattern is "Korean War,British Invasion,Vietnam War" and the score from the grade() method would be 5, since there were 5 answers right. I'm trying to use the dynamic programming approach, and although I can figure out how to do this for a singular string, I am struggling to figure out how to do it for an array of strings (if that's even the best way to handle it).
import java.util.*;
import java.io.*;
import java.util.stream.Collectors;
public class Patterns {
public int grade;
public String LHP;
String[] answers = null;
String[] myAnswers = null;
public Patterns(String filename) {
List<String> readAnswers = new ArrayList<String>();
try {
FileInputStream newFile = new FileInputStream(filename);
DataInputStream data_input = new DataInputStream(newFile);
BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input));
String line;
while ((line = buffer.readLine()) != null) {
line = line.trim();
if ((line.length() != 0)) {
readAnswers.add(line);
}
}
buffer.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
System.out.println(readAnswers);
answers = new String[readAnswers.size()];
answers = readAnswers.toArray(answers);
}
public int grade(String filename) {
List<String> readMyAnswers = new ArrayList<String>();
try {
FileInputStream newFile = new FileInputStream(filename);
DataInputStream data_input = new DataInputStream(newFile);
BufferedReader buffer = new BufferedReader(new InputStreamReader(data_input));
String line;
while ((line = buffer.readLine()) != null) {
if ((line.length() != 0)) {
readMyAnswers.add(line);
}
}
buffer.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
System.out.println(readMyAnswers);
myAnswers = new String[readMyAnswers.size()];
myAnswers = readMyAnswers.toArray(myAnswers);
grade = LCS(answers, myAnswers);
return grade;
}
public String pattern(String filename) {
return LHP;
}
public static int LCS(String[] A, String[] B) {
int[][] LCS = new int[A.length + 1][B.length + 1];
String[][] solution = new String[A.length + 1][B.length + 1];
for (int i = 0; i <= B.length; i++) {
LCS[0][i] = 0;
solution[0][i] = "0";
}
for (int i = 0; i <= A.length; i++) {
LCS[i][0] = 0;
solution[i][0] = "0";
}
for (int i = 1; i <= A.length; i++) {
for (int j = 1; j <= B.length; j++) {
if (A[i - 1] == B[j - 1]) {
LCS[i][j] = LCS[i - 1][j - 1] + 1;
} else {
LCS[i][j] = Math.max(LCS[i - 1][j], LCS[i][j - 1]);
}
}
}
return LCS[A.length][B.length];
}
public static void main(String[] args) {
Patterns test1 = new Patterns("answersA.txt");
System.out.println("The score is: " + test1.grade("myanswers1.txt"));
}
}
Hi for my HW I am suppose to read a text file of '.' and 'x' representing cells in Conway's Game of Life. I'm having trouble with reading the given text input and adding it into my double integer arrays. Specifically the rowcounter and columncounter part I'm sure there is a better way to do it but when I tried for loops it only read one row. I included previous parts of the code just in case. Thanks.
// Initiate file
File inputfile = new File(inputfilename);
try {
input = new Scanner(inputfile);
} catch (Exception ie) {
}
// Get array size
int[] arraysize = new int[2];
while (input.hasNextInt()) {
for (int i = 0; i < 2; i++) {
int token = input.nextInt();
arraysize[i] = token;
}
}
//System.out.println(Arrays.toString(arraysize));
// Create Array
int[][] newarray = new int[arraysize[0]][arraysize[1]];
//System.out.println(Arrays.deepToString(newarray));
// Read initial
int rowcounter = 0;
int columncounter = 0;
while (input.hasNextLine()) {
Scanner inputtoken = new Scanner(input.nextLine());
while (inputtoken.hasNext()) {
String token = inputtoken.next();
//System.out.print(token);
char xchar = token.charAt(0);
if (xchar == 'x') {
newarray[rowcounter][columncounter] = 1;
} else {
newarray[rowcounter][columncounter] = 0;
//System.out.print(rowcounter);
}
columncounter = columncounter + 1;
//System.out.print(columncounter);
}
columncounter = 0;
System.out.println();
rowcounter = rowcounter + 1;
//System.out.print(rowcounter);
}
System.out.println(Arrays.deepToString(newarray));
I have tried to write a Java program that count number of words start with UpperCase in each line separately, like in a txt file, and print the line number next to the number of words start with UpperCase in that line.
I have only come out with how to count the number for a single line using:
Scanner in = new Scanner(System.in);
String s = new String();
System.out.println("Enter a line:");
s = " " + in .nextLine();
char ch;
int count = 0;
for (int i = 1; i < s.length(); i++) {
ch = s.charAt(i);
if (Character.isUpperCase(ch) && (i == 0 || Character.isWhitespace(s.charAt(i - 1)))) {
count++;
}
}
System.out.println("total number of words start with capital letters are :" + count);
I tried to do it on the way I want, but it keep showing me "File is empty":
FileInputStream in = new FileInputStream("io-02.txt");
Scanner inScanner = new Scanner(in);
FileOutputStream out = new FileOutputStream("io-02-out.txt");
PrintWriter pwr = new PrintWriter(out);
int linenumb=0;
String s="";
char c;
int count = 0;
inScanner.useDelimiter("");
for (int i = 1; i < s.length(); i++) {
s = " " + inScanner.nextLine().trim();
c = s.charAt(i);
if (Character.isUpperCase(c) && (i == 0 || Character.isWhitespace(s.charAt(i - 1)))) {
count++;
} else if(s == "\n"){
if(linenumb == 0)
pwr.printf("%6s%35s%n", "Line#", "Number of Uppercase characters");
linenumb++;
pwr.printf("%5d.%35d%n", linenumb, count);
count = 0;
}
}
if(linenumb == 0)
System.out.println("Error: The input file is empty");
else{
linenumb++;
pwr.printf("%5d.%35d%n", linenumb, count);
System.out.println("The file output.txt has been created . . . ");
}
Please help.
Java 8 solution:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
final public class UppercaseWordCounter { // https://stackoverflow.com/questions/49193228/counting-number-of-words-start-with-uppercase-letter-in-strings-java
final private static File FILE_WORDS = new File("io-02.txt");
final private static File FILE_RESULTS = new File("io-02-out.txt");
public static void main(final String[] args) {
if (!FILE_WORDS.exists()) {
System.err.println("Input file does not exist: " + FILE_WORDS);
System.exit(1);
}
if (FILE_RESULTS.exists()) {
if (!FILE_RESULTS.delete()) {
System.err.println("Intended output file exists already and can't be deleted: " + FILE_RESULTS);
System.exit(2);
}
}
try (final BufferedReader br = Files.newBufferedReader(FILE_WORDS.toPath(), StandardCharsets.UTF_8);
final BufferedWriter bw = Files.newBufferedWriter(FILE_RESULTS.toPath(), StandardCharsets.UTF_8)) {
int lineCounter = 1;
String line;
while ((line = br.readLine()) != null) {
final int upperCaseWordsInThisLine = countUpperCaseWords(line);
bw.write("Line " + lineCounter + " has " + upperCaseWordsInThisLine + " upper case word" + (upperCaseWordsInThisLine == 1 ? "" : "s") + ".\n");
lineCounter++;
}
} catch (Exception e) {
e.printStackTrace();
}
System.exit(0);
}
private static int countUpperCaseWords(final String line) {
int ret = 0;
final int length = line.length();
boolean newWord = true;
for (int i = 0; i < length; i++) {
final char c = line.charAt(i);
if (" .,;/".indexOf(c) >= 0) {
newWord = true;
} else if (newWord) {
newWord = false;
if (Character.isUpperCase(c)) {
ret++;
}
}
}
return ret;
}
}
Why don't you use a method from Files class, which is available from java 1.7
List<String> lst = Files.readAllLines(Path path, Charset cs)
then you can loop over the lst List checking your condition
So I'm trying to read in a string from a file. However, I want each string to contain exactly 64 characters or less if the last string doesn't have 64 in it. So essentially I have a counter, when that counter reaches 64, I set the array of characters to a string, go to the next row and reset the count to zero. However I'm not getting output of any kind when I run it. Any help is appreciated. Here is a snippet of my code
public static void main(String[] args) throws IOException{
File input = null;
if (1 < args.length) {
input = new File(args[1]);
}
else {
System.err.println("Invalid arguments count:" + args.length);
System.exit(0);
}
String key = args[0];
BufferedReader reader = null;
int len;
Scanner scan = new Scanner(System.in);
System.out.println("How many lines in the file?");
if(scan.hasNextInt()){
len = scan.nextInt();
}
else{
System.out.println("Please enter an integer: ");
scan.next();
len = scan.nextInt();
}
scan.close();
String[] inputText = new String[2 * len];
String[] encryptText = new String[2 * len];
char[][] inputCharArr = new char[2 * len][64];
reader = new BufferedReader(new FileReader(input));
int r;
int counter = 0;
int row = 0;
while ((r = reader.read()) != -1) {
char ch = (char) r;
if(counter == 64){
String temp = new String(inputCharArr[row]);
inputText[row] = temp;
encryptText[row] = inputText[row];
System.out.println(inputText[row]);
row++;
counter = 0;
}
if(row == len){
break;
}
inputCharArr[row][counter] = ch;
counter++;
}
Edit: Is this close?
CharBuffer cbuf = CharBuffer.allocate(64);
int counter = 0;
while (reader.read(cbuf) != -1) {
inputText[counter] = cbuf.toString();
encryptText[counter] = inputText[counter];
counter++;
cbuf.clear();
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to print 2D Array from .txt file in Java
text file is:
8.00 28.00
18.00 28.00
8.00 23.00
12.00 20.00
15.00 30.00
... etc (many more lines)
i am reached upto:
public class Asgn2backup {
public static double[][] matrix;
public static void main(final String[] args) throws IOException {
System.out.print("Enter the name of the file: ");
final String fileName = readInput();
final BufferedReader br = new BufferedReader(
new FileReader(fileName + ".txt"));
String line;
int order = 0;
int rowIndex = 0;
int counter = 0;
while ((line = br.readLine()) != null) {
counter++;
if (counter == 1) {
order = Integer.parseInt(line);
matrix = new double[order][order];
System.out.println("order: " + order);
}
if (counter == 2) {
final String source = line;
System.out.println("source: " + source);
}
if (counter != 2 && counter != 1) {
order = Integer.parseInt(line);
matrix = new double[order][order];
System.out.println("order: " + order);
final StringTokenizer theLine =
new StringTokenizer(line, ", ");
int colIndex = 0;
while (theLine.hasMoreTokens()) {
final String st = theLine.nextToken();// .trim();
matrix[rowIndex][colIndex] = Double.parseDouble(st);
colIndex = colIndex + 1;
}
rowIndex = rowIndex + 1;
}
}
for (int x = 0; x < matrix.length - 1; x++) {
for (int p = 0; p < matrix.length - 1; p++) {
System.out.print(matrix[x][p] + " ");
}
}
br.close();
}
private static String readInput() {
try {
final BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
return in.readLine();
} catch (final IOException e) {
}
return "";
}
}
but it gives numberformatexception runtime error.
give me complete solution.
pls help me.
The parser does not fit the input file at all. In each condition you try to parse the entire line as a single integer value. This will cause NumberFormatExceptions.
Example:
if (counter != 2 && counter != 1) {
order = Integer.parseInt(line); // line = "8.00 23.00" < not an integer
The lines contain float or double values. So you'll have to split the line around multiple whitespaces and parse the two fragments with Double.parseDouble(split[<0|1>]) to double values.