You are here:

C++/a question


i want to write a programme that shows all combination of 'n' variable,for instance for two variable 'a' and 'b',it prints:"aa","ab","ba","bb"
my question is that:
i should found a method for printing these combination or i can use RAND function?
i mean is it logical to use RAND function or it's better to use a method for finding the combination?
(indeed i want to know your idea as an expert)



For your case, using 2 letters going from 'a' say to 'z', using 2 for loops will get you call combinations (2 nested for loops is a total number of loops of the inner count times outer count).  For 'a' to 'z', there will be 26*26 pairs.  If you use rand() as you mention, you can get pairs, but you won't get all pairs for a potentially long run of the program, and you will definitely see duplicates.  If you want a generic way to get all combinations from say 2 to 5 I'd use an array and loop until the last array has been counted (if you go too big you get millions or billions of combinations - even with a length of 4 you have 26*26*26*26 of combinations!).  What I mean is like a odometer of a car.  For 4 letters, think about having 4 wheels that go from 'a' to 'z' instead of 0 to 9.  Spin in a loop adding to the first wheel.  When it gets to 'z', go back to 'a' and increase the next wheel. Repeat this until the last wheel is at 'z' (at which time the other 3 will be at 'z').  You will see all combinations from 'a' 'a' 'a' 'a' to 'z' 'z' 'z' 'z'.

However, for 2 letters, for loops is easiest:

char c1, c2;
int count = 0;

for(c1='a'; c1<='z'; ++c1)
 for(c2='a'; c2<='z'; ++c2)
   printf( "Combination %u - %c%c\n", ++count, c1, c2 );



All Answers

Answers by Expert:

Ask Experts


Bill A


I can answer questions about C++, programming algorithms, Windows programming in MFC (which is C++). I cannot answer questions about STL (templates) and I have no experience with Linux. I do enjoy reviewing code and critiquing it or finding problems in it. I will also gladly show better algorithms or methods if you want to take advantage of that.


I've developed a commercial embedded C compiler/assembler and IDE with debugger toolset, of which the IDE and debugger are written in C++. I work in the industry writing high tech embedded programs and Windows programs to communicate with the embedded devices.

Book: Embedded Systems Design using the Rabbit 3000 Microprocessor Authored Chapter 10 in its entirety.

BS Computer Engineering

©2016 All rights reserved.