Skip to content

Commit f5ac4f0

Browse files
committed
add Sequence Alignment
1 parent e1f6633 commit f5ac4f0

File tree

2 files changed

+89
-0
lines changed

2 files changed

+89
-0
lines changed

08/SequenceAlignment.java

+88
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package hw08;
2+
3+
import java.util.Scanner;
4+
5+
public class SequenceAlignment {
6+
private int gapCost = 1;
7+
private int mismatchCost = 2;
8+
private String str1 = null, str2 = null;
9+
private int[][] M = null;
10+
11+
public SequenceAlignment(){
12+
Scanner sc = new Scanner(System.in);
13+
System.out.print("String1 : ");
14+
str1 = sc.nextLine();
15+
System.out.print("String2 : ");
16+
str2 = sc.nextLine();
17+
M = new int[str1.length()+1][str2.length()+1];
18+
}
19+
20+
public void sequenceAlignment(){
21+
for(int i = 0; i<str2.length() + 1; i++){
22+
M[0][i] = i * gapCost;
23+
}
24+
25+
for(int i = 0; i<str1.length() + 1; i++){
26+
M[i][0] = i * gapCost;
27+
}
28+
29+
for(int i = 1; i<str1.length()+1 ;i ++){
30+
for(int j = 1; j<str2.length()+1 ; j++){
31+
M[i][j] = Math.min(Math.min(calcMismatchCost(i - 1,j - 1) + M[i-1][j-1], gapCost + M[i-1][j]), gapCost + M[i][j-1]);
32+
}
33+
}
34+
}
35+
36+
private int calcMismatchCost(int x, int y){
37+
if(str1.charAt(x) == str2.charAt(y)){
38+
return 0;
39+
}
40+
return mismatchCost;
41+
}
42+
43+
// 배열로도 구할수 있지 않을까?
44+
private void printRoute(int x, int y){
45+
System.out.print("M[" + x +"][" + y +"] => ");
46+
if(x == 0 && y == 0){
47+
return ;
48+
}else if(y == 0){
49+
printRoute(x - 1, y);
50+
}else if(x == 0){
51+
printRoute(x, y-1);
52+
}else if(calcMismatchCost(x - 1,y - 1) + M[x-1][y-1] < gapCost + M[x-1][y]){
53+
if(calcMismatchCost(x - 1,y - 1) + M[x-1][y-1] < gapCost + M[x][y-1]){
54+
printRoute(x-1,y-1);
55+
}
56+
else{
57+
printRoute(x,y-1);
58+
}
59+
}else{
60+
if(gapCost + M[x-1][y] < gapCost + M[x][y-1]){
61+
printRoute(x-1,y);
62+
}else{
63+
printRoute(x,y-1);
64+
}
65+
}
66+
}
67+
68+
public void print(){
69+
System.out.println("MIN COST : " + M[str1.length()][str2.length()]);
70+
71+
System.out.print(" ");
72+
for(int i = 0; i<str2.length(); i++){
73+
System.out.printf("%3s", str2.charAt(i));
74+
}
75+
System.out.println();
76+
77+
for(int i = 0; i<str1.length()+1 ;i ++){
78+
for(int j = 0; j<str2.length()+1 ; j++){
79+
if( i == 0 && j == 0) System.out.print(" ");
80+
else if( i > 0 && j == 0 ) System.out.printf("%3s", str1.charAt(i-1));
81+
System.out.printf("%3s", M[i][j]);
82+
}
83+
System.out.println();
84+
}
85+
86+
printRoute(str1.length(), str2.length());
87+
}
88+
}

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@
66
5. Minimize Lateness / Huffman Code
77
6. Dijkstra / Prim
88
7. Knapsack
9+
8. Sequence Alignment

0 commit comments

Comments
 (0)