Я пытаюсь решить проблему минимального покрытия вершин, используя два алгоритма аппроксимации, и у меня есть кадры в моем проекте. Я использовал SwingWorker, потому что время выполнения может быть долгим, но оно не заканчивается sh, поэтому я могу записать результат, в то время как когда я запускаю ту же функцию без фреймов и работника Swing, программа печатает результаты.
Вот swingWorkerClass, одна из функций, где вызывается swingWorker, и функции, которые вызываются внутри doInBackground () в swingWorker.
package advancedalgorithmstask1;
import java.util.List;
import java.util.Set;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
/**
*
* @author Siba
*/
public class VertexCoverSwingWorker extends SwingWorker<Set<Integer>, String>{
private String fileName;
private vertexCoverAlg algorithmName;
private final JTextArea textArea;
public VertexCoverSwingWorker(String fileName, vertexCoverAlg algorithmName, JTextArea textArea) {
this.fileName = fileName;
this.algorithmName = algorithmName;
this.textArea = textArea;
}
@Override
protected Set<Integer> doInBackground() throws Exception {
if(algorithmName.equals(vertexCoverAlg.LP)){
return AdvancedAlgorithmsTask1.minVertexCoverLP(fileName,this);
}
else{
return AdvancedAlgorithmsTask1.minVertexCover2Approx(fileName,this);
}
}
protected void process(final List<String> chunks) {
// Updates the messages text area
for (final String string : chunks) {
textArea.append(string);
}
}
public void publishData(String text){
publish(text);
}
public void publishDataLn(String text){
publish(text);
publish("\n");
}
private static void failIfInterrupted() throws InterruptedException {
if (Thread.currentThread().isInterrupted()) {
throw new InterruptedException("Interrupted while searching files");
}
}
}
private void twoApproxButtonActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
if(selectedFilePath.equals("")){
JOptionPane.showMessageDialog(this,"Please select a dataset file first!");
return;
}
ResultFrame resultFrame=new ResultFrame();
resultFrame.setVisible(true);
VertexCoverSwingWorker worker=new VertexCoverSwingWorker(selectedFilePath, vertexCoverAlg.twoApprox, resultFrame.getResultsTextAreaElement());
long startTime=System.nanoTime();
worker.execute();
if(worker.isDone()){
try {
long endTime=System.nanoTime();
Set<Integer> result=new HashSet<>();
Graph.copyContentOfSet2ToSet1(result, worker.get());
AdvancedAlgorithmsTask1.printSolution(result,worker);
AdvancedAlgorithmsTask1.printSolution(result);
long duration=(endTime-startTime)/1000000000;
String time=duration/3600+" hours and "+duration/60+" minutes and "+duration%60;
worker.publishDataLn("the algorithm took "+time);
} catch (InterruptedException ex) {
Logger.getLogger(ExecutionFrame.class.getName()).log(Level.SEVERE, null, ex);
} catch (ExecutionException ex) {
Logger.getLogger(ExecutionFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
this.setVisible(false);
}
public static Set<Integer> minVertexCoverLP(String fileName,VertexCoverSwingWorker swingWorker) throws IOException{
Graph g=new Graph();
System.out.println("reading the graph.....\n");
swingWorker.publishDataLn("reading the graph.....\n");
g.readGraphFromText(fileName);
System.out.println("RUNNING LP ALGORITHM:\n---------------------------");
swingWorker.publishDataLn("RUNNING LP ALGORITHM:\n-------------------------------------------");
System.out.println("number of nodes="+g.getNodeNum());
swingWorker.publishDataLn("number of nodes="+g.getNodeNum());
System.out.println("number of edges="+g.getEdgeNum());
swingWorker.publishDataLn("number of edges="+g.getEdgeNum());
Map<Integer,Double> solutionMap=computeVertexProbNum(g);
Set<Integer> minVertexCover=new HashSet<>();
for(Entry<Integer,Double> entry:solutionMap.entrySet()){
if(entry.getValue()>=0.5){
minVertexCover.add(entry.getKey());
}
}
return minVertexCover;
}
public static Set<Integer> minVertexCover2Approx(String fileName,VertexCoverSwingWorker swingWorker) throws IOException{
System.out.println("NOTE: as an update the program will print the current number of edges each 30sec\n\n");
swingWorker.publishDataLn("NOTE: as an update the program will print the current number of edges each 30sec\n\n");
Graph g=new Graph();
System.out.println("reading the graph.....\n");
swingWorker.publishDataLn("reading the graph.....\n");
g.readGraphFromText(fileName);
Set<Integer> returned=new HashSet<>();
long startTime=System.currentTimeMillis();
System.out.println("RUNNING 2-APPROXIMATION ALGORITHM:\n--------------------------------");
swingWorker.publishDataLn("RUNNING 2-APPROXIMATION ALGORITHM:\n------------------------------------------------------------------------");
System.out.println("number of nodes="+g.getNodeNum());
swingWorker.publishDataLn("number of nodes="+g.getNodeNum());
System.out.println("number of edges="+g.getEdgeNum());
swingWorker.publishDataLn("number of edges="+g.getEdgeNum());
while(!g.isEmpty()){
long nowTime=System.currentTimeMillis();
int[] randomEdge=g.chooseRandomEdge();
int inNode=randomEdge[0];
int outNode=randomEdge[1];
if(outNode==-1){
continue;
}
returned.add(inNode);
returned.add(outNode);
g.deleteEdgeUndirected(inNode,outNode);
g.deleteAdjacentUndirectedEdges(inNode, outNode);
if((nowTime/1000)>(startTime/1000)+20){
System.out.println("number of edges now="+g.getEdgeNum());
swingWorker.publishDataLn("number of edges now="+g.getEdgeNum());
startTime=nowTime;
}
}
return returned;
}