Thread: c program to find combination of numbers

  1. #1
    Registered User
    Join Date
    Aug 2015
    Posts
    75

    c program to find combination of numbers

    i am trying to find combination of numbers . i tried following code but its not working. it is giving strange output. can anyone please fix this code or give me working code?

    Code:
    #include <stdio.h>#include <stdlib.h>
    
    
    void combination(int[],int,int);
    int a[] = {1,2,3,4};
    int size = sizeof(a)/sizeof(a[0]);
    int main() {
    
    
        combination(a, 0, 3);
    
    
    }
    void combination(int a[], int start, int com) {
        int i,j,k;
        if(start==com) {
            printf("\n");
            return;
        }
        for(i=start;i<=com;i++) {
            combination(a,start+1, 3);
            printf("%d", a[start]);
        }
    }
    i want to pass how many combinations i want so i passed 3 for testing but it can be anything.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,986
    > combination(a,start+1, 3);
    Perhaps
    combination(a,start+1, com-1);

    The whole point of a recursive function is that you call yourself with a simpler version of the problem.
    Which in this case, is an array which is one element shorter.

    Eventually, you end up with a trivial case, like an array with 0 or 1 elements, which terminates the recursion.

    > if(start==com)
    Perhaps com == 0 would be better.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Nov 2018
    Location
    Amberg in upper palatinate, Bavaria
    Posts
    45

    Example to show possible combinations of numbers

    Hallo san12345!

    May be there is an example for you. IO wrote it by my own.
    But the program is in german language.
    But i hope some parts of the program can help cou.
    There are three parts:

    1. main.cc
    2. permutieren.h
    3.permutieren.cxx

    I wrote it with Anjuta on SUSE Linux tumbleweed.
    With some experience you can port it to codeblocks, codelite, kdevelop
    First i think, main.cc:
    Code:
    /* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*-  */
    /*
     * main.cc
     * Copyright (C) 2017 Josef Wismeth (rusyoldguy)
     * upper palatinate, Bavaria, district cockreed in Amberg, Pine-tree- way 7 
     * 
     * permutieren4 is free software: you can redistribute it and/or modify it
     * under the terms of the GNU General Public License as published by the
     * Free Software Foundation, either version 3 of the License, or
     * (at your option) any later version.
     * 
     * permutieren4 is distributed in the hope that it will be useful, but
     * WITHOUT ANY WARRANTY; without even the implied warranty of
     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
     * See the GNU General Public License for more details.
     * 
     * You should have received a copy of the GNU General Public License along
     * with this program.  If not, see <http://www.gnu.org/licenses/>.
     */
    
    #include "permutieren.h"
    
    //using namespace std;
    
    
    /* In C ist dies die Hauptfunktion */
    int main()
    {
    
     int wastun = 9, zeiza, perze;
     permutieren euler;    
    
     do
     switch(wastun)
     {        
      default:
         std::cout << "Erzeugen von Permutierten Zahlenreihen" << std::endl;     
         std::cout << "Programm beenden.....................0" << std::endl;
         std::cout << "Permutierte Zahlenreihe aufzeigen....1" << std::endl;
         std::cout << "Permutierte Letterreihe aufzeigen....2" << std::endl;     
         std::cout << "Ihre Wahl: ";
         std::cin >> wastun;
        break;     
    
    case 0:
        std::cout << "Programm beendet" << std::endl;
        return EXIT_SUCCESS;     
       break; 
             
    case 3:
    case 1:
        if (wastun == 1)
         {
          std::cout << "Bitte Anzahl der Zahlen(3 bis 8) eingeben: ";
          std::cin >> zeiza;
         }
    
        if ((zeiza < 3) || (zeiza > 8))
         { 
          std::cout << "Falsche Anzahl von Elementen: "<< zeiza << std::endl; 
          wastun = 9;
          break;
         } 
    
       perze = euler.zaehleperm(zeiza);
    
       std::cout << "Anzahl der Permutationen: " << zeiza << "! = " << perze << std::endl;
       wastun = 9;
      break;     
    
    case 2:
        std::cout << "Bitte Wort (mindestend 3 maximal 8 Buchstaben Laenge) eingeben: ";
        std::cin >> euler.permwort;
        for (zeiza = 0; zeiza < 26; zeiza++)
         if (euler.permwort[zeiza] == '\0'){
        std::cout <<"Laenge des Wortes: " << zeiza << std::endl; 
        break;
        }     
        wastun = 3;
      break;     
         
     }while(wastun != 0);
        
     return EXIT_SUCCESS;
    }
    now permutieren.h:
    Code:
    #ifndef PERMUTATION_H_INCLUDED
    #define PERMUTATION_H_INCLUDED
    
    #include <iostream>
    
    void zeichendoppeltest(std::string zahlwort,int *zaehler, int zeiza);
    int zaehleperm(int zeiza);
    
    class permutieren
    {
     public:
      permutieren();
      ~permutieren();        
     int atoint(std::string zawo);    
     std::string itoa(int number);
     void initwort(std::string *wort, std::string *bwort, int zeiza);
     int pruefestring(std::string wort, std::string soll);    
     void zeichendoppeltest(std::string zahlwort,int *zaehler, int zeiza);    
     int zaehleperm(int zeiza);        
     void showperms(std::string zahlwort, int zeiza);    
     char permwort[26];        
    
    };
    
    
    #endif // PERMUTATION_H_INCLUDED
    Here permutieren.cxx:
    Code:
    #include <permutieren.h>
    
    using namespace std;
    
    #include <string.h>
    #include <sstream>
    #include <complex.h>
    
     permutieren::permutieren()
     {
    
      char pwort[26]={
      'A','B','C','D','E','F','G','H',
      'I','J','K','L','M','N','O','P',
      'Q','R','S','T','U','V','W','X',
      'Y','Z'};     
      for (int i = 0; i < 26; i++)
       permwort[i] = pwort[i];         
    
     }
     permutieren::~permutieren(){};        
    
    
    int permutieren::atoint(std::string zawo)
    {
     int rewer = 0;
     std::istringstream b(zawo);
     b >> rewer;
     return rewer;
    }
    
    std::string permutieren::itoa(int number)
    {
     std::ostringstream buff;
     buff << number;
     return buff.str();
    }
    
    void permutieren::initwort(std::string *wort, std::string *bwort, int zeiza)
    {
     int slei, sleib;
     char numchar[10] = {'0','1','2','3','4','5','6','7','8','9'};     
     for (slei = 1; slei <= zeiza; slei++)
      *wort +=numchar[slei];
    
     for (slei = zeiza; slei >= 1; slei--)
      *bwort +=numchar[slei];    
    }
    
    // Prueft String wort auf vorkommen der Zeichen in String soll, bei nicht Uebereinstimmung
    // Rueckgabewert ungleich Null sonst Null;
    int permutieren::pruefestring(std::string wort, std::string soll)
      {
       int slei, sleib, lgeist, lgesoll, rewer;
       std::string str1 ="";
       std::string str2 = "";
        
       lgeist  = wort.length();
       lgesoll = soll.length();
      
    
        
      for (slei = 0; slei < lgeist; slei++)
        {
         //cout << endl << "vor slei=" << slei << "   ";
         if (rewer == lgesoll) break;
          for (sleib = 0; sleib < lgesoll; sleib++)
         {
          str1 = wort.substr(slei, 1);
          str2 = soll.substr(sleib, 1);
    
          /// if (wort[slei] != soll[sleib])
          if (str1.compare(str2) != 0)
           {
            ++rewer;
            //cout << "  wort=" << wort[slei] << "   soll=" << soll[sleib] << "   rewer=" << rewer << endl;
           }
           else
            {
             rewer = 0;
             //cout << "* wort=" << wort[slei] << "   soll=" << soll[sleib] << "   rewer=" << rewer << endl;
             break;
            }
         }
        //cout << "    nach slei=" << slei << "  \n";
        }
    
        //cout << "E-soll=" << soll<< "  wort:" << wort <<  "  rewer: " << rewer  << "   \n\n";
        return rewer;
      }
    
     // test a string if characters are mor as one time in string
    void permutieren::zeichendoppeltest(std::string zahlwort,int *zaehler, int zeiza)
    {
     int slei, sleib, dummy = 0;
     std::string str1 ="";
     std::string str2 = "";
    
     //cout << "Zahlwort=" << zahlwort  << "\n";    
        
       for (slei = 0; slei < zeiza; slei++)
        {
            for (sleib = slei + 1; sleib < zeiza; sleib++)
          {
           str1 = zahlwort.substr(slei, 1);
           str2 = zahlwort.substr(sleib, 1);        
           if (str1.compare(str2) == 0)
            dummy++;
           //cout << "str1=" << str1 << "  str2:" << str2 <<  "  dummy: " << dummy  << "\n";
         }
        }
      *zaehler = dummy;
     //cout << "dummy: " << dummy  << "\n";
        
    }
    
    int permutieren::zaehleperm(int zeiza)
    {
     std::string wort, bwort, zahlwort;
     int start, ende, slei, zaehler, nuze, perze;
     
     initwort(&wort, &bwort, zeiza);
    
     start = atoint(wort); //, 10);
     ende  = atoint(bwort); //, 10);
     
     cout << "\nAnzahl der Elemente.: "<< zeiza << endl << "Start bei Zahl......: "<< start << endl << "Ende bei Zahl.......: " << ende << endl;
    
     cout << "Startzahl als String: " << wort  << endl;
     cout << "Endezahl als String.: " << bwort << endl << endl;
    
     cout << "start: " << start  << endl;
     cout << "ende:  " << ende << endl << endl;
        
        
     perze = 0; //  zaehlt die Anzahl der dargestellten Zahlen
    
     // Schleife von 12345 bis Ueber 54321 weil im diesem Beispiel 5 unterschiedliche Zeichen 
     for (slei = start; slei <= ende; slei++)//ende
     {
      zahlwort = itoa(slei);     // , zahlwort, 10); // wandelt ganze Zahl in String um
      zeiza = zahlwort.length(); // strlen(zahlwort); // Stellt fest, wieviele Zeichen die als String dargestellte Zahl hat 
      zaehler = 0;               // zaehlt, wie oft ein Zeichen im String vorkommt
    
       // untersucht den String ob ein Zeichen mehr als einmal vorkommt 
      zeichendoppeltest(zahlwort, &zaehler, zeiza);
    
     nuze = 0;
    
      // test a string if  characters are included where not alowed
      nuze = pruefestring(zahlwort, wort);
    
      //cout << "*Permutation Nr.: " << perze << " = " << zahlwort <<  "   nuze= " << nuze  << "  zaehler=" << zaehler << "   ";
         
      if ((nuze == 0) && (zaehler == 0))
       {
        perze++;
        cout << "Permutation Nr.: " << perze << " = " << zahlwort << "   ";
        showperms(zahlwort, zeiza);
       }
      }
    
    return perze;
    }
    
    void permutieren::showperms(std::string zahlwort, int zeiza)
    {
     int slei, sleia, sleib = 0;
     std::string zsymbol = "123456789";
     std::string str1 ="";
     std::string str2 = "";    
     //char permwort[8] = {'A','B','C','D','E','F','G','H'};     
     //std::cout << "\n"; //permwort[sleib]; 
     for (slei = 0; slei < zeiza; slei++) 
      {
        for (sleia = 0; sleia < zeiza; sleia++) 
         {
          str1 = zahlwort.substr(slei, 1);
          str2 = zsymbol.substr(sleia, 1);
          
          if (str1.compare(str2) == 0)
           {
            sleib = sleia;
            //std::cout << "str1=" << str1 << " str2=" << str2 << "   sleib=" << sleib <<"\n"; //permwort[sleib]; 
            break;
           }      
         }
    
         std::cout << permwort[sleib]; 
      }    
    
     std::cout << std::endl;
    }
    short descrition:
    First, you tell the program how much numbers do yout want to have.
    It is limited from 3 th 8 (would be 1*2*3*4*`5*6*7*8)
    now it creats a string with decimal numbers.
    If your input was 3 you have "123". and a second string with "321"
    Now this two strings will convert to two decimal numbers;
    123 and 321;
    A loop shows the numbers from 123 to 321.
    Every character of the generated number you have ony one time.
    Example:
    122 or 323 wil not be printed on screen.
    example of an output in terminal:
    Code:
    Erzeugen von Permutierten Zahlenreihen
    Programm beenden.....................0
    Permutierte Zahlenreihe aufzeigen....1
    Permutierte Letterreihe aufzeigen....2
    Ihre Wahl: 1
    Bitte Anzahl der Zahlen(3 bis 8) eingeben: 4
    
    Anzahl der Elemente.: 4
    Start bei Zahl......: 1234
    Ende bei Zahl.......: 4321
    Startzahl als String: 1234
    Endezahl als String.: 4321
    
    start: 1234
    ende:  4321
    
    Permutation Nr.: 1 = 1234   ABCD
    Permutation Nr.: 2 = 1243   ABDC
    Permutation Nr.: 3 = 1324   ACBD
    Permutation Nr.: 4 = 1342   ACDB
    Permutation Nr.: 5 = 1423   ADBC
    Permutation Nr.: 6 = 1432   ADCB
    Permutation Nr.: 7 = 2134   BACD
    Permutation Nr.: 8 = 2143   BADC
    Permutation Nr.: 9 = 2314   BCAD
    Permutation Nr.: 10 = 2341   BCDA
    Permutation Nr.: 11 = 2413   BDAC
    Permutation Nr.: 12 = 2431   BDCA
    Permutation Nr.: 13 = 3124   CABD
    Permutation Nr.: 14 = 3142   CADB
    Permutation Nr.: 15 = 3214   CBAD
    Permutation Nr.: 16 = 3241   CBDA
    Permutation Nr.: 17 = 3412   CDAB
    Permutation Nr.: 18 = 3421   CDBA
    Permutation Nr.: 19 = 4123   DABC
    Permutation Nr.: 20 = 4132   DACB
    Permutation Nr.: 21 = 4213   DBAC
    Permutation Nr.: 22 = 4231   DBCA
    Permutation Nr.: 23 = 4312   DCAB
    Permutation Nr.: 24 = 4321   DCBA
    Anzahl der Permutationen: 4! = 24
    Erzeugen von Permutierten Zahlenreihen
    Programm beenden.....................0
    Permutierte Zahlenreihe aufzeigen....1
    Permutierte Letterreihe aufzeigen....2
    Ihre Wahl: 0
    I hope now you get an idea to solve your problem.
    Other users can take it for their own ideas, creations.

    rusyoldguy
    Last edited by rusyoldguy; 02-16-2020 at 04:16 AM.

  4. #4
    misoturbutc Hodor's Avatar
    Join Date
    Nov 2013
    Posts
    1,750
    @san12345 do you want combinations or permutations?
    @rusyoldguy are you sure your program is complicated enough? Is it the enterprise solution to the problem? Additionally, This is the C sub-forum, not C++. And, I have to say it although others may disagree, you really should be using English function, variable, class etc names. Also English comments. That's just the way it is.

  5. #5
    Registered User
    Join Date
    Dec 2017
    Posts
    933
    Code:
    #include <stdio.h>
    #include <stdlib.h>
     
    // Print array a of size n on a single line.
    void print(int* a, int n)
    { 
        for (int i = 0; i < n; i++)
            printf("%d ", a[i]);
        putchar('\n');
    }
     
    #if 1
    // Using a loop and a single recursive call.
    void combo_r(int *in, int n, int r, int i_in,
                 int *out, int i_out)
    {
        if (i_out == r)
            print(out, r);
        else
            for (int i = i_in; n - i >= r - i_out; ++i)
            {
                out[i_out] = in[i];
                combo_r(in, n, r, i + 1, out, i_out + 1);
            }
    }
     
    #else
    // Using two recursive calls (no loop).
    void combo_r(int *in, int n, int r, int i_in,
                 int *out, int i_out)
    {
        if (i_out == r)
            print(out, r);
        else if (i_in < n)
        {
            out[i_out] = in[i_in];
            combo_r(in, n, r, i_in + 1, out, i_out + 1); // use element i_in
            combo_r(in, n, r, i_in + 1, out, i_out);     // don't use element i_in
        }
    }
    #endif
     
    // Print combinations (n-choose-r subsets) of in.
    void combo(int *in, int n, int r)
    {
        int out[r]; // VLA
        combo_r(in, n, r, 0, out, 0);
    }
     
    int main()
    {
        int a[] = {1, 2, 3, 4, 5};
        int n = sizeof a / sizeof a[0];
     
        for (int r = 0; r <= n; ++r)
        {
            printf("===== %d =====\n", r);
            combo(a, n, r);
        }
     
        return 0;
    }
    Code:
    ===== 0 =====
     
    ===== 1 =====
    1 
    2 
    3 
    4 
    5 
    ===== 2 =====
    1 2 
    1 3 
    1 4 
    1 5 
    2 3 
    2 4 
    2 5 
    3 4 
    3 5 
    4 5 
    ===== 3 =====
    1 2 3 
    1 2 4 
    1 2 5 
    1 3 4 
    1 3 5 
    1 4 5 
    2 3 4 
    2 3 5 
    2 4 5 
    3 4 5 
    ===== 4 =====
    1 2 3 4 
    1 2 3 5 
    1 2 4 5 
    1 3 4 5 
    2 3 4 5 
    ===== 5 =====
    1 2 3 4 5
    If you want the truth to stand clear before you, never be for or against. - Sent-ts'an

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Program to find combination of groups and letters
    By Lukáš Riedel in forum C Programming
    Replies: 3
    Last Post: 12-31-2015, 09:30 AM
  2. Every possible combination of a set of numbers
    By BIGDENIRO in forum C Programming
    Replies: 3
    Last Post: 07-09-2014, 11:00 AM
  3. Logic To Find Least Common Number Combination
    By EdMarx in forum C Programming
    Replies: 5
    Last Post: 11-29-2013, 07:16 AM
  4. Replies: 7
    Last Post: 04-07-2013, 03:45 PM

Tags for this Thread