i want to find next smallest palindrome but im not allowed to use some built-in function. so i create this code :
function reverse(nums) {
var reverse = "";
for (var i = String(nums).length - 1; i >= 0; i--) {
reverse += String(nums)[i];
}
return reverse;
}
function Palindrome(num) {
if (String(num).length < 2) {
return num + 1
}
for (var i = num + 1; i < num + 3; i++) {
if (String(i) === reverse(num)) {
return i
}
}
}
console.log(Palindrome(23)) // 32
first function will reverse the string and the second will find the nearest palindrome.
on the test case, the result are supposed to be 33.
but when i run the code the result is :
console.log(Palindrome(23))// 32
it only reversing the numbers.
could you help me to find what could be wrong from my code?
thanks before.
correct code is:
function reverse(nums) {
var reverse = "";
for (var i = String(nums).length - 1; i >= 0; i--) {
reverse += String(nums)[i];
}
return reverse;
}
function Palindrome(num) {
if (String(num).length < 2) {
return num + 1
}
for (var i = num + 1; ; i++) {
if (String(i) === reverse(i)) {
return i
}
}
}
console.log(Palindrome(23))
you were doing reverse of num in place of i
The check should be for reverse of i, not reverse of num. Try the following condition.
if (String(i) === reverse(i)) { ... }
you don't need to reverse, as it would take O(n), if you iterate and check only for half the length of num, you can improve performance.
Here I'm matching the digits of number at places from beginning and the end.
So, the first digit should match the last, second should match the second last and so on. I any such match fails the number is not palindrome.
And this, way you only have to go upto half the length of number (after converting it to string);
function Palindrome(num) {
num = "" + num;
for(var i = 0; i < num.length/2; i++)
{
if(num[i] != num[num.length - (i+1)])
return false;
}
return true;
}
function nextPalindrome(num)
{
while(!Palindrome(++num)){}
return num;
}
console.log(nextPalindrome(22));
console.log(nextPalindrome(23));
console.log(nextPalindrome(232));
console.log(nextPalindrome(122));
console.log(nextPalindrome(1001));
I have used while loop here. You can try this:
function reverse(nums) {
var reverse = "";
for (var i = String(nums).length - 1; i >= 0; i--) {
reverse += String(nums)[i];
}
return reverse;
}
function Palindrome(num) {
if (String(num).length < 2) {
return num + 1;
}
var i=num;
while(i!=0) {
if (String(i++) === reverse(num)) {
return --i;
}
num=i;
}
}
console.log(Palindrome(23));
Related
I developed a logic for the above problem but i couldnt get the desired result.
function thirdOccurence(string){
var count = 0;
var i=0;
var result = 0;
while(i<string.length){
if(string[i]=='e' && string[i+1]=='f' && string[i+2]=='g')
{
count = count+1;
i+3;
if(count==3)
{
result = i+1;
break;
}
}
else
i++;
}
}*
here the string is the input - abcefgacefgabcceftyefghjklop
-output should be 20 since we need to find position. I have a working code but with a different logic. But i need to know why this is not working.
The problem was with the line where you increment the i variable by 3: i += 3. This meant you jumped 3 indexes forward, before the final condition if(count==3). But if you increment i by 3 after this final condition - everything works as expected :)
function thirdOccurence(string) {
var count = 0;
var i = 0;
var result = 0;
while (i < string.length) {
if (string[i] === "e" && string[i + 1] === "f" && string[i + 2] === "g") {
count += 1;
if (count === 3) {
result = i + 1;
break;
}
i += 3;
} else {
i++;
}
}
return result
}
console.log('result should be 20:', thirdOccurence('abcefgacefgabcceftyefghjklop'))
My function takes an integer array of divisors, a low number and a high number as parameters. It prints the range between a low and a high number.
If the number in the range is divisible by all elements of the array, print "all match".
If at least one number matches, print "one match".
If no number matches, print the number.
But, I can't figure out how to write my if-else statements properly. It only prints the numbers that match. When I change the else-if statement, it prints all the numbers twice.
function allFactors(factors, num){
var nums = [];
for(var i = 0; i < factors.length; i++) {
var factor = factors[i];
if(num % factor === 0){
nums.push(factor);
}
}
if(nums.length === factors.length){
return true;
}
return false;
}
//console.log(allFactors([2,3],6))
function isFactor(num, factor) {
if(num % factor === 0) {
return true;
}
return false;
}
function matches(factors, low, high) {
var skipper = false
for(var i = low; i <= high; i++) {
if(allFactors(factors,i)){
console.log(i + " match_all")
} else {
for(var j = 0; j < factors.length;j++) {
var factor = factors[j];
if(isFactor(i,factor)) {
console.log(i + " match_one");
skipper = true
} else {
if(isFactor(i,factor)) {continue}
console.log(i)
}
}
}
}
}
matches([2,3],1,6)
Try breaking from the loops once you know that One factor matches.
function matches(factors, low, high) {
var skipper = false;
for(var i = low; i <= high; i++) {
if(allFactors(factors,i)){
console.log(i + " match_all")
} else {
for(var j = 0; j < factors.length;j++) {
var factor = factors[j];
if(isFactor(i,factor)) {
console.log(i + " match_one");
skipper = true;
// break here because we know that at least one factor matches
// and print "match_one"
break;
} else {
// number not matched
console.log(i);
}
}
}
// use skipper variable you assigned above to break out of outer loop
if(skipper){
break;
}
}
}
The answer I'm getting is not the correct one (correct answer is 906609). Please help me understand where I am going wrong. I want the while loop to go from 100 to 999 while multiplying itself against the current i value before the loop increments it.
// A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
// Find the largest palindrome made from the product of two 3-digit numbers.
var pali = [];
function palindrome() {
for (var i = 100; i <= 999; i++) {
var counter = 100;
while (counter <= 999) {
var result = counter * i;
if (result.toString() === result.toString().split("").reverse().join("")) {
pali.push(result);
}
counter++;
}
}
return pali[pali.length - 1];
}
console.log(palindrome());
You're going to have to sort the array in ascending order if you want the last one to be the highest:
pali.sort(function(a, b){return a-b});
Using that, I get 906609.
Lengthier, but faster. Starting at the max values and working down, short circuiting when we won't find higher values:
function largestPalindromeProduct(lower, upper) {
var palindrome = 0;
var outerLow = lower;
var outer = upper;
while (outer > outerLow) {
var inner = upper;
var innerLow = lower;
while (inner > innerLow) {
var result = inner * outer;
if (result + "" === (result + "").split("").reverse().join("")) {
if (result > palindrome) {
palindrome = result;
outerLow = inner; // Don't go lower than this value in the outer, no need!
}
inner = innerLow; // short-circuit this loop
}
inner--;
}
outer--;
}
return palindrome;
}
console.log(largestPalindromeProduct(100, 999))
I think the easiest way will be to add a If statement.
function palindrome()
{
var max = 0;
for (var i = 999; i >= 100; i--)
{
var counter = 999;
while (counter >= 100)
{
var result = counter * i;
if (result.toString() === result.toString().split("").reverse().join(""))
{
if(result>max)
{
max = result;
}
}
counter++;
}
}
return max;
}
While working through some Coderbyte challenges, I was able to solve the following problem recursively, but was hoping to get some feedback on how I can improve it.
Have the function AdditivePersistence(num) take the num parameter being passed which will always be a positive integer and return its additive persistence which is the number of times you must add the digits in num until you reach a single digit.
For example: if num is 2718 then your program should return 2 because
2 + 7 + 1 + 8 = 18 and 1 + 8 = 9 and you stop at 9.
My submitted, working recursive solution is below. How can I place "count" into my function without letting it get "reset" every time I recurse?
var count = 0;
function AdditivePersistence(num) {
count = 0;
if (num < 10) {
return count;
}
if (num > 10) {
count++;
AdditivePersistence('' + num.split("").reduce(function(a,b) {
return parseInt(a) + parseInt(b)
}));
}
}
Here's my broken attempt at moving the counter within the function... would appreciate any pointers for my beginner-self. Beyond just fixing the code, I'd love it if there are other great methods for solving this puzzle!
function AdditivePersistence(num) {
var count = 0;
(function recurse(num) {
if (num < 10) {
return count;
}
if (num > 10) {
count++;
recurse('' + num.split("").reduce(function(a,b) {
return parseInt(a) + parseInt(b);
}));
}
})();
return count;
}
Edit: I just tried with a while loop below
function AdditivePersistence(num) {
var count = 0;
while (num >= 10) {
count++
num = num.toString().split('').reduce(function(a,b) {
return parseInt(a) + parseInt(b);
})}
return count;
}
Many thanks in advance!
The idea is simple
AdditivePersistence(n):
if n < 10
return 0
else
return 1 + AdditivePersistence(sum-of-digits(n))
Strictly speaking, there's no need for the recursion here - that's essentially a normal while loop.
I'm going to extend #georg's answer and provide a full implementation
var additivePersistance = (function () {
function sumOfDigits (n) {
var ret = 0;
n.toString().split('').forEach(function (i) {
ret += parseInt(i, 10);
});
return ret;
}
return function additivePersistance (n) {
if (n < 10) {
return 0;
}
return additivePersistance(sumOfDigits(n)) + 1;
}
}());
This implementation hides the sumOfDigits as a helper method using a closure.
additivePersistance(2718); // 2
This closure idea can also serve to create a psudo static variable in the recursive function. Follow this form.
var func = (function () {
var staticCounter = 0;
return function func() {
if (staticCounter++ > 20) {
return 0;
}
return func() + 1;
};
}());
Here the body of the inner func method is using the variable staticCounter accross all calls to the outter func.
var count = 0;
function AdditivePersistence(num)
{
// make the number into a string so that each digit can be taken
var num_string = num.toString();
// this will hold each digit
var numbers = [];
// iterate through each digit as a character
for(var i = 0; i < num_string.length; ++i)
{
// add the character converted to a number into the numbers array
numbers.push(parseInt(num_string[i]));
}
// this will hold the value of all the digits added together
var total = 0;
// iterate through the digits
for(var i = 0; i < numbers.length; ++i)
{
// add each digit to the total
total += numbers[i];
}
// if larger than the total
if(total > 10)
{
// increase the count
++count;
// redo it again
AdditivePersistence(total);
}
else
{
// return the total amount of tries
return (++count);
}
}
I'm writing a function that takes a string as an argument, checks it for a given character (say "B" in this case), and then returns an integer that reflects the number of times that character appeared. I'm aware that this can be done using regex and such, but the tutorial I'm using has so far made no mention of regex. Code time:
function countBs(string) {
var i = 0;
var n = 0;
var position = string.charAt(n);
while (i < string.length) {
if (string.charAt(n) == "B")
n += 1;
i++; //This line causes the following else statement to throw a syntax error. But it's the only way I can think of to have the loop continue iteration *while* checking for equivalence to "B"
else
i++;
return n;
}
}
And then check with console.log(countBs("ABBA"));
Your code is quite broken.
function countBs(string) {
var i = 0;
var n = 0;
// var position = string.charAt(n); // REMOVE--NOT NECESSARY
while (i < string.length) {
if (string.charAt(i) == "B") // i, NOT n
n++; // CONSISTENCY IN ADD-ONE SYNTAX
// i++; // INCREMENT ONCE BELOW
//else
i++;
}
return n; // MUST GO OUTSIDE THE LOOP
}
Correct code would therefore be:
function countBs(string) {
var i = 0;
var n = 0;
while (i < string.length) {
if (string.charAt(i) == "B") n++;
i++;
}
return n;
}
There's nothing particularly wrong with using a while loop, but a for would be more natural:
function countBs(str) {
var n = 0;
for (var i = 0; i < str.length; i++) if (str[i]== "B") n++;
return n;
}
Modern JS
For your reference, in modern JS, you could avoid the loops and variables. First, let's write a separate checking function:
function isB(c) { return c === 'B'; }
Then write
function countBs(str) {
return str . split('') . filter(isB) . length;
}
or, using reduce:
function countBs(str) {
return str.split('').reduce(function(cnt, c) {
return cnt + isB(c);
}, 0);
}
or, although you said you didn't want to use regexps:
function countBs(str) {
return (str.match(/B/g) || []) . length;
}
If you are writing in an ES6 environment, then using array comprehensions
function countBs(str) {
return [for (c of str) if (isB(c)) c] . length;
}
Try wrapping it in curly braces:
if (string.charAt(n) == "B")
{ n += 1;
i++;
}
An else requires a previous if, and no other statements in between. i++ was outside the if.
Here's my answer
function countBs(Str)
{
let char = "B" ;
return String(Str).split(char).length - 1;
}
function countChar(Str, char)
{
return String(Str).split(char).length - 1;
}