sorting an alphanum array using jQuery - javascript

i am trying to compare two arrays containing alphabets and numbers using jquery but a call to the function does nothing.
jQuery.compare = function (string2,string1) {
alert("comparing")
var i, j;
for ( i = 0, j=0; i < string2.length|| j<string1.length; ++i,++j) {
var n1 = 0,n2=0;
if ($.isNumeric(string2[i+1])) {
num=string2[i]
while ($.isNumeric(string2[i+1])) {
i++;
num += string2[i]
}
n1 = 1;
}
if ($.isNumeric(strin1[j])) {
num1 = string1[j]
while ($.isNumeric(string1[j+1])) {
j++;
num1 += string1[j]
}
n2 = 1;
}
if (n1 == 1) {
if (n2 = 1) {
if( parseInt(num1) - parseInt(num) !=0)
return parseInt(num1) - parseInt(num);
}
else
return 1;
}
else if (n2 = 1)
return -1;
else {
if(string2[i]-string1[j]!=0)
return string2[i]-string1[j]!=0;
}
}
if (j < string1.length)
return -1;
else
return 1;
}
Also i would like to know the best way to call this function. I would like to use something like string1.compare(string2) and replace string1 with 'this' in the above code fragment.
EDIT:
This is how i call the compare function.Here, colValues is an array of string.
$.fn.sort = function (colValues) {
alert("sorting")
var i;
for (i = 0; i < colValues.length; ++i) {
for (var j = 0; j < i - 1; ++j) {
alert("before compare")
if(colValues.compare(colValues[j],colValues[j + 1])) {
var temp = colValues[j];
colValues[j] = colValues[j + 1];
colValues[j + 1] = temp;
}
}
}
return colValues
}
if i replace
if(colValues.compare(colValues[j],colValues[j + 1]))
with
if(colValues[j]>colValues[j+1])
my sort function works.
i am a complete newbie at coding in jquery. There is probably some syntactical error. I dont really want any help with the algorithm just the syntax.
jsfiddle-checkout my code here
EDIT2:
i fixed everything thx to metadings.
heres what i had to change
1)
jQuery.compare
to
$.fn.compare
2)
if($.isNumeric(string2[i+1]))
to
if(jQuery.isNumeric(string2[i + 1]))
somehow the
while ($.isNumeric(string1[j+1]))
syntax worked without any changes
3)
parseInt(num1) - parseInt(num)
didnt work either as it returned NaN. To solve this problem i defined two var variables 'number1' and 'number2' and initialized them with 0's and assigned parseInt(num1) individually to the variables and then subtracted the new variables.

Related

Creating an Iterative - Javascipt

I have a recursive function below and I was just wondering how can I create an iterative (i.e. loops without recursion) for the same thing. I would really appreciate any help or suggestions thank you!
function countPalindromes(string, count) {
if (string.length <= 1) {
return count;
}
let [ firstLetter ] = string;
let lastLetter = string[string.length - 1];
if (firstLetter === lastLetter) {
let stringWithoutFirstAndLastLetters = string.substring(1, string.length - 1);
return countPalindromes(stringWithoutFirstAndLastLetters, count + 1);
} else {
return count;
}
}
console.log(countPalindromes("level", 0));
console.log(countPalindromes("aya", 0));
Took me a while, but this should work.
function countPalindromes(string, count) {
for (i = 0; i < Math.floor(string.length/2); i++) {
if (string.charAt(i) === string.charAt(string.length - i-1)) {count++};
}
return count;
}
console.log(countPalindromes("level", 0));
console.log(countPalindromes("aya", 0));
You can do something like this:
function countPalindromes(string) {
let count = 0;
for (let i = 0; i < Math.floor(string.length / 2); i++) {
const letterFromTheStart = string[i];
const letterFromTheEnd = string[(string.length - 1) - i];
if (letterFromTheStart !== letterFromTheEnd) {
break;
}
count++;
}
return count;
}
console.log(countPalindromes("level"));
console.log(countPalindromes("aya"));
The important parts are i < Math.floor(string.length / 2) and (string.length - 1) - i.
The first one assures the loop stops before or at the half of the string and the second gets the nth character starting from the string's end.
I didn't get your recursive palindrome function. Just converted the recursive one to iterative one.
function countPalindromes(string, count) {
if (string.length <= 1) {
return count;
}
let i = 0, j = string.length-1;
for (; i < j && string[i] == string[j]; i++, j--);
return i;
}
console.log(countPalindromes("level", 0));
console.log(countPalindromes("aya", 0));
You can reverse the string and compare letters until you hit a mismatch returning the last index that matched plus one.
function isPalindrome(word) {
const drow = word.split('').reverse();
for (i = 0; i < drow.length && drow[i] === word[i]; i++);
return i;
}
console.log(isPalindrome("level"));

