Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Binary Reflected Gray Code using vectors

$
0
0
I have a homework assignment that's objective is to create a function that returns a vector of binary reflected gray code. I know this can be done iteratively, however it must be done recursively in order to be to spec. This is not an easy task. I have spent most of the last few days trying to figure out how to do this with only one parameter (int n) as part of my function. If anyone could help me I am currently working on it from home, throwing new ideas at it over time. The function must also return a vector of strings.



#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
vector<string> Gray(int n)
{
  vector<string> graycode;
  vector<string> reverse;
  vector<string> gray;
  
  if (n==0){
    cout<<"base case"<<endl;
    cout<< "n == 0"<<endl;
  }
  
  else{
    cout<< "else level 1" <<endl;
    if (graycode.empty())
      {
	graycode.push_back("0");
	graycode.push_back("1");    
      }
    else{
      cout<< "else level 2"<< endl;
      //attempt to create a reversed graycode vector called reverse
      //by looping over each item
      cout << "First for loop"<< endl;
      for(int x = graycode.size(); x>=1; x--){
	int y = 1;
	reverse[y] = graycode[x];
	y++;
      }
      //Loop over graycode and attempt to prepend "0" to each item in the original vector
      for(int c = 1; c <= graycode.size(); c++){
	graycode[c] = "0"+ graycode[c];
	gray.push_back(graycode[c]);
      }
      //Loop over reverse and attempt to prepend "1" to each item in the reverse vector
      for(int h = 1; h<=reverse.size(); h++){
	reverse[h] = "1"+ reverse[h];
	gray.push_back(reverse[h]);
      }   
    } 
    Gray(n-1);     
    return gray;
  }
}
int main()
{
  cout << "Entered main..." << endl;
  int n;
  cout<< "Enter an integer"<< endl;
  cin >> n;
  vector<string> Grays = Gray(n);
  for(int i = 0; i <= Grays.size();i++){
    cout << Grays[i] << endl;
  }
  
  return 0;
}



Viewing all articles
Browse latest Browse all 51036

Trending Articles