На главную Наши проекты:
Журнал   ·   Discuz!ML   ·   Wiki   ·   DRKB   ·   Помощь проекту
ПРАВИЛА FAQ Помощь Участники Календарь Избранное RSS
msm.ru
Модераторы: Qraizer, Hsilgos
Страницы: (2) [1] 2  все  ( Перейти к последнему сообщению )  
> Как реализовать переменное количество вложенных циклов? , Как реализовать переменное количество вложенных циклов
    Ниже приведен код для массива из 4-х элементов. В реальности, количество элементов величина переменная, может быть значительно больше 4-х и каждому элементу соответствует свой цикл 'for'.
    Как это оформить в виде переменного количества вложенных циклов?

    Спасибо!


    Цитата

    int Array[4] = {1, 2, 3, 4};
    int Array_Size = 4;

    int x1, x2, x3, x4;


    for(x1=0; x1<Array_Size; x1++) {
    Print("Combination = ", Array[x1]);
    // -----------------------------------------------------
    for(x2=x1+1; x2<Array_Size; x2++) {
    Print("Combination = ", Array[x1] + " " + Array[x2]);
    // -----------------------------------------------------
    for(x3=x2+1; x3<Array_Size; x3++) {
    Print("Combination = ", Array[x1] + " " + Array[x2] + " " + Array[x3]);
    // -----------------------------------------------------
    for(x4=x3+1; x4<Array_Size; x4++) {
    Print("Combination = ", Array[x1] + " " + Array[x2] + " " + Array[x3] + " " + Array[x4]);
    }
    // -----------------------------------------------------
    }
    // -----------------------------------------------------
    }
    // -----------------------------------------------------
    }

      Рекурсией или шаблонами, если компайл-тайм достаточно
      Сообщение отредактировано: applegame -
        Цитата applegame @
        Рекурсией

        Это понятно, хотелось бы увидеть исправленный код, тем более что здесь всего несколько строк.
          Хотя, вот именно такие циклы рекурсией не получится.
              Вроде есть решение рекурсией, сейчас набросаю.
                Цитата applegame @
                Вроде есть решение рекурсией, сейчас набросаю.

                Возможно что-то наподобие последнего примера по линку:
                http://otvety.google.ru/otvety/thread?tid=19c7c28b27e095be

                Но не знаю как быть с принтами.
                Жду Вашего кода.
                  Как-то так в общем:
                  http://ideone.com/N12H4c

                  ExpandedWrap disabled
                    #include <iostream>
                    using namespace std;
                     
                    void combinationImpl(int* arr, int* outers, int size, int deep = 0) {
                        for(int x = deep ? outers[deep - 1] + 1 : 0; x < size; x++) {
                            outers[deep] = x;
                            cout << "Combination =";
                            for(int i = 0; i <= deep; i++) {
                                cout << " " << arr[outers[i]];
                            }
                            cout << endl;
                            if(deep < size) {
                                combinationImpl(arr, outers, size, deep + 1);
                            }
                        }
                    }
                    void combination(int* arr, int size) {
                        int* outers = new int[size];
                        combinationImpl(arr, outers, size);
                        delete[] outers;
                    }
                     
                    int main() {
                        int arr[4] = {1, 2, 3, 4};
                        combination(arr, 4);
                    }
                    Цитата applegame @
                    Как-то так в общем:
                    http://ideone.com/N12H4c

                    ExpandedWrap disabled
                      #include <iostream>
                      using namespace std;
                       
                      void combinationImpl(int* arr, int* outers, int size, int deep = 0) {
                          for(int x = deep ? outers[deep - 1] + 1 : 0; x < size; x++) {
                              outers[deep] = x;
                              cout << "Combination =";
                              for(int i = 0; i <= deep; i++) {
                                  cout << " " << arr[outers[i]];
                              }
                              cout << endl;
                              if(deep < size) {
                                  combinationImpl(arr, outers, size, deep + 1);
                              }
                          }
                      }
                      void combination(int* arr, int size) {
                          int* outers = new int[size];
                          combinationImpl(arr, outers, size);
                          delete[] outers;
                      }
                       
                      int main() {
                          int arr[4] = {1, 2, 3, 4};
                          combination(arr, 4);
                      }

                    Спасибо! Ваш результат идентичен моему оригинальному, но теперь возникла другая дилемма - мне надо чтобы этот код заработал в MQL4, там синтаксис похож на Си, а у Вас написано С++. Это С или С++?
                      Цитата atztek @
                      Это С или С++?
                      Это C++. Но на си переписывается очень просто:
                      ExpandedWrap disabled
                        #include <stdio.h>
                        #include <malloc.h>
                         
                        void combinationImpl(int* arr, int* outers, int size, int deep) {
                            int x, i;
                            for(x = deep ? outers[deep - 1] + 1 : 0; x < size; x++) {
                                outers[deep] = x;
                                printf("Combination =");
                                for(i = 0; i <= deep; i++) {
                                    printf(" %d", arr[outers[i]]);
                                }
                                printf("\n");
                                if(deep < size) {
                                    combinationImpl(arr, outers, size, deep + 1);
                                }
                            }
                        }
                        void combination(int* arr, int size) {
                            int* outers = malloc(size * sizeof(int));
                            combinationImpl(arr, outers, size, 0);
                            free(outers);
                        }
                         
                        int main() {
                            int arr[] = {1, 2, 3, 4};
                            combination(arr, 4);
                            return 0;
                        }


                      Добавлено
                      Как это переписать на MQL4 я не знаю.
                      Сообщение отредактировано: applegame -
                        Цитата applegame @


                        Строка
                        for(x = deep ? outers[deep - 1] + 1 : 0; x<size; x++) {

                        содержит в себе условие 'if', компилятор MQL4 жалуется на '?', видимо эта конструкция ему не понятна.
                        Как ее можно упростить?
                          ExpandedWrap disabled
                            int outer;
                            if(deep == 0)outer = 0;
                            else outer = outers[deep - 1] + 1;
                            for(x = outer: x < size; x++) {
                            Цитата applegame @


                            Большое Вам Спасибо за помощь с кодом!
                            Дальше я разберусь с тем как он работает и перепишу его в формате MQL4.
                              У вас используется "malloc(size * sizeof(int))", а в MQL4 malloc нет.
                              Можно ли как-нибудь обойтись без него?


                              void combination(int* arr, int size) {
                              int* outers = malloc(size * sizeof(int));
                              combinationImpl(arr, outers, size, 0);
                              free(outers);
                              }
                                applegame

                                У вас используется "malloc(size * sizeof(int))", а в MQL4 malloc нет.
                                Можно ли как-нибудь обойтись без него?


                                void combination(int* arr, int size) {
                                int* outers = malloc(size * sizeof(int));
                                combinationImpl(arr, outers, size, 0);
                                free(outers);
                                }
                                1 пользователей читают эту тему (1 гостей и 0 скрытых пользователей)
                                0 пользователей:


                                Рейтинг@Mail.ru
                                [ Script execution time: 0,0373 ]   [ 17 queries used ]   [ Generated: 15.05.24, 03:30 GMT ]