Наши проекты:
Журнал · Discuz!ML · Wiki · DRKB · Помощь проекту |
||
ПРАВИЛА | FAQ | Помощь | Поиск | Участники | Календарь | Избранное | RSS |
[18.223.196.171] |
|
Сообщ.
#1
,
|
|
|
Ниже приведен код для массива из 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]); } // ----------------------------------------------------- } // ----------------------------------------------------- } // ----------------------------------------------------- } |
Сообщ.
#2
,
|
|
|
Рекурсией или шаблонами, если компайл-тайм достаточно
|
Сообщ.
#3
,
|
|
|
Цитата applegame @ Рекурсией Это понятно, хотелось бы увидеть исправленный код, тем более что здесь всего несколько строк. |
Сообщ.
#4
,
|
|
|
Хотя, вот именно такие циклы рекурсией не получится.
|
Сообщ.
#5
,
|
|
|
Сообщ.
#6
,
|
|
|
Вроде есть решение рекурсией, сейчас набросаю.
|
Сообщ.
#7
,
|
|
|
Цитата applegame @ Вроде есть решение рекурсией, сейчас набросаю. Возможно что-то наподобие последнего примера по линку: http://otvety.google.ru/otvety/thread?tid=19c7c28b27e095be Но не знаю как быть с принтами. Жду Вашего кода. |
Сообщ.
#8
,
|
|
|
Как-то так в общем:
http://ideone.com/N12H4c #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); } |
Сообщ.
#9
,
|
|
|
Цитата applegame @ Как-то так в общем: http://ideone.com/N12H4c #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, там синтаксис похож на Си, а у Вас написано С++. Это С или С++? |
Сообщ.
#10
,
|
|
|
Цитата atztek @ Это C++. Но на си переписывается очень просто:Это С или С++? #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 я не знаю. |
Сообщ.
#11
,
|
|
|
Цитата applegame @ Строка for(x = deep ? outers[deep - 1] + 1 : 0; x<size; x++) { содержит в себе условие 'if', компилятор MQL4 жалуется на '?', видимо эта конструкция ему не понятна. Как ее можно упростить? |
Сообщ.
#12
,
|
|
|
int outer; if(deep == 0)outer = 0; else outer = outers[deep - 1] + 1; for(x = outer: x < size; x++) { |
Сообщ.
#13
,
|
|
|
Цитата applegame @ Большое Вам Спасибо за помощь с кодом! Дальше я разберусь с тем как он работает и перепишу его в формате MQL4. |
Сообщ.
#14
,
|
|
|
У вас используется "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); } |
Сообщ.
#15
,
|
|
|
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); } |
Сообщ.
#16
,
|
|
|
Цитата atztek @ Можно завести глобальный массив соответствующего размера. У вас используется "malloc(size * sizeof(int))", а в MQL4 malloc нет. Можно ли как-нибудь обойтись без него? |
Сообщ.
#17
,
|
|
|
Цитата atztek @ а в MQL4 malloc нет а что есть? |
Сообщ.
#18
,
|
|
|
Цитата shm @ Цитата atztek @ а в MQL4 malloc нет а что есть? Команд типа malloc нет, но как уже предлагал applegame применительно к этому случаю можно создать массив необходимого размера. |