I have an arraylist of doubles that I update each time I iterate through an algorithm. I want to output the full list of numbers to a file but it as only outputting one value instead of the entire list. I use a simple simulated annealing local search. After each evaluation I store the new value in an array and I want to then output all values of the list to a file.
My code:
while (eval < 50) {
//Pick two positions on the grid
int Pos1 = (int) (Math.random() * size());
int Pos2 = (int) (Math.random() * size());
boolean swap = array1[Pos1];
array2[Pos1] = array1[Pos2];
array2[Pos2] = swap;
Fitness = evaluate(array2);
double current = fits[value];
System.out.println(eval + " " +Fitness);
list = Arrays.asList(Fitness);
//I WANT TO SAVE ALL VALUES IN THIS LIST TO A FILE
//Keep track of best solution by only replacing it if a better fitness
//value is found by the algorithm
if(Fitness <= current)
{
for(int i=0; i<grid.size();i++) {
individuals[value][i] = array2[i];
fits[value] = Fitness;
}
}
else {
//value for the current solution
double difference = Fitness - current;
double random = Math.random();
double prob = Math.exp(-(double)Math.abs(difference)/Temp);
if(prob > random)
{
for(int i=0; i<grid.size();i++) {
individuals[value][i] = array1[i];
fits[value] = current;
}
}
}
//Cool the system
Temp *= 1-coolingRate;
eval++;
}
Code that writes only one entry to file:
list = Arrays.asList(Fitness);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(FNAME))) {
for (Double line : list) {
bw.write(line + "\n");
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
Implementation used to write Array of doubles to file:
ArrayList<Double> yourArray = new ArrayList<>();
final String FILENAME = "sample.txt";
list.add(arrayValue)
try ( BufferedWriter bw = new BufferedWriter (new FileWriter (FILENAME)) )
{
for (Double line : yourArray) {
bw.write (line + "\n");
bw.newLine();
}
bw.close ();
} catch (IOException e) {
e.printStackTrace ();
}