I'm practicing recursion, and am trying to use it to constantly add individual digits in a number until there is only 1 digit left.
Basically, if the number is 84, it becomes 8+4 = 12 which then becomes 1 + 2 = 3.
Below is my attempt on it. Not sure what I'm missing..
const weirdSum = (num) => {
let result = 0;
const split = num.toString().split('');
if(split.length > 1){
for(let i=0;i<split.length;i++){
result = result + (split[i]*1);
}
weirdSum(result); // pass result as argument, which will be split.
}
return result; // return result if split.length is 1
}
there are 2 mistakes, one you need to return weirdSum(result);
another you are returning result which is 0 you should return num
const weirdSum = (num) => {
let result = 0;
const split = num.toString().split('');
if(split.length > 1){
for(let i=0;i<split.length;i++){
result = result + (split[i]*1);
}
return weirdSum(result); // pass result as argument, which will be split.
}
return num; // return result if split.length is 1
}
console.log(weirdSum(84));
let weirdSum = num => {
const split = num.toString().split('');
if(split.length > 1){
const sum = split.reduce((acc, it) => parseInt(it) + acc, 0)
return weirdSum(sum);
}
return num;
}
console.log(weirdSum(84));
console.log(weirdSum(123456));
const weirdSum = (num) => {
let result = 0;
const split = num.toString().split('');
if(split.length > 1){
for(let i=0;i<split.length;i++){
result = result + (split[i]*1);
}
return weirdSum(result); // pass result as argument, which will be split.
}
return split[0]; // return result if split.length is 1
}
console.log(weirdSum(84))
I just changed your codes to works properly, I have no idea it is optimized or not.
You need ti return the split[0] when recursion stack ends not the result!
This function isn't anonymous but it solves your problem
function weirdSum(num) {
if(parseInt(num/10) == 0) {
return num;
}
var num1 = 0;
while(num != 0) {
var d = parseInt(num%10);
num1=num1+d;
num=parseInt(num/10);
}
return weirdSum(num1);
}
How it works ?
Any single digit number when divided by 10 gives 0 as quotient ( parsing to int is required ), function exists when this condition is met ( the first if ).
In the while loop I'm extracting digits of the number ( starting from the last digit ), when we divide a number by 10, the remainder is always the same as the last digit, then we are adding this to the new num ( num1 ).
In the last step of the while loop, we are shortening the number by removing is last digit by dividing it by 10 and repacing the old num1 by quoatient.
const weirdSum = num => {
// figure out the sum
const sum = [...num + ""].reduce((a, e) => a + (e - 0), 0);
// recurse if necessary
return sum < 10 ? sum : weirdSum(sum);
}
console.log(weirdSum(84));
Related
Here's the question:
A Narcissistic Number is a positive number which is the sum of its own digits, each raised to the power of the number of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10).
For example, take 153 (3 digits), which is narcisstic:
1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
Your code must return true or false (not 'true' and 'false') depending upon whether the given number is a Narcissistic number in base 10.
My Code is:
function narcissistic(value) {
let vLen = value.length;
let sum = 0;
for (let i = 0; i < vLen; i++) {
sum += Math.pow(value[i], vLen);
}
if (sum == value) {
return true;
} else {
return false;
}
}
But I'm getting errors. What should I do?
Numbers don't have .length, convert to string first
vLen[i], you cant treat a number as array, again, convert to string to use that syntax.
The return can be simplefied to return (sum === value);
function narcissistic(value) {
let sVal = value.toString();
let vLen = sVal.length;
let sum = 0;
for (let i = 0; i < vLen; i++) {
sum += Math.pow(sVal[i], vLen);
}
return (sum === value);
}
console.log(narcissistic(153));
console.log(narcissistic(111));
Well... There are several things wrong with this code, but I think there is mostly a problem with the types of your input.
I'll show you how you can cast the types of your input to make sure you work with the types you need:
Also... You should try to avoid using the == operator and try to use === instead (same goes for != and !==), because the == and != don't try to match the types, resulting in sometimes unpredictable results
function narcissistic(value) {
valueStr = String(value);
let vLen = valueStr.length;
let sum = 0;
for (let i = 0; i < vLen; i++) {
sum += Number(valueStr[i]) ** vLen;
}
if (sum === value) {
return true;
} else {
return false;
}
}
if(narcissistic(153)) {
console.log("narcissistic(153) is true!") // expected value: true
}
All the first 9 digits from 1 to 9 is Narcissistic number as there length is 1 and there addition is always same.
So, first we are checking weather the number is greater than 9 or not.
if(num>9) =>false than it's a narcissistic number.
-if(num>9) =>true than we have to split number into digits for that I have used x = num.toString().split('');. Which is first converting number to String and than using split() function to split it.
Than , we are looping through each digit and digitsSum += Math.pow(Number(digit), x.length); adding the power of digit to const isNarcissistic = (num) => { let x = 0; let digitsSum.
at the end, we are comparing both num & digitsSum if there are matched than number is narcissistic else not.
const isNarcissistic = (num) => {
let x = 0;
let digitsSum = 0;
if (num > 9) {
x = num.toString().split('');
x.forEach(digit => {
digitsSum += Math.pow(Number(digit), x.length);
});
if (digitsSum == num) {
return true;
} else {
return false;
}
} else {
return true;
}
}
console.log(isNarcissistic(153));
console.log(isNarcissistic(1634));
console.log(isNarcissistic(1433));
console.log(isNarcissistic(342));
I have a recursive function that checks if a string is a palindrome, but my assignment asks me to count the number of palindromes in a string (for example kayak has 2).
I'm really confused about how I can implement a recursive function that counts the number of palindromes. Here's my current code:
function isPalindrome(string) {
if (string.length <= 1) {
return true;
}
let [ firstLetter ] = string;
let lastLetter = string[string.length - 1];
if (firstLetter === lastLetter) {
let stringWithoutFirstAndLastLetters = string.substring(1, string.length - 1);
return isPalindrome(stringWithoutFirstAndLastLetters);
} else {
return false;
}
}
When the function gets a palindrome it is easy:
Record the input
Try again without the edges
Stop when input is three characters or less
"kayak" -> "aya"
If the input isn't a palindrome try "both ends" recursively e.g. with "kayam" try with both "kaya" and "ayam" and keep going...
We stop the recursion when a string is 3 (or less) characters. A single character is not a palindrome and checking whether a two or three characters string is a palindrome is trivial.
kayam
|
+-------------+
| |
kaya ayam
| |
+-------+ +--------+
| | | |
kay aya aya yam
const reverse =
([...xs]) =>
xs.reverse().join("");
const is_palindrome =
a =>
a.length === 1 ? false
: a.length <= 3 ? a[0] === a[a.length-1]
: a === reverse(a);
const find_palindromes = str => {
const scan =
(x, xs = []) =>
x.length <= 3 ? xs.concat(is_palindrome(x) ? x : [])
: is_palindrome(x) ? xs.concat
( x
, scan(x.slice(1, -1))
)
: xs.concat
( scan(x.slice(0, -1))
, scan(x.slice(1))
);
return [...new Set(scan(str))];
};
console.log(find_palindromes("kayak").join());
console.log(find_palindromes("kayakkayak").join());
console.log(find_palindromes("kayakcanoe").join());
console.log(find_palindromes("kayam").join());
console.log(find_palindromes("appal").join());
console.log(find_palindromes("madamimadam").join());
console.log(find_palindromes("madamimadamkayak").join());
I think the accepted answer does not actually work. It will not count palindromes unless they are centered in the string and will count substrings that are not palindromes if as long as they start and end with the same letter. The answer from CertainPerformance would probably work but I think it would result in checking a lot of strings that don't need to be checked. Here's what I came up with, I think it works for the extra tests I've added.
function countPalindromes(string) {
if (string.length <= 1) {
return 0;
}
count = 0
for ( var i = 0; i < string.length; i++ ) {
count += countPalindromesCenteredAt(string, i)
count += countPalindromesCenteredAfter(string, i)
}
return count
}
function countPalindromesCenteredAt(string, i) {
count = 0
for ( var j = 1; i-j>=0 && i+j < string.length; j++ ) {
if (string.charAt(i-j) === string.charAt(i+j)) {
count += 1
}
else {
return count
}
}
return count
}
function countPalindromesCenteredAfter(string, i) {
count = 0
for ( var j = 1; i-j>=0 && i+j < string.length; j++ ) {
if (string.charAt(i-j+1) === string.charAt(i+j)) {
count += 1
}
else {
return count
}
}
return count
}
console.log(countPalindromes("kayak"));
console.log(countPalindromes("aya"));
console.log(countPalindromes("kayakcanoe"));
console.log(countPalindromes("kcanoek"));
One method would be to first get all substrings, then validate each:
getAllSubstrings('kayak').filter(str => str.length >= 2 && isPalindrome(str))
function getAllSubstrings(str) {
var i, j, result = [];
for (i = 0; i < str.length; i++) {
for (j = i + 1; j < str.length + 1; j++) {
result.push(str.slice(i, j));
}
}
return result;
}
function isPalindrome(string) {
if (string.length <= 1) {
return true;
}
let [ firstLetter ] = string;
let lastLetter = string[string.length - 1];
if (firstLetter === lastLetter) {
let stringWithoutFirstAndLastLetters = string.substring(1, string.length - 1);
return isPalindrome(stringWithoutFirstAndLastLetters);
} else {
return false;
}
}
console.log(
getAllSubstrings('kayak').filter(str => str.length >= 2 && isPalindrome(str))
);
Here's an answer similar to that from CertainPerformance, but using recursion for the helper functions:
const getSubstrings = (str) =>
str .length == 0
? []
: [
... str .split ('') .map ((_, i) => str .slice (0, str .length - i)),
... getSubstrings (str .slice (1))
]
const isPalindrome = (str) =>
str .length < 2
? true
: str [0] === str .slice (-1) [0] && isPalindrome (str .slice (1, -1))
const getPalindromicSubstrings = (str) =>
getSubstrings (str)
.filter (s => s.length > 1)
.filter (isPalindrome)
const countPalindromicSubstrings = (str) =>
getPalindromicSubstrings (str) .length
const countUniquePalindromicSubstrings = (str) =>
new Set(getPalindromicSubstrings (str)) .size
console .log (getPalindromicSubstrings ('madamimadam'))
console .log (countPalindromicSubstrings ('madamimadam'))
console .log (countUniquePalindromicSubstrings ('madamimadam'))
.as-console-wrapper {max-height: 100% !important; top: 0}
getSubstrings does just what you'd expect. getSubstrings('abcd') returns ["abcd", "abc", "ab", "a", "bcd", "bc", "b", "cd", "c", "d"].
isPalindrome says that the empty string and single-character strings are automatically palindromes and that for another string we check that the two end characters match, recurring on the remainder.
getPalindromicSubstrings finds all the substrings that are palindromes, skipping those of length 1.
countPalindromicSubstrings returns a count of those.
countUniquePalindromicSubstrings uses a Set to filter out duplicates and returns that count.
We could also easily write a getUniquePalindromicSubstrings in a similar manner if needed.
getSubstrings is the only function with any complexity. It operates by repeatedly slicing our string from to a value varying from length down to 1, then recurring on the string starting with the second character, stopping when our input is empty.
I tried to use a recursive function to reverse a number it works but for one call only it's because of scoping i guess but i don't know how to fix it
let num;
let reversed='';
let result;
function reverseNum(n){
for(let i =0; i<n; i++){
num = n%10; // get the last digit e.g 352 %10 = 2
reversed+= num
result = parseInt(n / 10); // remove last digit e.g. parseInt(352/10) = 35
reverseNum(result);
if(result ===0){
break;
}
}
return reversed;
}
You need the num, reversed, and result variables to be created anew each time the function is called externally. Here's one simple tweak, by defining the recursive function inside the top reverseNum function:
function reverseNum(n) {
let num;
let reversed = '';
let result;
const recurse = (n) => {
for (let i = 0; i < n; i++) {
num = n % 10; // get the last digit e.g 352 %10 = 2
reversed += num
result = parseInt(n / 10); // remove last digit e.g. parseInt(352/10) = 35
recurse(result);
if (result === 0) {
break;
}
}
return reversed;
};
return recurse(n);
}
console.log(reverseNum(1234));
console.log(reverseNum(1234));
But a more elegant method would be:
function reverseNum(n, str = String(n)) {
const thisDigit = str[str.length - 1];
const recursiveResult = str.length === 1 ? '' : reverseNum(str.slice(0, str.length - 1));
return Number(thisDigit + recursiveResult);
}
console.log(reverseNum(1234));
console.log(reverseNum(1234));
function reverse(number){
let index = 0 ;
let reversed = '';
let max = `${number}`.toString().length-1;
while(index <= max ){
reversed += `${number}`.charAt(max-index)
index ++;
}
return reversed;
}
console.log(reverse(546))
CertainPerformance has explained why your code wasn't working.
Here is another implementation, one I find reasonably simple:
const reverseNum = (n) =>
n < 10
? String(n)
: String (n % 10) + reverseNum (Math .floor (n / 10))
console .log (reverseNum (8675309))
Note that this returns a String rather than a Number. If we wanted to, we could make this a private function and make a public function one which called this and converted the result back into a number. But that would have the weird effect that reversing, say, 1000 would yield 1, since 0001 is simplified to 1. And that would mean that when you reverse again, you don't get anything like your original value. So I choose to keep with a String.
Of course if we're going to do String reversal, perhaps we're better off just using a String reversal function in the first place:
const reverseStr = (s) =>
s.length == 0
? ''
: reverseStr (s .slice (1)) + s [0]
const reverseNum = (n) =>
reverseStr (String(n))
console .log (reverseNum (8675309))
Or if we weren't interested in doing this recursively, we could just write the more common string reversal function:
const reverseStr = (s) =>
s .split ('') .reverse () .join ('')
const reverseNum = (n) =>
reverseStr (String (n))
console .log (reverseNum (8675309))
Given Problem:
Write a function called "sumDigits".
Given a number, "sumDigits" returns the sum of all its digits.
var output = sumDigits(1148);
console.log(output); // --> 14
If the number is negative, the first digit should count as negative.
var output = sumDigits(-316);
console.log(output); // --> 4
My code:
function sumDigits(num) {
return num.toString().split("").reduce(function(a, b){
return parseInt(a) + parseInt(b);
});
}
My code solves the problem for positive integers. Any hints on how should I go about solving the problem for negative integers? Please and thanks.
Edit: And what if the given number is 0? Is it acceptable to add an if statement to return 0 in such cases?
Check to see if the first character is a -. If so, b is your first numeral and should be negative:
function sumDigits(num) {
return num.toString().split("").reduce(function(a, b){
if (a == '-') {
return -parseInt(b);
} else {
return parseInt(a) + parseInt(b);
}
});
}
You could use String#match instead of String#split for a new array.
function sumDigits(num) {
return num.toString().match(/-?\d/g).reduce(function(a, b) {
return +a + +b;
});
}
console.log(sumDigits(1148)); // 14
console.log(sumDigits(-316)); // 4
Somebody who is looking for a solution without reduce functions etc. can take this approach.
function sumDigits(num) {
var val = 0, remainder = 0;
var offset = false;
if (num <0) {
offset = true;
num = num * -1;
}
while (num) {
remainder = num % 10;
val += remainder;
num = (num - remainder) / 10;
}
if (offset) {
val -= 2 * remainder;//If the number was negative, subtract last
//left digit twice
}
return val;
}
var output = sumDigits(-348);
console.log(output);
output = sumDigits(348);
console.log(output);
output = sumDigits(1);
console.log(output);
//Maybe this help: // consider if num is negative:
function sumDigits(num){
let negativeNum = false;
if(num < 0){
num = Math.abs(num);
negativeNum = true;
}
let sum = 0;
let stringNum = num.toString()
for (let i = 0; i < stringNum.length; i++){
sum += Number(stringNum[i]);
}
if(negativeNum){
return sum - (Number(stringNum[0]) * 2);
// stringNum[0] has the "-" sign so deduct twice since we added once
} else {
return sum;
}
}
I have an array as
arr = [1,2,3,4,6,7,8,9]
Now I want to check if the values in the array are consecutive.
Being more specific, I want this
First Check gives first and second element are consecutive and the next element is not consecutive then the algo must return the first element from where the consecutive number started
Like
First Check will give 1
Second Check will give 6
and so on...
Please help
Thanks in advance
/**
* Given an array of number, group algebraic sequences with d=1
* [1,2,5,4,8,11,14,13,12] => [[1,2],[4,5],[8],[11,12,13,14]]
*/
import {reduce, last} from 'lodash/fp';
export const groupSequences = (array) => (
reduce((result, value, index, collection) => {
if (value - collection[index - 1] === 1) {
const group = last(result);
group.push(value);
} else {
result.push([value]);
}
return result;
}, [])(array)
);
/**
* Given an array of number, group algebraic sequences with d=1
* [1,2,3,4,5,6] => true
* [1,2,4,5,6] => false
*/
const differenceAry = arr.slice(1).map(function(n, i) { return n - arr[i]; })
const isDifference= differenceAry.every(value => value == 1)
console.log(isDifference);
One sidenote is that you want to call it multiple times, so each call should know which array it's working on and what the previous offset in that array was. One thing you can do is to extend the native Array object. [Demo]
Array.prototype.nextCons = (function () {
var offset = 0; // remember the last offset
return function () {
var start = offset, len = this.length;
for (var i = start + 1; i < len; i++) {
if (this[i] !== this[i-1] + 1) {
break;
}
}
offset = i;
return this[start];
};
})();
Usage
var arr = [1,2,3,4,6,8,9];
arr.nextCons(); // 1
arr.nextCons(); // 6
arr.nextCons(); // 8
Check if all numbers in array are consecutives:
Updated March 2022
const allConsecutives = (arr) =>{
if(arr.some(n=> typeof n !== "number" || Number.isNaN(n))) return false;
return arr.every((num, i)=> arr[i+1]-num === 1 || arr[i+1] === undefined)
}
pseudo code:
int count = 0
for i = 0 to array.length - 2
if {array[i + 1] - array[i] = 1 then
count+=1
return i
else count=0}
const array1 = [1,2,3];
const sum = array1.reduce((accumulator, currentValue) =>{
return accumulator + currentValue;
});
const max = Math.max(...array1);
maximum = max
if(sum == maximum * (maximum+1) /2) {
console.log(true);
} else {
console.log(false);
}