var allRegions = ['1', '2', '3', '4', '5', '6', '7'];
// to skip sequence of repeated letters.
var isSequence = /^([a-zA-Z0-9])\1+$/;
// to skip, if the combination has duplicates.
var hasDuplicates = /([a-zA-Z0-9]).*?\1/;
function isNotUniqueCombination(ex, rand) {
for (var n = 0; n < ex.length; n++) {
var e = ex[n];
var combinations = [
[e[0], e[1], e[2]],
[e[0], e[2], e[1]],
[e[1], e[0], e[2]],
[e[1], e[2], e[0]],
[e[2], e[0], e[1]],
[e[2], e[1], e[0]]
];
for (var i = 0; i < combinations.length; i++) {
var com = combinations[i];
if (com.join("") === rand.join("")) return true;
}
}
return false;
}
/**
* Return a random number without sequence of repeated letters & without excludes
* @param {String} array
* @param {String} excludes
*/
function getRandom(array, excludes) {
// Random number array
var randomNumber = [];
var excludesMap = excludes.map(function(e) {
return e.join("");
});
do {
// Generate random number
randomNumber = [
array[Math.floor(Math.random() * array.length)],
array[Math.floor(Math.random() * array.length)],
array[Math.floor(Math.random() * array.length)]
];
} while (excludesMap.indexOf(randomNumber.join("")) !== -1 || isSequence.test(randomNumber.join("")) || hasDuplicates.test(randomNumber.join("")) || isNotUniqueCombination(excludes, randomNumber));
return randomNumber;
}
var excludes = [
['2', '5', '7'],
['1', '3', '6']
];
// Test Case
// =========
for (var i = 0; i < 1e3; i++) {
var arr = getRandom(allRegions, excludes);
var div = document.createElement('div');
div.innerHTML = arr.join("");
document.body.appendChild(div);
// Check if the string contains a sequence of repeated letters of has duplicates
if (isSequence.test(arr.join("")) || hasDuplicates.test(arr.join("")) || isNotUniqueCombination(excludes, arr)) {
div.style.color = "#ff0000";
div.innerHTML += " [ sequence of repeated letters found || duplicates found ]";
document.body.appendChild(div);
break;
}
}
// ===