Jump to content

Possible Letter Combinations


johnnyg24

Recommended Posts

I am looking to write a script that generates every possible combination of 4 different letters. I need to be able to represent a null value using 'x'.Each combination needs to have 4 characters separated by a '.'.Here's an example: A.B.C.DX.X.X.XX.X.X.DX.X.C.DX.B.C.DX.X.C.XX.B.X.XX.B.C.XA.X.X.XA.B.X.XA.B.C.XA.X.X.DA.X.C.XA.B.X.DX.B.C.DA.X.C.D The order of the letters will never change, so it doesn't need to generate a value of: d.c.b.a or anything like that. There should be 16 different combinations I think. Is there a way to use JavaScript to do this? Thanks.

Link to comment
Share on other sites

The letters don't really matter. They're just true or false. With four bits you can represent values from 0 to 16. We can use bitwise logic operators for that. The bitwise operator takes the binary value of a number and compares it with the binary value of another.

var str = "";for(i = 0; i < 16; i++) {  str += (i & 8 ? "A." : "X.");  str += (i & 4 ? "B." : "X.");  str += (i & 2 ? "C." : "X.");  str += (i & 1 ? "D\n" : "X\n");}alert(str);

Link to comment
Share on other sites

The number of possible combinations is n^x where n is how many possibilities for each slot (in this case, 2: a letter or null) and x is the number of slots (5 in the case of ABCDE) so the number of combinations is 2^5 or 32. In the code Ingolme showed you, just change the 16 to 32. If you want this to be dynamic or easily manipulated, you can create a function to do it:

function combinations(n, x) {   return Math.pow(n, x);} var str = "";for (i = 0; i < combinations(2, 5); i++) {   str += (i & 16 ? "A." : "X.");   str += (i & 8 ? "B." : "X.");   str += (i & 4 ? "C." : "X.");   str += (i & 2 ? "D" : "X");   str += (i & 1 ? "E\n" : "X\n");}alert(str);

Now all you have to do is change the 5 to whatever length you want. EDIT: Oops, forgot you'll also have to add another line in there for printing the E. I'm not sure if I've got the bitwise operations correct, but I'm sure Ingolme can verify.

Link to comment
Share on other sites

Thank you everyone for the help. Thought I would add my spin on this with a completely dynamic way of doing this based on an array of possible letters

function combinations(n, x) {   return Math.pow(n, x);}var att = ['A','B','C','D','E','F','G']var pw = []var n = 1for(p=0;p<att.length;p++){n = n * 2pw.push(combinations(2, att.length)/n)} var str = ""; for (i = 0; i < combinations(2, att.length); i++) {   var cnt = 0   for(l=0;l<att.length;l++){    if(l<att.length-1){   str += (i & pw[cnt] ? att[cnt] + "." : "X.");   cnt++}else{str += (i & pw[cnt] ? att[cnt] + "<br>" : "X<br>");   cnt++}   }}  document.getElementById('here').innerHTML = str

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...