Skip to content

Instantly share code, notes, and snippets.

@klauszhang
Last active November 13, 2017 07:17
Show Gist options
  • Save klauszhang/5c26ac963a2538e92912ca9c24253f30 to your computer and use it in GitHub Desktop.
Save klauszhang/5c26ac963a2538e92912ca9c24253f30 to your computer and use it in GitHub Desktop.
a functional appropach
function getNumber() {
return Math.floor(Math.random() * 10000);
}
function getFourDigitNum(pin) {
if (pin <= 1000) {
getFourDigitNum(getNumber());
}
return pin;
}
function getStuffInShape(pin) {
const stringArr = pin.toString().split('');
const stringSet = new Set(stringArr);
const numArr = stringArr.map(item=>parseInt(item));
const isValid =
numArr[1] - numArr[0] !== 1 &&
numArr[2] - numArr[1] !== 1 &&
numArr[3] - numArr[2] !== 1;
if (stringSet.size === 4 && isValid) {
return pin;
}
return getStuffInShape(
getFourDigitNum(getNumber())
);
}
function getSolution(howMany) {
const result = new Set();
return function getEach(pin) {
if (typeof pin === 'undefined') {
console.log('error!');
}
result.add(pin);
if (result.size !== howMany) {
getEach(
getStuffInShape(
getFourDigitNum(getNumber())
)
);
}
return result;
};
}
// console.log(
// Array.from(
// getSolution(1000)(
// getStuffInShape(
// getFourDigitNum(getNumber())
// )
// )
// ).join(',')
// );
module.exports = getSolution(1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment