How to reverse a sequence

Hello everybody, sorry for my english, I'm french.
I'm also a beginner in C++
I have a question. I need to reverse a sequence of letters
In one octet, there are 4 letters (2 bits by letter)

For example, I have this :
ATCG CTTA AATT
And I need to have this :
TTAA ATTC GCTA

But, first, I just want to reverse the octet to obtain this :
AATT CTTA ATCG

But it doesn't working for size of sequence which isn't divisible by 4.
For this : ATCGCTTAAAT
I obtain : AATACTTAATC

I do this, with this code :

1
2
3
4
5
6
  size_t longueur_tab = (longueur/4 + (longueur%4 !=0)), temp = 0;
    for (size_t i = 0 ; i < (longueur_tab/2) ; i++){
    	temp = tab[i];
        tab[i] = tab[longueur_tab - i -1];
        tab[longueur_tab - i - 1] = temp;
	}

Note : longueur : is for the size of my sequence

In a second time, I want to obtain :
TAAATTCGCTA
But it's too difficult for me !

Thank you very much for your help and sorry for my english !!
Are you limited to cpp? Otherwise I would advice you to use the biopython library in python.

I don't really know what is wrong with your code, but you could also write it differently and loop through the string and insert every char into the first position of a new string. Something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

int main()
{
string seq = "AGGTTGGAAA";
string seq2;
string seq1;
int seqlen = seq.length();
    for (int x=0; x<seqlen; x++)
    {
        seq1 = seq[x];
        seq2.insert(0,seq1);
    }
cout << seq2 << endl;
system("pause");
return 0;
}


Last edited on
You could make an Octet class or struct:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <iostream>
#include <string>
#include <vector>

struct Octet {
	std::string content;

	const std::string getReverse() const { return std::string(content.rbegin(), content.rend()); }
};

int main() {

	std::vector<Octet> octets;

	octets.push_back({ "ABAB" });
	octets.push_back({ "COCO" });
	octets.push_back({ "TUTU" });
	
	//Octets in order, conent not reversed
	for (auto octet : octets) {
		std::cout << octet.content << "\t";
	}
	std::cout << std::endl;

	//Octets in order, conent reversed
	for (auto octet : octets) {
		std::cout << octet.getReverse() << "\t";
	}
	std::cout << std::endl;

	octets = std::vector<Octet>(octets.rbegin(), octets.rend());

	//Octets in reversed order, content not reversed
	for (auto octet : octets) {
		std::cout << octet.content << "\t";
	}
	std::cout << std::endl;

	//Octets in reversed order, content reversed
	for (auto octet : octets) {
		std::cout << octet.getReverse() << "\t";
	}
	std::cout << std::endl;

	return 0;
}


What's nice about this approach is that the content of each octet can be an arbitrary size.
Last edited on
Topic archived. No new replies allowed.