Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating complement of DNA sequence and reversing it C++

So I am trying to create the complement of the sequence TGAGACTTCAGGCTCCTGGGCAACGTGCTGGTCTGTGTGC however my output didn't work as expected. The complements for each letter in the sequence are
A -> T
G -> C
C -> G
T -> A

I've been programming in Java for over a year now so I've gotten really rusty with pointers in C++, I'm guessing the problem lies in the reverse methods and the way to pointers are shifted around through each pass of the function call

#include<stdio.h>
#include<iostream>
using namespace std;

void reverse(char s[]);

int main() {
    char s[40] = {'T','G','A','G','A','C','T','T','C','A','G','G','C','T','C','C','T','G','G','G','C','A','A','C','G','T','G','C','T','G','G','T','C','T','G','T','G','T','G'};

    cout << "DNA sequence: "<< endl << s << endl;

    reverse(s);

    cout << "Reverse Compliment: "<< endl << s << endl;



    system("pause");
}

void reverse(char s[])
{
    char c;
    char *p, *q;

    p = s;

    if (!p)
        return;

    q = p + 1;
    if (*q == '\0')
        return;

    c = *p;
    reverse(q);

    switch(c) {
        case 'A':
            *p = 'T';
            break;
        case 'G':
            *p = 'C';
            break;
        case 'C':
            *p = 'G';
            break;
        case 'T':
            *p = 'A';
            break;  
    }
    while (*q != '\0') {
        *p = *q;
        p++;
        q++;
    }

    *p = c;

    return;
}
like image 650
Juan Battini Avatar asked Jan 08 '23 09:01

Juan Battini


1 Answers

Standard modern C++ makes this low-level, pointer-oriented programming, unnecessary (in fact, you're effectively writing C).

Once you have a function, say complement, which transforms a nucleotide to its complement, you just need to apply some standard library function like transform.

Here is a rewrite of your program in C++11:

#include <string>
#include <iostream>                                                                                                                                                                                          
#include <algorithm>
#include <cassert>


using namespace std;


char complement(char n)
{   
    switch(n)
    {   
    case 'A':
        return 'T';
    case 'T':
        return 'A';
    case 'G':
        return 'C';
    case 'C':
        return 'G';
    }   
    assert(false);
    return ' ';
}   


int main() 
{   
    string nucs = "ACAATTGGA";
    transform(
        begin(nucs),
        end(nucs),
        begin(nucs),
        complement);
    cout << nucs << endl;
}   
like image 191
Ami Tavory Avatar answered Jan 09 '23 23:01

Ami Tavory