Check Digit Sum Javascript- recursion [duplicate]

This question already has answers here:
Adding digits from a number, using recursivity - javascript
(6 answers)
Closed 8 months ago.
Looking for Javascript solution in recursion to get the sum of all digits in number until single digit come as result
For example, for the number is "55555" the sum of all digits is 25. Because this is not a single-digit number, 2 and 5 would be added, and the result, 7.
I tried the below solution based on the algorithm.
function getSum(n) {
let sum = 0;
while(n > 0 || sum > 9)
{
if(n == 0)
{
n = sum;
sum = 0;
}
sum += n % 10;
n /= 10;
}
return sum;
}
console.log(getSum("55555"));
This would kind of work, but I'm almost sure there's a beautiful one-line solution which I just don't see yet.
function singleDigitSum(str) {
str = [...str].reduce((acc, c) => { return Number(c) + acc }, 0)
while (str.toString().length > 1) {
str = singleDigitSum(str.toString());
}
return str
}
console.log(singleDigitSum("55555"))
Explanation:
As a first step in your function you reassign to the parameter passed to the function the result of a reducer function which sums up all numbers in your String. To be able to use Array.prototype.reduce() function, I'm spreading your str into an array using [...str].
Then, for as often as that reducer returns a value with more than one digit, rinse and repeat. When the while loop exits, the result is single digit and can be returned.
function checSumOfDigit(num, sum = "0") {
if (num.length == 1 && sum.length !== 1) {
return checSumOfDigit(Number(sum) + Number(num) + "", "0");
} else if (num.length == 1) {
return Number(sum) + Number(num);
}
num = num.split("")
sum = Number(sum) + Number(num.pop());
return checSumOfDigit(num.join(""), sum + "")
}
console.log(checSumOfDigit("567"));
console.log(checSumOfDigit("123"));
console.log(checSumOfDigit("55555"));
this code might be help you
If you need a recursion try this one
function CheckDigitSum(number) {
let nums = number.split('');
if (nums.length > 1) {
let sum = 0;
for (let i = 0; i < nums.length; i++) {
sum += Number(nums[i]);
}
return CheckDigitSum(sum.toString());
} else {
return parseInt(nums[0], 10);
}
}
Here you go:
function createCheckDigit(num) {
var output = Array.from(num.toString());
var sum = 0;
if (Array.isArray(output) && output.length) {
for ( i=0; i < output.length; i++){
sum = sum + parseInt(output[i]);
}
if ((sum/10) >= 1){
sum = createCheckDigit(sum);
}
}
return sum;
}
This can be calculated by recursive function.
function createCheckDigit(membershipId) {
// Write the code that goes here.
if(membershipId.length > 1){
var dgts = membershipId.split('');
var sum = 0;
dgts.forEach((dgt)=>{
sum += Number(dgt);
});
//console.log('Loop 1');
return createCheckDigit(sum + '');
}
else{
//console.log('Out of Loop 1');
return Number(membershipId);
}
}
console.log(createCheckDigit("5555555555"));
function checkid(num) {
let sum = 0;
let s = String(num);
for (i = 0; i < s.length; i++) {
sum = sum + Number(s[i]);
}
if(String(sum).length >= 2) return checkid(sum)
else return sum;
}
console.log(checkid(55555);

How do you iterate over an array every x spots and replace with letter?

/Write a function called weave that accepts an input string and number. The function should return the string with every xth character replaced with an 'x'./
function weave(word,numSkip) {
let myString = word.split("");
numSkip -= 1;
for(let i = 0; i < myString.length; i++)
{
numSkip += numSkip;
myString[numSkip] = "x";
}
let newString = myString.join();
console.log(newString);
}
weave("weave",2);
I keep getting an infinite loop. I believe the answer I am looking for is "wxaxe".
Here's another solution, incrementing the for loop by the numToSkip parameter.
function weave(word, numToSkip) {
let letters = word.split("");
for (let i=numToSkip - 1; i < letters.length; i = i + numToSkip) {
letters[i] = "x"
}
return letters.join("");
}
Well you need to test each loop to check if it's a skip or not. Something as simple as the following will do:
function weave(word,numSkip) {
var arr = word.split("");
for(var i = 0; i < arr.length; i++)
{
if((i+1) % numSkip == 0) {
arr[i] = "x";
}
}
return arr.join("");
}
Here is a working example
Alternatively, you could use the map function:
function weave(word, numSkip) {
var arr = word.split("");
arr = arr.map(function(letter, index) {
return (index + 1) % numSkip ? letter : 'x';
});
return arr.join("");
}
Here is a working example
Here is a more re-usable function that allows specifying the character used for substitution:
function weave(input, skip, substitute) {
return input.split("").map(function(letter, index) {
return (index + 1) % skip ? letter : substitute;
}).join("");
}
Called like:
var result = weave('weave', 2, 'x');
Here is a working example
You dont need an array, string concatenation will do it, as well as the modulo operator:
function weave(str,x){
var result = "";
for(var i = 0; i < str.length; i++){
result += (i && (i+1)%x === 0)?"x":str[i];
}
return result;
}
With arrays:
const weave = (str,x) => str.split("").map((c,i)=>(i&&!((i+1)%x))?"x":c).join("");
You're getting your word greater in your loop every time, so your loop is infinite.
Try something like this :
for(let k = 1; k <= myString.length; k++)
{
if(k % numSkip == 0){
myString[k-1]='x';
}
}
Looking at what you have, I believe the reason you are getting an error is because the way you update numSkip, it eventually becomes larger than
myString.length. In my code snippet, I make i increment by numSkip which prevents the loop from ever executing when i is greater than myString.length. Please feel free to ask questions, and I will do my best to clarify!
JSFiddle of my solution (view the developer console to see the output.
function weave(word,numSkip) {
let myString = word.split("");
for(let i = numSkip - 1; i < myString.length; i += numSkip)
{
myString[i] = "x";
}
let newString = myString.join();
console.log(newString);
}
weave("weave",2);
Strings are immutable, you need a new string for the result and concat the actual character or the replacement.
function weave(word, numSkip) {
var i, result = '';
for (i = 0; i < word.length; i++) {
result += (i + 1) % numSkip ? word[i] : 'x';
}
return result;
}
console.log(weave("weave", 2));
console.log(weave("abcd efgh ijkl m", 5));
You can do this with fewer lines of code:
function weave(word, numSkip) {
word = word.split("");
for (i = 0; i < word.length; i++) {
word[i] = ((i + 1) % numSkip == 0) ? "x" : word[i];
}
return word.join("");
}
var result = weave("weave", 2);
console.log(result);

Why is this code looping infinitely?

I'm trying to write a program in JavaScript that generates 100 random numbers and checks the primality of each. The program does just that, except for some reason it doesn't stop at 100 and just loops infinitely. I'm sure I made some simple novice mistake, but for some reason I can't see it. Any advice?
My code:
function isPrime(n) {
if (n < 2 || n % 1)
return false;
var r = Math.sqrt(n);
for (i = 2; i <= r; i++)
if (n % i === 0)
return false;
return true;
}
for (i = 0; i < 100; i++) {
var temp = Math.floor((Math.random() * 100) + 1);
if (isPrime(temp))
console.log(temp + " is a prime number!");
else
console.log(temp + " is not a prime number.");
}
Thanks!
You need to declare i variable in for-loops:
(var i = 0; i < 100; i++) ...
otherwise it is defined in global scope and it is shared between for-loop and isPrime function.
madox2 is correct that you should declare i in the for loop, however I think the reason the loop itself is infinite is because by only doing i=0 in the loop, and then for (i = 2; i <= r; i++) in the function the loop calls, you are resetting i every iteration
You should change your code to declare i within the scope of both loops separately, like so:
function isPrime(n) {
if (n < 2 || n % 1)
return false;
var r = Math.sqrt(n);
for (var i = 2; i <= r; i++)
if (n % i === 0)
return false;
return true;
}
for (var i = 0; i < 100; i++) {
var temp = Math.floor((Math.random() * 100) + 1);
if (isPrime(temp))
console.log(temp + " is a prime number!");
else
console.log(temp + " is not a prime number.");
}

Factorialize a Number

I'm taking the freecodecamp course one of the exercises it's to create a Factorialize function, I know there is several ways to do it just not sure what this one keeps returning 5
function factorialize(num) {
var myMax = num;
var myCounter = 1;
var myTotal = 0;
for (i = 0; i>= myMax; i++) {
num = myCounter * (myCounter + 1);
myCounter++;
}
return num;
}
factorialize(5);
This is a recursive solution of your problem:
function factorialize(num) {
if(num <= 1) {
return num
} else {
return num * factorialize(num-1)
}
}
factorialize(5)
This is the iterative solution:
function factorialize(num) {
var cnt = 1;
for (var i = 1; i <= num ; i++) {
cnt *= i;
}
return cnt;
}
factorialize(5)
with argument 5, it will return the 5! or 120.
To answer your question, why your function is returning 5:
Your function never reaches the inner part of the for-loop because your testing if i is greater than myMax instead of less than.
So you are just returning your input parameter which is five.
But the loop does not calculate the factorial of num, it only multiplies (num+1) with (num+2);
My solution in compliance with convention for empty product
function factorializer(int) {
if (int <= 1) {
return 1;
} else {
return int * factorializer(int - 1);
}
}
Here is another way to solve this challenge and I know it is neither the shortest nor the easiest but it is still a valid way.
function factorialiaze(num){
var myArr = []; //declaring an array.
if(num === 0 || num === 1){
return 1;
}
if (num < 0){ //for negative numbers.
return "N/A";
}
for (var i = 1; i <= num; i++){ // creating an array.
myArr.push(i);
}
// Reducing myArr to a single value via .reduce:
num = myArr.reduce(function(a,b){
return a * b;
});
return num;
}
factorialiaze(5);
Maybe you consider another approach.
This solution features a very short - cut to show what is possible to get with an recursive style and a implicit type conversion:
function f(n) { return +!~-n || n * f(n - 1); }
+ convert to number
! not
~ not bitwise
- negative
function f(n) { return +!~-n || n * f(n - 1); }
var i;
for (i = 1; i < 20; i++) {
console.log(f(i));
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Try this function
const factorialize = (num) => num === 0 ? 1 : num * factorialize(num-1)
Use it like this:
factorialize(5) // returns 120
Try this :
function factorialize(num) {
var value = 1;
if(num === 1 || num ===0) {
return value;
} else {
for(var i = 1; i<num; i++) {
value *= i;
}
return num * value;
}
}
factorialize(5);
// My solution
const factorialize = num => {
let newNum = 1;
for (let i = 1; i <= num; i++) {
newNum *= i
}
return newNum;
}
I love syntactic sugar, so
let factorialize = num => num <= 1 ? num : num * factorialize(num -1)
factorialize(5)

Categories

Resources