Knapsack 0-1 C++ binary & WE

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • DANILIN
    New Member
    • Oct 2018
    • 24

    Knapsack 0-1 C++ binary & WE

    Knapsack 0-1 C++ binary & WE

    Classic Knapsack problem is solved in many ways

    My newest program synthesizes all ciphers from 0 & 1
    adding an extra register and 0 remain on left in cipher

    Feature of algorithm:
    converts whole into a string
    and converts string into a whole
    what will help in other programs

    Number of comparisons decreases from N! to 2^N
    for example N=10 & N!=3628800 >> 2^N=1024

    Random values origin are automatically assigned
    quantity and quality and integral of value is obtained
    and in general: integral of quantity and quality

    Code:
    #include <iostream> // KNAPSACK 0-1 DANILIN
    using namespace std; int main()
    { setlocale (LC_ALL, "RUS");
      srand(time(NULL)); // rextester.com/VCBSQ91995
       
    { int n=7; int G=5; int a=2;  
      int dec, i, h, k, max, m; 
      for (i=0; i<n; i++) a=2*a; string e[a]; // 2^n 
      int L[n], C[n], j[n], q[a], d[a];  
    
    cout << "#  Amo Price" << endl << endl; 
    for (i=0; i<n; i++)
    { L[i]=1+(rand() % 3); C[i]=10+(rand() % 9); j[i]=0;
      cout << i+1 << "   " << L[i] << "   " << C[i] << endl; 
    } 
    for (i=0; i<a; i++) { q[i]=0; d[i]=0;}
    cout << endl; 
    
    cout << "Mx Amo Price Chifer" << endl << endl; 
    for (h = a-1; h>(a-1)/2; h--)
      { dec=h; while (dec > 0)
          { string s(""); s += '0'+dec%2;   
            e[h] = s + e[h]; dec/=2; 
          }
    if (e[h] == "") {e[h] = "0";}
    e[h]= e[h].substr(1, e[h].size()-1);
    
    for (k=0; k<n; k++)
    { j[k] = atoi((char*)(e[h].substr(k,1)).c_str()); 
      q[h]=q[h]+L[k]*j[k]*C[k];
      d[h]=d[h]+L[k]*j[k];
    }
    
    if (d[h] <= G)
    cout << G << "  " << d[h] << "  " << q[h] << "  " << e[h] << endl; 
    } cout << endl;
    
    max=0; m=1;
    for (i=0; i<a; i++)
    { if (d[i]<=G && q[i]>max){ max=q[i]; m=i;}
    }
    cout << "Mx Price Cipher" << endl << endl; 
    cout << d[m] << "  " << q[m] << "  " << e[m] << endl << endl;}
    system("pause");
    }
Working...