StoryCode

유전 알고리즘(Genetic Algorithm)(2)-MST(java)

유전 알고리즘
반응형


출처: https://twinw.tistory.com/2?category=543725 [흰고래의꿈]


앞에서 포스팅한 글에서 예시로 다루었듯이

모든 도시를 최단으로 방분하는 경우

 Minimum Spaning Tree를 유전알고리즘으로 하여 구해보도록 하겠습니다. 

사용 언어는 나중에 안드로이드 개발에 사용하기 위해 자바로 하였고

오늘 포스팅은 데이터를 외부에서 가져오는 것까지하고

실질적인 유전알고리즘에 대한 코드는 다음 포스팅에서 설명해드리겠습니다.

 

데이터 파일은 첨부파일에 보시면 됩니다.

samples.zip


import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
 
public class MST {
    public static void main(String[] argv){
        String fileName = "input.dat";
        int[][] dataMatrix = null;
        int nodeNum = 0;
        String temp;
     
        try {
            FileReader Fr = new FileReader(fileName);
            BufferedReader Br = new BufferedReader(Fr);
            try {
                if(Br.ready()){
                    System.out.println("파일이 로드 되었습니다.");
                    nodeNum = Integer.valueOf(Br.readLine());
                    dataMatrix = new int [nodeNum][nodeNum];
                    while((temp=Br.readLine())!=null){
                        dataMatrix[Integer.valueOf(temp.split(" ")[0])]
                                [Integer.valueOf(temp.split(" ")[1])] = Integer.valueOf(temp.split(" ")[2]);
                        dataMatrix[Integer.valueOf(temp.split(" ")[1])]
                                [Integer.valueOf(temp.split(" ")[0])]= Integer.valueOf(temp.split(" ")[2]);
                    }
                }
            catch (IOException e) {
                System.err.println("파일 로드를 실패했습니다..");
            }
        catch (FileNotFoundException e) {
                System.err.println("다음 파일이 없습니다. : " + fileName);
        }
        //입력확인
//      for(int i=0; i<nodeNum;i++){
//          for(int j=0; j<nodeNum;j++){
//              System.out.print(dataMatrix[i][j]+" ");
//          }
//          System.out.println();
//      }
         
        //데이터 + 염색체 길이 + 염색체 갯수 + 목적치 + th_fit + 엘리트수 + 교배횟수
        GA mGA = new GA(dataMatrix, nodeNum,10,1000,80000,2,10000);
    }
}




반응형