Advertisement
Guest User

Untitled

a guest
Dec 28th, 2021
615
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.72 KB | None | 0 0
  1.  
  2. #include <iostream>
  3. #include <fstream>
  4. #include <string>
  5. using namespace std;
  6.  
  7.  
  8.  int myFunction(string x){ //12 bit binary decoder
  9.     int y = 0;
  10.     for(int i = 0;i < 12;i++){
  11.         if(x.at(i) == '1'){
  12.             if(i==0){y+=2048;}
  13.             if(i==1){y+=1024;}
  14.             if(i==2){y+=512;}
  15.             if(i==3){y+=256;}
  16.             if(i==4){y+=128;}
  17.             if(i==5){y+=64;}
  18.             if(i==6){y+=32;}
  19.             if(i==7){y+=16;}
  20.             if(i==8){y+=8;}
  21.             if(i==9){y+=4;}
  22.             if(i==10){y+=2;}
  23.             if(i==11){y+=1;}
  24.         }
  25.     }
  26.     cout << "\n"<< y;
  27.     return y;
  28. }
  29.  
  30. int main () {
  31.  
  32.     int zerocount[12]{0,0,0,0,0,0,0,0,0,0,0,0}, onescount[12]{0,0,0,0,0,0,0,0,0,0,0,0};
  33.     string gamma, epsilon;
  34.  
  35. ifstream myfile ("input3.txt");
  36. string line;
  37. if (myfile.is_open()){
  38.  
  39.     while ( getline (myfile,line) ){ //start looping through each line
  40.         for(int i = 0; i < 12;i++){ //for each line loop 12 times, adjust count[i] according to line.at(i)
  41.            
  42.             if(line.at(i) == '0'){ //counters
  43.                 zerocount[i] ++;
  44.  
  45.             }else{
  46.                 onescount[i] ++;
  47.             }
  48.         }
  49.     }
  50.  
  51.     for(int i =0; i <12;i++){
  52.         if (onescount[i] > zerocount[i]){ //construct gamma/epsilon by concat either a 0 or a 1
  53.             gamma += "1";
  54.             epsilon += "0";
  55.         }
  56.         else {gamma += "0"; epsilon += "1";}
  57.     }
  58.  
  59.     cout << "\nG: " << gamma << " E: " << epsilon; //print
  60.  
  61.     int g = myFunction(gamma);
  62.     int e = myFunction(epsilon);
  63.     cout << "\n Final answer is: "  <<e*g;
  64.  
  65. myfile.close();} else cout << "Unable to open file"; //compacted file reading code
  66.  
  67.  
  68.     return 0;
  69. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement