Created
May 17, 2021 02:35
-
-
Save CarlaTeo/73145597867b79af526bc07d1c36489a to your computer and use it in GitHub Desktop.
[JS] Colorful Numbers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Source problem: https://algorithms.tutorialhorizon.com/colorful-numbers/ | |
// Objective: Given a number, find out whether its colorful or not. | |
// Colorful Number: When in a given number, product of every digit of a sub-sequence are different. That number is called Colorful Number. | |
// Given Number : 3245 | |
// Output : Colorful | |
// Number 3245 can be broken into parts like 3 2 4 5 32 24 45 324 245. | |
// this number is a colorful number, since product of every digit of a sub-sequence are different. | |
// That is, 3 2 4 5 (3*2)=6 (2*4)=8 (4*5)=20, (3*2*4)= 24 (2*4*5)= 40 | |
// Given Number : 326 | |
// Output : Not Colorful. | |
// 326 is not a colorful number as it generates 3 2 6 (3*2)=6 (2*6)=12. | |
function isColorful(number) { | |
const products = new Set(); | |
for(let i = 0; i < number.length; i++) { | |
for(let j = i + 1; j <= number.length; j++) { | |
const subNumber = number.slice(i, j); | |
const product = subNumber.split("").reduce((prod, num) => { | |
return prod * Number(num); | |
} , 1); | |
if(products.has(product)) return false; | |
else products.add(product); | |
} | |
} | |
return true; | |
} | |
// -------------------------------- Test ------------------------------ // | |
console.log(isColorful('3245')) // true | |
console.log(isColorful('123')) // false | |
console.log(isColorful('326')) // false | |
console.log(isColorful('')) // true | |
console.log(isColorful('9')) // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment