diff --git a/14. happinessNumber/happinessNumber.js b/14. happinessNumber/happinessNumber.js new file mode 100644 index 0000000..6822051 --- /dev/null +++ b/14. happinessNumber/happinessNumber.js @@ -0,0 +1,32 @@ +/* +PROBLEM + You will be given a string of characters containing only the following characters: "(", ")", ":" + Create a function that returns a number based on the number of sad and happy smiley faces there is. + * The happy faces :) and (: are worth 1. + * The sad faces :( and ): are worth -1. + * Invalid faces are worth 0. + EXPLANATION : + happinessNumber(":):(") ➞ -1 + The first 2 characters are :) +1 Total: 1 + The next 2 are ): -1 Total: 0 + The last 2 are :( -1 Total: -1 +*/ + +function happinessNumber(smilies) { + let arr = smilies.split(''); + let count = 0; + for (var i = 0; i < arr.length; i++) { + if (arr[i] + arr[i + 1] == ':)') count += 1; + + if (arr[i] + arr[i + 1] == '(:') count += 1; + + if (arr[i] + arr[i + 1] == '):') count -= 1; + + if (arr[i] + arr[i + 1] == ':(') count -= 1; + } + return count; +} + +// console.log(happinessNumber(":):(")) // -1 +// console.log(happinessNumber("(:)")) // 2 +// console.log(happinessNumber("::::")) // 0 \ No newline at end of file diff --git a/README.md b/README.md index 80773fb..538504c 100644 --- a/README.md +++ b/README.md @@ -85,6 +85,7 @@ __Algorithms practiced using JS__ 10. Caesar Cipher 11. Lexicographically equal or not 12. Fizz Buzz +14. happinessNumber ## Explanation <b>1. String reversing</b> @@ -1532,4 +1533,59 @@ const dist = dijkstra(graph, 6); console.log(dist); ``` -</p> \ No newline at end of file +</p> + + + +</p> +<hr> +<hr> + +<b>14. happinessNumber</b> + +__The Challenge:__ + +Hpiness Number Problem :) + +__Algorithmic Thinking:__ +``` text +PROBLEM + You will be given a string of characters containing only the following characters: "(", ")", ":" + Create a function that returns a number based on the number of sad and happy smiley faces there is. + * The happy faces :) and (: are worth 1. + * The sad faces :( and ): are worth -1. + * Invalid faces are worth 0. + EXPLANATION : + happinessNumber(":):(") ➞ -1 + The first 2 characters are :) +1 Total: 1 + The next 2 are ): -1 Total: 0 + The last 2 are :( -1 Total: -1 + +``` +__Implementation:__ + +```js + +function happinessNumber(smilies) { + let arr = smilies.split(''); + let count = 0; + for (var i = 0; i < arr.length; i++) { + if (arr[i] + arr[i + 1] == ':)') count += 1; + + if (arr[i] + arr[i + 1] == '(:') count += 1; + + if (arr[i] + arr[i + 1] == '):') count -= 1; + + if (arr[i] + arr[i + 1] == ':(') count -= 1; + } + return count; +} + +console.log(happinessNumber(":):(")) // -1 +console.log(happinessNumber("(:)")) // 2 +console.log(happinessNumber("::::")) // 0 + +``` + + +