Advertisement
STANAANDREY

Untitled

May 17th, 2023
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. int matchScore = 1;
  8. int mismatchScore = -1;
  9. int gapScore = -2;
  10.  
  11. int maximum(int a, int b, int c) {
  12. return max(max(a, b), c);
  13. }
  14.  
  15. void needlemanWunsch(string seq1, string seq2) {
  16. int n = seq1.length();
  17. int m = seq2.length();
  18.  
  19. vector<vector<int>> scoreMatrix(n + 1, vector<int>(m + 1, 0));
  20.  
  21. // Initialize the first row and column with gap scores
  22. for (int i = 0; i <= n; i++)
  23. scoreMatrix[i][0] = i * gapScore;
  24. for (int j = 0; j <= m; j++)
  25. scoreMatrix[0][j] = j * gapScore;
  26.  
  27. // Fill in the score matrix
  28. for (int i = 1; i <= n; i++) {
  29. for (int j = 1; j <= m; j++) {
  30. int match = scoreMatrix[i - 1][j - 1] + (seq1[i - 1] == seq2[j - 1] ? matchScore : mismatchScore);
  31. int deletion = scoreMatrix[i - 1][j] + gapScore;
  32. int insertion = scoreMatrix[i][j - 1] + gapScore;
  33. scoreMatrix[i][j] = maximum(match, deletion, insertion);
  34. }
  35. }
  36.  
  37. // Traceback to find the alignment
  38. string alignedSeq1 = "";
  39. string alignedSeq2 = "";
  40. int i = n, j = m;
  41. while (i > 0 && j > 0) {
  42. if (scoreMatrix[i][j] == scoreMatrix[i - 1][j - 1] + (seq1[i - 1] == seq2[j - 1] ? matchScore : mismatchScore)) {
  43. alignedSeq1 = seq1[i - 1] + alignedSeq1;
  44. alignedSeq2 = seq2[j - 1] + alignedSeq2;
  45. i--;
  46. j--;
  47. } else if (scoreMatrix[i][j] == scoreMatrix[i - 1][j] + gapScore) {
  48. alignedSeq1 = seq1[i - 1] + alignedSeq1;
  49. alignedSeq2 = "-" + alignedSeq2;
  50. i--;
  51. } else {
  52. alignedSeq1 = "-" + alignedSeq1;
  53. alignedSeq2 = seq2[j - 1] + alignedSeq2;
  54. j--;
  55. }
  56. }
  57.  
  58. while (i > 0) {
  59. alignedSeq1 = seq1[i - 1] + alignedSeq1;
  60. alignedSeq2 = "-" + alignedSeq2;
  61. i--;
  62. }
  63.  
  64. while (j > 0) {
  65. alignedSeq1 = "-" + alignedSeq1;
  66. alignedSeq2 = seq2[j - 1] + alignedSeq2;
  67. j--;
  68. }
  69.  
  70. cout << "Aligned Sequence 1: " << alignedSeq1 << endl;
  71. cout << "Aligned Sequence 2: " << alignedSeq2 << endl;
  72. }
  73.  
  74. int main() {
  75. string seq1 = "AGTACGCA";
  76. string seq2 = "TATGC";
  77.  
  78. needlemanWunsch(seq1, seq2);
  79.  
  80. return 0;
  81. }
  82.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement