Related
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package freewill_project;
import java.util.Arrays;
import javax.swing.JOptionPane;
/**
*
* #author ///
*/
public class Testing {
public static void main(String[] args) {
int batas = Integer.parseInt(JOptionPane.showInputDialog("Batas Siswa"));
String[] nama = new String[batas];
String mapel1, mapel2;
int nilai1[] = new int[batas];
int nilai2[] = new int[batas];
int total1 = 0, total2 = 0, Ttotal;
int kkm1, kkm2, k=0;
String[] tlulus1 = new String[nama.length];
String[] lulus1 = new String[nama.length];
String[] tlulus2 = new String[nama.length];
String[] lulus2 = new String[nama.length];
int jumlah = 0;
mapel1 = JOptionPane.showInputDialog("Masukan Mapel 1");
mapel2 = JOptionPane.showInputDialog("Masukan Mapel 2");
kkm1 = (Integer.parseInt(JOptionPane.showInputDialog("Input KKM 1")));
kkm2 = (Integer.parseInt(JOptionPane.showInputDialog("Input KKM 2")));
for (int i = 0; i < nama.length; i++) {
nama[i] = (JOptionPane.showInputDialog("Nama Siswa"));
nilai1[i] = Integer.parseInt(JOptionPane.showInputDialog("Input Nilai"));
total1 += nilai1[i];
if (nilai1[i] < kkm1) {
tlulus1[i] = nama[i];
} else {
nama[i] = lulus1[i];
}
nilai2[i] = Integer.parseInt(JOptionPane.showInputDialog("Input Nilai"));
total2 += nilai2[i];
if (nilai2[i] < kkm2) {
nama[i] = tlulus2[i];
} else {
nama[i] = lulus2[i];
}
}
Ttotal = total1 + total2;
int rata = Ttotal / 2;
int max1 = nilai1[0];
int min1 = nilai1[0];
int max2 = nilai2[0];
int min2 = nilai2[0];
for (int i = 0; i < 2; i++) { //for untuk output max, min, jumlah, rata arrays
if (max1 < nilai1[i]) {
max1 = nilai1[i];
} else if (min1 > nilai1[i]) {
min1 = nilai1[i];
}
if (max2 < nilai2[i]) {
max2 = nilai2[i];
} else if (min2 > nilai2[i]) {
min2 = nilai2[i];
}
}
System.out.println("Nilai Rata: " + rata + "\nNilai Tertinggi1: " + max1 + "\nNilai Terendah1: " + min2 + "\nNilai Tertinggi2: " + max2 + "\nNilai Terendah2: " + min2 + "\nSiswa Lulus1: " + Arrays.toString(lulus1) + "\nSiswa Tidak Lulus1: " + Arrays.toString(tlulus1) + "\nSiswa Lulus2: " + Arrays.toString(lulus2) + "\nSiswa Tidak Lulus2: " + Arrays.toString(tlulus2));
}
}
if the nilai is less than the kkm, then an element of the array in nama will be copied to tlulus, else an element in nama will be copied to lulus, however the output shows both lulus and tlulus as null
the output of lulus and tlulus should contain elements of nama, it showed up as null instead, I tried several fixes but then I get Arrays.outofbounds exception, any solution?
Your code
} else {
nama[i] = lulus1[i];
}
does not seem to match your specification:
else an element in nama will be copied to lulus
Shouldn't it rather be
} else {
lulus1[i] = nama[i];
}
?
Your code can lead to nama inputs being overwritten with null.
I have created a simple program that sorts integers in an input file using different algorithms. I also use filewriter to output results to another file. Unfortunately no matter how I change my code, file gets overridden. Any advice?
Been searching for answer on google and tried changing the way I input the syntax but nothing works.
important bits:
setting the writer up
try {
FileWriter fileWriter = new FileWriter ("Sorted output.txt");
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
outputting to the file
out.println("User's own data set sorted using bubble sort.");
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println("Sorted Array looks like this:" + Arrays.toString(intArrayBubble));
out.println(timeToSort + bubbleSortIs + bubbleTime + "ms");
it works fine, however its used in a do while loop, with nested if statements, and each one overrides the other.
Rest of code in case its required - UPDATED - still not working
import java.io.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
public class PDD_Sorting {
public static void main (String [] pArgs)
{
//Array for a file
String[] FileOne;
FileOne = new String[0];
int optionOne = 1,
optionTwo = 2,
optionThree = 3,
secondaryOptionOne = 1,
secondaryOptionTwo = 2,
secondaryOptionThree = 3,
userSelection,
subUserSelection;
String unsortedArray = "Unsorted array is: ",
bubbleSort = "Sorted array using bubble sort: ",
selectionSort = "Sorted array using selection sort: ",
insertionSort = "Sorted array using insertion sort: ",
timeToSort = "Time needed to sort this array using ",
bubbleSortIs = "bubble sort is ",
selectionSortIs = "selection sort is ",
insertionSortIs = "insertion sort is ",
welcomeToSorter = "Welcome to the SORTER - program that can sort your txt files containing integeres in an ascending order!",
notFiles = "Integers, not files :)",
pleaseSelect = "Please select one of the following options, by enetering a number asociated with it.",
optionOneUserInput = "1. Sort your own data set - input your own set of data (integers, separated by colons, no spaces) into the Input file.",
optionTwoPredefined = "2. Use predetermind set of data to test the algorythms.",
optionThreeExit = "3. Exit the program.",
subMenuPleaseSelect = "Please select which algorythm would you like to use to sort this file.",
optionBubble = "(1) - Bubble Sort.",
optionSelection = "(2) - Selection Sort.",
optionInsertion = "(3) - Insertion Sort.",
usersDataBubble = "User's own data set sorted using bubble sort.",
sortedArrayLooks = "Sorted Array looks like this:",
msTime = "ms",
usersDataSelection = "User's own data set sorted using selection sort.",
usersDataInsertion = "User's own data set sorted using insertion sort.",
validOption = "Please enter a valid option i.e. 1,2 or 3",
lessThanZero = "If time shown in ms is 0, that means the time needed to conduct the sort is shorter than 1ms.",
fileCreated = "File created.",
terminatingProgram = "Terminating the program.",
unableToWriteFile = "Unable to write to file";
System.out.println(welcomeToSorter);
System.out.println(notFiles);
Scanner tInput = new Scanner (System.in);
try {
FileWriter fileWriter = new FileWriter ("Sorted output.txt");
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
do {
System.out.println(pleaseSelect);
System.out.println(optionOneUserInput);
System.out.println(optionTwoPredefined);
System.out.println(optionThreeExit);
// Scanner tInput = new Scanner (System.in);
userSelection = tInput.nextInt();
if (userSelection == optionOne) {
//System.out.println("Please enter a valid path for your file.");
String[] splitFile = null;
//String userFile = tInput.next();
FileOne = getAndPrepareFile(splitFile);
System.out.println(subMenuPleaseSelect);
System.out.println(optionBubble);
System.out.println(optionSelection);
System.out.println(optionInsertion);
subUserSelection = tInput.nextInt();
if (subUserSelection == secondaryOptionOne) {
int size = FileOne.length;
int [] intArrayBubble = new int [size];
for(int i=0; i<size; i++) {
intArrayBubble[i] = Integer.parseInt(FileOne[i]);
}
bubbleSort(intArrayBubble);
long bubbleTime = timeCount(intArrayBubble);
out.println(usersDataBubble);
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println(sortedArrayLooks + Arrays.toString(intArrayBubble));
out.println(timeToSort + bubbleSortIs + bubbleTime + msTime);
}
else if (subUserSelection == secondaryOptionTwo) {
int size2 = FileOne.length;
int [] intArraySelection = new int [size2];
for(int i=0; i<size2; i++) {
intArraySelection[i] = Integer.parseInt(FileOne[i]);
}
doSelectionSort(intArraySelection);
long selectionTime = timeCount(intArraySelection);
out.println(usersDataSelection);
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println(sortedArrayLooks + Arrays.toString(intArraySelection));
out.println(timeToSort + selectionSortIs + selectionTime + msTime);
}
else if (subUserSelection == secondaryOptionThree) {
int size3 = FileOne.length;
int [] intArrayInsertion = new int [size3];
for(int i=0; i<size3; i++) {
intArrayInsertion[i] = Integer.parseInt(FileOne[i]);
}
doInsertionSort(intArrayInsertion);
long insertionTime = timeCount(intArrayInsertion);
out.println(usersDataInsertion);
out.println(unsortedArray + Arrays.deepToString(FileOne));
out.println(sortedArrayLooks + Arrays.toString(intArrayInsertion));
out.println(timeToSort + insertionSortIs + insertionTime + msTime);
}
else {
System.out.println(validOption);
tInput.next();
}
}
else if (userSelection == optionTwo){
//file being prepared and loaded via function
String[] splitFilePredefined = null;
FileOne = getAndPrepareFilePredefined(splitFilePredefined);
//converting string array into int array so the method can sort it.
int size = FileOne.length;
int [] intArrayBubble = new int [size];
for(int i=0; i<size; i++) {
intArrayBubble[i] = Integer.parseInt(FileOne[i]);
}
int size2 = FileOne.length;
int [] intArraySelection = new int [size2];
for(int i=0; i<size2; i++) {
intArraySelection[i] = Integer.parseInt(FileOne[i]);
}
int size3 = FileOne.length;
int [] intArrayInsertion = new int [size3];
for(int i=0; i<size3; i++) {
intArrayInsertion[i] = Integer.parseInt(FileOne[i]);
}
//inserting pre-prepared int arrays into variables including a timecount method
int bubbleTime = timeCount(intArrayBubble);
int selectionTime = timeCount(intArraySelection);
int insertionTime = timeCount(intArrayInsertion);
//sorting array using various sorts
bubbleSort(intArrayBubble);
doSelectionSort(intArraySelection);
doInsertionSort(intArrayInsertion);
//out.println("Sorted arrray using insertion sort looks like this: " + Arrays.toString(intArrayInsertion));
out.println(timeToSort + bubbleSortIs + bubbleTime + "ms");
out.println(timeToSort + selectionSortIs + selectionTime + "ms");
out.println(timeToSort + insertionSortIs + insertionTime + "ms");
out.println(lessThanZero);
System.out.println(fileCreated);
}
else if (userSelection == optionThree){
System.out.println(terminatingProgram);
System.exit(0);
}
else {
System.out.println(validOption);
tInput.next();
}
out.flush();
out.close();
//tInput.close();
}while (userSelection != optionThree);
}
catch (Exception e)
{
System.out.println(unableToWriteFile);
tInput.next();
}
tInput.close();
}//end main
//method that fetches the file from predefined, hardcoded location and removes comas, esentially prepares the file for the next phase
private static String[] getAndPrepareFile (String[] splitFile)
{
Scanner fileIn = null;
try
{
fileIn = new Scanner(new FileInputStream("C:\\Users\\Greg\\Documents\\Programming\\PDD - Assignment 1\\Input.txt"));
String fileNew = fileIn.next();
splitFile = fileNew.split(",");
//System.err.println(Arrays.toString(splitFile)); //Arrays.toString needed to print the array correctly, otherwise it prints the address of the object
fileIn.close();
}
catch (IOException e)
{
System.out.println("File not found.");
//System.exit(0);
}
return splitFile;
}
//as above but works for predefined file, that can be generated using randomNumber.java program
private static String[] getAndPrepareFilePredefined (String[] splitFilePredefined)
{
Scanner fileIn = null;
try
{
fileIn = new Scanner(new FileInputStream("C:\\Users\\Greg\\Documents\\Programming\\PDD - Assignment 1\\Generated input.txt"));
String fileNew = fileIn.next();
splitFilePredefined = fileNew.split(",");
//System.err.println(Arrays.toString(splitFile)); //Arrays.toString needed to print the array correctly, otherwise it prints the address of the object
fileIn.close();
}
catch (IOException e)
{
System.out.println("File not found.");
//System.exit(0);
}
return splitFilePredefined;
}
//method used to sort a file using bubble sort
private static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i=0; i < n; i++){
for(int j=1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
//method used to sort a file using selection sort
private static int[] doSelectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++)
if (arr[j] < arr[index])
index = j;
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
return arr;
}
//method used to sort a file using sinsertion sort
private static int[] doInsertionSort(int[] input){
int temp;
for (int i = 1; i < input.length; i++) {
for(int j = i ; j > 0 ; j--){
if(input[j] < input[j-1]){
temp = input[j];
input[j] = input[j-1];
input[j-1] = temp;
}
}
}
return input;
}
//method used to calculate how much time has lapsed while using any of the given sort methods, outputs in ms, if less than 1 ms, outputs 0ms
private static int timeCount (int[] anArray)
{
long start = System.nanoTime();
Arrays.sort(anArray);
long end = System.nanoTime();
long timeInMillis = TimeUnit.MILLISECONDS.convert(end - start, TimeUnit.NANOSECONDS);
//System.out.println("Time spend in ms: " + timeInMillis);
return (int) timeInMillis;
}
}//end class
File gets constantly overridden, how do i stop this and make it add to file instead?
You don't need the first FileWriter fileWriter = new FileWriter("Sorted output.txt");; this is actually creating/overwriting the file, after which your PrintWriter opens it again for appending.
So, just change
// ... omitting beginning
try {
FileWriter fileWriter = new FileWriter ("Sorted output.txt");
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
do {
// ... omitting rest
to
// ... omitting beginning
try {
//BufferedWriter bufferedWriter = new BufferedWriter (fileWriter);
PrintWriter out = new PrintWriter (new FileWriter("Sorted output.txt", true));
do {
// ... omitting rest
Move out.close() outside the loop
else {
System.out.println("Please enter a valid option i.e. 1,2 or 3");
tInput.next();
}
out.flush();
/* THIS -> out.close(); <- THIS */
//tInput.close();
}while (userSelection != optionThree);
out.close();
}
I tried your code and your problem is not that the file is being overwritten, but that you are closing the outputstream in the first iteration.
I've recently stumbled upon Tiny GP (A Genetic Programming program), and I found it pretty useful, so I decided to change all System.out.println() in the program to a write to text file method.
Problem: In the text file, for some reason, only says "PROBLEM SOLVED", instead of printing out generations and other things that it is supposed to (see code).
Tiny GP modified class file:
package main;
/*
* Program: tiny_gp.java
*
* Author: Riccardo Poli (email: rpoli#essex.ac.uk)
*
* Modified by Preston Tang
*/
import java.util.*;
import java.io.*;
import java.text.DecimalFormat;
public class tiny_gp {
String Name;
double[] fitness;
char[][] pop;
static Random rd = new Random();
static final int ADD = 110,
SUB = 111,
MUL = 112,
DIV = 113,
FSET_START = ADD,
FSET_END = DIV;
static double[] x = new double[FSET_START];
static double minrandom, maxrandom;
static char[] program;
static int PC;
static int varnumber, fitnesscases, randomnumber;
static double fbestpop = 0.0, favgpop = 0.0;
static long seed;
static double avg_len;
static final int MAX_LEN = 10000,
POPSIZE = 100000,
DEPTH = 5,
GENERATIONS = 100,
TSIZE = 2;
public static final double PMUT_PER_NODE = 0.05,
CROSSOVER_PROB = 0.9;
public static double[][] targets;
public double run() {
/* Interpreter */
char primitive = program[PC++];
if (primitive < FSET_START) {
return (x[primitive]);
}
switch (primitive) {
case ADD:
return (run() + run());
case SUB:
return (run() - run());
case MUL:
return (run() * run());
case DIV: {
double num = run(), den = run();
if (Math.abs(den) <= 0.001) {
return (num);
} else {
return (num / den);
}
}
}
return (0.0); // should never get here
}
public int traverse(char[] buffer, int buffercount) {
if (buffer[buffercount] < FSET_START) {
return (++buffercount);
}
switch (buffer[buffercount]) {
case ADD:
case SUB:
case MUL:
case DIV:
return (traverse(buffer, traverse(buffer, ++buffercount)));
}
return (0); // should never get here
}
public void setup_fitness(String fname) {
try {
int i, j;
String line;
BufferedReader in
= new BufferedReader(
new FileReader(fname));
line = in.readLine();
StringTokenizer tokens = new StringTokenizer(line);
varnumber = Integer.parseInt(tokens.nextToken().trim());
randomnumber = Integer.parseInt(tokens.nextToken().trim());
minrandom = Double.parseDouble(tokens.nextToken().trim());
maxrandom = Double.parseDouble(tokens.nextToken().trim());
fitnesscases = Integer.parseInt(tokens.nextToken().trim());
targets = new double[fitnesscases][varnumber + 1];
if (varnumber + randomnumber >= FSET_START) {
Write("too many variables and constants");
//System.out.println("too many variables and constants");
}
for (i = 0; i < fitnesscases; i++) {
line = in.readLine();
tokens = new StringTokenizer(line);
for (j = 0; j <= varnumber; j++) {
targets[i][j] = Double.parseDouble(tokens.nextToken().trim());
}
}
in.close();
} catch (FileNotFoundException e) {
Write("ERROR: Please provide a data file");
//System.out.println("ERROR: Please provide a data file");
System.exit(0);
} catch (Exception e) {
Write("ERROR: Incorrect data format");
//System.out.println("ERROR: Incorrect data format");
System.exit(0);
}
}
public double fitness_function(char[] Prog) {
int i = 0, len;
double result, fit = 0.0;
len = traverse(Prog, 0);
for (i = 0; i < fitnesscases; i++) {
for (int j = 0; j < varnumber; j++) {
x[j] = targets[i][j];
}
program = Prog;
PC = 0;
result = run();
fit += Math.abs(result - targets[i][varnumber]);
}
return (-fit);
}
public int grow(char[] buffer, int pos, int max, int depth) {
char prim = (char) rd.nextInt(2);
int one_child;
if (pos >= max) {
return (-1);
}
if (pos == 0) {
prim = 1;
}
if (prim == 0 || depth == 0) {
prim = (char) rd.nextInt(varnumber + randomnumber);
buffer[pos] = prim;
return (pos + 1);
} else {
prim = (char) (rd.nextInt(FSET_END - FSET_START + 1) + FSET_START);
switch (prim) {
case ADD:
case SUB:
case MUL:
case DIV:
buffer[pos] = prim;
one_child = grow(buffer, pos + 1, max, depth - 1);
if (one_child < 0) {
return (-1);
}
return (grow(buffer, one_child, max, depth - 1));
}
}
return (0); // should never get here
}
public int print_indiv(char[] buffer, int buffercounter) {
int a1 = 0, a2;
if (buffer[buffercounter] < FSET_START) {
if (buffer[buffercounter] < varnumber) {
Write("X" + (buffer[buffercounter] + 1) + " ");
//System.out.print("X" + (buffer[buffercounter] + 1) + " ");
} else {
WriteDouble(x[buffer[buffercounter]]);
//System.out.print(x[buffer[buffercounter]]);
}
return (++buffercounter);
}
switch (buffer[buffercounter]) {
case ADD:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" + ");
//System.out.print(" + ");
break;
case SUB:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" - ");
//System.out.print(" - ");
break;
case MUL:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" * ");
//System.out.print(" * ");
break;
case DIV:
Write("(");
//System.out.print("(");
a1 = print_indiv(buffer, ++buffercounter);
Write(" / ");
//System.out.print(" / ");
break;
}
a2 = print_indiv(buffer, a1);
Write(")");
//System.out.print(")");
return (a2);
}
public static char[] buffer = new char[MAX_LEN];
public char[] create_random_indiv(int depth) {
char[] ind;
int len;
len = grow(buffer, 0, MAX_LEN, depth);
while (len < 0) {
len = grow(buffer, 0, MAX_LEN, depth);
}
ind = new char[len];
System.arraycopy(buffer, 0, ind, 0, len);
return (ind);
}
public char[][] create_random_pop(int n, int depth, double[] fitness) {
char[][] pop = new char[n][];
int i;
for (i = 0; i < n; i++) {
pop[i] = create_random_indiv(depth);
fitness[i] = fitness_function(pop[i]);
}
return (pop);
}
public void stats(double[] fitness, char[][] pop, int gen) {
int i, best = rd.nextInt(POPSIZE);
int node_count = 0;
fbestpop = fitness[best];
favgpop = 0.0;
for (i = 0; i < POPSIZE; i++) {
node_count += traverse(pop[i], 0);
favgpop += fitness[i];
if (fitness[i] > fbestpop) {
best = i;
fbestpop = fitness[i];
}
}
avg_len = (double) node_count / POPSIZE;
favgpop /= POPSIZE;
Write("Generation=" + gen + " Avg Fitness=" + (-favgpop)
+ " Best Fitness=" + (-fbestpop) + " Avg Size=" + avg_len
+ "\nBest Individual: ");
//System.out.print("Generation=" + gen + " Avg Fitness=" + (-favgpop)
// + " Best Fitness=" + (-fbestpop) + " Avg Size=" + avg_len
// + "\nBest Individual: ");
print_indiv(pop[best], 0);
Write("\n");
//System.out.print("\n");
//System.out.flush();
}
public int tournament(double[] fitness, int tsize) {
int best = rd.nextInt(POPSIZE), i, competitor;
double fbest = -1.0e34;
for (i = 0; i < tsize; i++) {
competitor = rd.nextInt(POPSIZE);
if (fitness[competitor] > fbest) {
fbest = fitness[competitor];
best = competitor;
}
}
return (best);
}
public int negative_tournament(double[] fitness, int tsize) {
int worst = rd.nextInt(POPSIZE), i, competitor;
double fworst = 1e34;
for (i = 0; i < tsize; i++) {
competitor = rd.nextInt(POPSIZE);
if (fitness[competitor] < fworst) {
fworst = fitness[competitor];
worst = competitor;
}
}
return (worst);
}
public char[] crossover(char[] parent1, char[] parent2) {
int xo1start, xo1end, xo2start, xo2end;
char[] offspring;
int len1 = traverse(parent1, 0);
int len2 = traverse(parent2, 0);
int lenoff;
xo1start = rd.nextInt(len1);
xo1end = traverse(parent1, xo1start);
xo2start = rd.nextInt(len2);
xo2end = traverse(parent2, xo2start);
lenoff = xo1start + (xo2end - xo2start) + (len1 - xo1end);
offspring = new char[lenoff];
System.arraycopy(parent1, 0, offspring, 0, xo1start);
System.arraycopy(parent2, xo2start, offspring, xo1start,
(xo2end - xo2start));
System.arraycopy(parent1, xo1end, offspring,
xo1start + (xo2end - xo2start),
(len1 - xo1end));
return (offspring);
}
public char[] mutation(char[] parent, double pmut) {
int len = traverse(parent, 0), i;
int mutsite;
char[] parentcopy = new char[len];
System.arraycopy(parent, 0, parentcopy, 0, len);
for (i = 0; i < len; i++) {
if (rd.nextDouble() < pmut) {
mutsite = i;
if (parentcopy[mutsite] < FSET_START) {
parentcopy[mutsite] = (char) rd.nextInt(varnumber + randomnumber);
} else {
switch (parentcopy[mutsite]) {
case ADD:
case SUB:
case MUL:
case DIV:
parentcopy[mutsite]
= (char) (rd.nextInt(FSET_END - FSET_START + 1)
+ FSET_START);
}
}
}
}
return (parentcopy);
}
public void print_parms() {
Write("-- TINY GP (Java version) --\n");
//System.out.print("-- TINY GP (Java version) --\n");
Write("SEED=" + seed + "\nMAX_LEN=" + MAX_LEN
+ "\nPOPSIZE=" + POPSIZE + "\nDEPTH=" + DEPTH
+ "\nCROSSOVER_PROB=" + CROSSOVER_PROB
+ "\nPMUT_PER_NODE=" + PMUT_PER_NODE
+ "\nMIN_RANDOM=" + minrandom
+ "\nMAX_RANDOM=" + maxrandom
+ "\nGENERATIONS=" + GENERATIONS
+ "\nTSIZE=" + TSIZE
+ "\n----------------------------------\n");
// System.out.print("SEED=" + seed + "\nMAX_LEN=" + MAX_LEN
// + "\nPOPSIZE=" + POPSIZE + "\nDEPTH=" + DEPTH
// + "\nCROSSOVER_PROB=" + CROSSOVER_PROB
// + "\nPMUT_PER_NODE=" + PMUT_PER_NODE
// + "\nMIN_RANDOM=" + minrandom
// + "\nMAX_RANDOM=" + maxrandom
// + "\nGENERATIONS=" + GENERATIONS
// + "\nTSIZE=" + TSIZE
// + "\n----------------------------------\n");
}
public tiny_gp(String fname, long s) {
fitness = new double[POPSIZE];
seed = s;
if (seed >= 0) {
rd.setSeed(seed);
}
setup_fitness(fname);
for (int i = 0; i < FSET_START; i++) {
x[i] = (maxrandom - minrandom) * rd.nextDouble() + minrandom;
}
pop = create_random_pop(POPSIZE, DEPTH, fitness);
}
public void evolve() {
int gen = 0, indivs, offspring, parent1, parent2, parent;
double newfit;
char[] newind;
print_parms();
stats(fitness, pop, 0);
for (gen = 1; gen < GENERATIONS; gen++) {
if (fbestpop > -1e-5) {
Write("PROBLEM SOLVED\n");
//System.out.print("PROBLEM SOLVED\n");
System.exit(0);
}
for (indivs = 0; indivs < POPSIZE; indivs++) {
if (rd.nextDouble() < CROSSOVER_PROB) {
parent1 = tournament(fitness, TSIZE);
parent2 = tournament(fitness, TSIZE);
newind = crossover(pop[parent1], pop[parent2]);
} else {
parent = tournament(fitness, TSIZE);
newind = mutation(pop[parent], PMUT_PER_NODE);
}
newfit = fitness_function(newind);
offspring = negative_tournament(fitness, TSIZE);
pop[offspring] = newind;
fitness[offspring] = newfit;
}
stats(fitness, pop, gen);
}
Write("PROBLEM *NOT* SOLVED\n");
//System.out.print("PROBLEM *NOT* SOLVED\n");
System.exit(1);
}
public void Write(String context) {
FileWriter fileWriter;
try {
fileWriter = new FileWriter("GP.txt");
try (BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
bufferedWriter.write(context);
}
} catch (IOException ex) {
}
}
public void WriteDouble(double context) {
FileWriter fileWriter;
try {
fileWriter = new FileWriter("GP.txt");
try (BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) {
String ncontext = Double.toString(context);
bufferedWriter.write(ncontext);
}
} catch (IOException ex) {
}
}
};
The Functions Mapper file that uses the Tiny GP class file:
package function_mapper;
import javax.swing.JOptionPane;
import main.*;
public class Function_Mapper {
public static void main(String[] args) {
String fname = JOptionPane.showInputDialog(null, "File Name", "Input Dialog", JOptionPane.INFORMATION_MESSAGE);
long s = -1;
if (args.length == 2) {
s = Integer.valueOf(args[0]).intValue();
fname = args[1];
}
if (args.length == 1) {
fname = args[0];
}
tiny_gp gp = new tiny_gp(fname, s);
gp.evolve();
}
}
Much help appreciated, thanks!
The Write method overwrites the contents of the file on each invocation. There are two ways to fix this.
An easier one, is to append file, instead of overwriting it. It could be achieved by passing append argument to the FileWriter (I simplified code a little bit along the way).
// true on the next line means "append"
try (Writer writer = new FileWriter("GP.txt", true)) {
writer.write(Double.toString(context));
} catch (IOException ex) {
}
A harder, but much fore efficient one is to openwriter in the constructor, use it in Write method, and close in the specially introduced close method of the tiny_gp.
I have a need to display large text files. Display text without the need to scroll as an e-book. I can break a long text on the page, but it takes me too much time. For example - the following code handles 1.4 MB of text for about 10-15 seconds.
public void split(TextPaint textPaint, String filepath,Context context) {
int pages = 0;
File file = new File(filepath);
char[] bufferChar = new char[1024];
String uncompletedtext="";
//How lines we can show
int maxLinesOnpage = 0;
StaticLayout staticLayout = new StaticLayout(
context.getString(R.string.lorem_ipsum),
textPaint,
pageWidth,
Layout.Alignment.ALIGN_NORMAL,
lineSpacingMultiplier,
lineSpacingExtra,
false
);
int startLineTop = staticLayout.getLineTop(0);
int endLine = staticLayout.getLineForVertical(startLineTop + pageHeight);
int endLineBottom = staticLayout.getLineBottom(endLine);
if (endLineBottom > startLineTop + pageHeight) {
maxLinesOnpage = endLine - 1;
} else {
maxLinesOnpage = endLine;
}
//let's paginate
try {
BufferedReader buffer = new BufferedReader(new FileReader(file));
while (buffer.read(bufferChar)>=0) {
uncompletedtext += new String(bufferChar);
boolean allcomplete = false;
staticLayout = new StaticLayout(
uncompletedtext,
textPaint,
pageWidth,
Layout.Alignment.ALIGN_NORMAL,
lineSpacingMultiplier,
lineSpacingExtra,
false
);
staticLayout.getLineCount();
int curTextPages= (int) Math.floor(staticLayout.getLineCount() / maxLinesOnpage);
uncompletedtext=uncompletedtext.substring(staticLayout.getLineEnd(curTextPages));
pages+=curTextPages;
Log.e("PAGES","" + pages);
}
} catch (Exception e) {
e.printStackTrace();
}
Log.e("FILE READED FULLY!!", "READ COMPLETE!!!!!!!!!!!!!!!!");
}
It is too long. I can not understand how applications such as FBReader and СoolReader handle large files (More than 9 MB) instantly.
I saw the source of the applications, but they have too much functionality to quickly find answer.
I really need help and tips. Thanks.
Thanks to all! I find solution! Not elegant but very fast code (10Mb ~ 600 ms)
public void split(TextPaint textPaint, String filepath,Context context) {
File file = new File(filepath);
char[] bufferChar = new char[512];
//How lines on page
int maxLinesOnpage = 0;
int symbolsOnLine = 0;
StaticLayout staticLayout = new StaticLayout(
context.getString(R.string.lorem_ipsum),//short text with 100 lines (\r\n\r\n\r\n\r\n\r\n\r\n)
textPaint, //MONOSPACE!!!
pageWidth,
Layout.Alignment.ALIGN_NORMAL,
lineSpacingMultiplier,
lineSpacingExtra,
false
);
int startLineTop = staticLayout.getLineTop(0);
int endLine = staticLayout.getLineForVertical(startLineTop + pageHeight);
int endLineBottom = staticLayout.getLineBottom(endLine);
if (endLineBottom > startLineTop + pageHeight) {
maxLinesOnpage = endLine - 1;
} else {
maxLinesOnpage = endLine;
}
symbolsOnLine = staticLayout.getLineEnd(0);
try {
RandomAccessFile rac = new RandomAccessFile(file, "r");
byte[] buffer = new byte[2048];
int wordLen = 0; //Length of word in symbols
int wordInBytes = 0; //Lenght of word
int startLinePos = 0; //Start first line position
int lineWidth = 0; //Current line length
int totalLines =0; //Total lines on current page
Log.e("Start pagination", "" + totalLines);
long timeout= System.currentTimeMillis();
int buflen=0; //buffer size
int totalReadedBytes = 0; //Total bytes readed
byte skipBytes = 0;
while ( (buflen=rac.read(buffer))!=-1){
for (int i=0;i<buflen;i++) {
totalReadedBytes++;
wordInBytes++;
if (skipBytes==0){ //Bytes on one symbol
if (unsignedToBytes(buffer[i])>=192){skipBytes=2;}
if (unsignedToBytes(buffer[i])>=224){skipBytes=3;}
if (unsignedToBytes(buffer[i])>=240){skipBytes=4;}
if (unsignedToBytes(buffer[i])>=248){skipBytes=5;}
if (unsignedToBytes(buffer[i])>=252){skipBytes=6;}
}
//Full bytes on symbol or not
if (skipBytes>0){
skipBytes--;
if (skipBytes>0){continue;}
}
if (buffer[i] == 13) {//We have a \r symbol. Ignore.
continue;
}
if (buffer[i]==10){//New line symbol
if (lineWidth + wordLen>symbolsOnLine){
totalLines++;
if (totalLines > maxLinesOnpage) {
int[] pgsbytes = {startLinePos, totalReadedBytes};
pages.add(pgsbytes);
startLinePos = totalReadedBytes ;
totalLines = 0;
}
}
wordLen=0;
wordInBytes=0;
totalLines++;
lineWidth=0;
if (totalLines>maxLinesOnpage){
int[] pgsbytes = {startLinePos, totalReadedBytes-1};
pages.add(pgsbytes);
startLinePos = totalReadedBytes-1;
totalLines=0;
}
}
if (buffer[i]==32){//Space symbol
if (lineWidth + wordLen+1<=symbolsOnLine){//Word fits in line
lineWidth+=wordLen + 1;
wordLen=0;
if (lineWidth==symbolsOnLine){
totalLines++;
if (totalLines > maxLinesOnpage) {
int[] pgsbytes = {startLinePos, totalReadedBytes};
pages.add(pgsbytes);
startLinePos = totalReadedBytes ;
totalLines = 0;
}
lineWidth = 0;
wordLen = 0;
wordInBytes=0;
}
} else {
if (lineWidth + wordLen==symbolsOnLine){
totalLines++;
if (totalLines > maxLinesOnpage) {
int[] pgsbytes = {startLinePos, totalReadedBytes};
pages.add(pgsbytes);
startLinePos = totalReadedBytes ;
totalLines = 0;
}
lineWidth = 0;
wordLen = 0;
wordInBytes=0;
} else {
totalLines++;
if (totalLines > maxLinesOnpage) {
int[] pgsbytes = {startLinePos, totalReadedBytes - 1 - wordInBytes};
pages.add(pgsbytes);
startLinePos = totalReadedBytes - 1;
totalLines = 0;
}
lineWidth = wordLen + 1;
wordLen = 0;
wordInBytes=0;
}
}
}
if (buffer[i]!=32&&buffer[i]!=10&&buffer[i]!=13){wordLen++; }
if (wordLen==symbolsOnLine){
totalLines++;
if (totalLines>maxLinesOnpage){
int[] pgsbytes = {startLinePos, totalReadedBytes-1 - wordInBytes};
pages.add(pgsbytes);
startLinePos = totalReadedBytes-1;
totalLines=0;
}
lineWidth=0;
wordLen=0;
wordInBytes=0;
}
}
}
rac.close();
timeout = System.currentTimeMillis() - timeout;
Log.e("TOTAL Time", " time " + timeout + "ms");
} catch (Exception e) {
e.printStackTrace();
}
Log.e("FILE READED FULLY!!", "READ COMPLETE!!!!!!!!!!!!!!!!");
}
So I'm working on a project for school. I need to record the data from my arrays into Excel and I'm having some trouble. This is part of my experiment class.
public static void exp(Params params) {
Scanner s = new Scanner(System.in);
String temp;
for (temp = ""; temp.isEmpty(); temp = s.nextLine()) {
System.out.println("Enter a directory and filename that you want the results to be saved under.");
System.out.println("(If no directory is specified, results will be in same folder as the jar.)");
}
params.setFileName(temp);
s.close();
System.out.println("Executing...");
long timeArray[] = new long[params.getFinalSize() / params.getIncrement()];
int counter = 0;
SortFacade facade = new SortFacade();
for (int n = params.getInitialSize(); n <= params.getFinalSize(); n += params.getIncrement()) {
System.out.println((new StringBuilder("Array of size: ")).append(n).toString());
long tempTime = 0L;
for (int j = 0; j < params.getNumTrials(); j++) {
System.out.println((new StringBuilder("Trial #")).append(j + 1).toString());
params.generateArrays(n, params.getTypeList());
tempTime += facade.sort(params);
}
timeArray[counter] = tempTime / (long) params.getNumTrials();
counter++;
}
params.setTimeArray(timeArray);
System.out.println("Times for each array size(ms): " + Arrays.toString(timeArray));
System.out.println("Writing to File...");
System.out.println("Complete.");
}
}
Start with Filewriter
Make sure what you write is comma-delimeted and saved as a .csv
Also, take a look at this existing question.