简体   繁体   中英

calculate combinations of n length string and n characters in each position

Ok what i need to do is something like this:

lets say that user has written a string that has 4 characters '6262' , now each of the position can contain different number of characters, for example this is how many characters can be in each position:

  • pos. 1 - 4 different characters 6, 7, 8, 9
  • pos. 2 - 2 different characters 2, 3
  • pos. 3 - 4 different characters 6, 7, 8, 9
  • pos. 4 - 2 different characters 2, 3

now how to calculate in total how many combinations can we have based on 4 length string and respectively 4, 2, 4, 2 chars in each spot?

This is a simple MATH problem not at all connected with programming or code.

4^2 * 2^2 = 2^4 * 2^2 = 2^6 = 64 combinations.

TO make a clearer example how would you calculate how many combinations are in 4 positions and each has 10 possibilities?

it's 10^4 = 1000 which is exactly why there is 10000 numbers possible with 4 digits in numeric system with the base of 10. As you might sense now those numbers are 0000 = 0 to 9999.

EDIT: comment requested the function that calculates what I wrote above.

Pass in this function number of combinations per place and it will return number of total combinations to you:

function productAll() {
    var i;
    var product = 1;
    for (i = 0; i < arguments.length; i++) {
        product *= arguments[i];
    }
    return product;
}

For your example you would call a function like: productAll(4,2,4,3);

Although this isn't a programming problem, here's a programming solution:

var counter = 0;
var abcd = "";
for(a = 6; a <=9; a++) {
  for(b = 2; b <=3; b++) {
    for(c = 6; c <=9; c++) {
      for(d = 2; d <=3; d++) {
        counter++;
        abcd += a + "" + b + "" + c + "" + d + " ";
      }
    }
  }
}

In the end, counter is 64, as DanteTheSmith predicted. And abcd is every combination:

6262 6263 6272 6273 6282 6283 6292 6293 6362 6363 6372 6373 6382 6383 6392 6393 7262 7263 7272 7273 7282 7283 7292 7293 7362 7363 7372 7373 7382 7383 7392 7393 8262 8263 8272 8273 8282 8283 8292 8293 8362 8363 8372 8373 8382 8383 8392 8393 9262 9263 9272 9273 9282 9283 9292 9293 9362 9363 9372 9373 9382 9383 9392 9393 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM