I codded a program to print n-bit binary gray codes. But I'm not sure if it is a backtracking program. If it is not a backtracking program, what is something I can do to use it in this code.
I want to print the binary codes themselves, not their decimal equivalent.
vector<string> grayCode(int n)
{
if(n<=0)
return {"0"};
if(n == 1)
return {"0", "1"};
vector<string> list1 = grayCode(n-1);
vector<string> mainList;
for(int i=0; i<list1.size(); i++)
mainList.push_back("0" + list1[i]);
for(int i=list1.size()-1; i>-1; i--){
mainList.push_back("1" + list1[i]);
return mainList;
}
int main()
{
vector<string> gcode = grayCode(4);
for(int i=0; i<gcode.size(); i++)
cout<< gcode[i] << " ";
return 0;
}
That should be your question. None of it has to do with grey code or backtracking. It's a simple output formatting question.
You can change the output format using for example
std::hexlike this:That will output the value in hexadecimal. There is also
std::octfor octal. Sadly there is nostd::binfor binary. Andstd::cout.setbase(2);will also not work.I think the simplest is to use
std::bitset, specifically theto_string().