How to find sum of integers in a string using JavaScript - javascript

I created a function with a regular expression and then iterated over the array by adding the previous total to the next index in the array.
My code isn't working. Is my logic off? Ignore the syntax
function sumofArr(arr) { // here i create a function that has one argument called arr
var total = 0; // I initialize a variable and set it equal to 0
var str = "12sf0as9d" // this is the string where I want to add only integers
var patrn = \\D; // this is the regular expression that removes the letters
var tot = str.split(patrn) // here i add split the string and store it into an array with my pattern
arr.forEach(function(tot) { // I use a forEach loop to iterate over the array
total += tot; // add the previous total to the new total
}
return total; // return the total once finished
}

var patrn = \\D; // this is the regular expression that removes the letters
This is not a valid regular expression in JavaScript.
You are also missing a closing bracket in the end of your code.
A simpler solution would be to find all integers in the string, to convert them into numbers (e.g. using the + operator) and summing them up (e.g. using a reduce operation).
var str = "12sf0as9d";
var pattern = /\d+/g;
var total = str.match(pattern).reduce(function(prev, num) {
return prev + +num;
}, 0);
console.log(str.match(pattern)); // ["12", "0", "9"]
console.log(total); // 21

you have some errors :
change var patrn = \\D with var patrn = "\\D"
use parseInt : total += parseInt(tot);
function sumofArr(arr){ // here i create a function that has one argument called arr
var total = 0; // I initialize a variable and set it equal to 0
var str = "12sf0as9d" // this is the string where I want to add only integers
var patrn = "\\D"; // this is the regular expression that removes the letters
var tot = str.split(patrn) // here i add split the string and store it into an array with my pattern
arr.forEach(function(tot){ // I use a forEach loop to iterate over the array
total += parseInt(tot); // add the previous total to the new total
})
return total; // return the total once finished
}
alert(sumofArr(["1", "2", "3"]));
https://jsfiddle.net/efrow9zs/

function sumofArr(str) {
var tot = str.replace(/\D/g,'').split('');
return tot.reduce(function(prev, next) {
return parseInt(prev, 10) + parseInt(next, 10);
});}
sumofArr("12sf0as9d");

Related

Set the last number in a string to negative

I have a string with diffrent mathematical characters, and i want to make the last number negative/positive. Let's say the string is "100/5*30-60+333". The result i want is "100/5*30-60+(-333)", and i want to convert it back to positive ("100/5*30-60+333").
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = hiddenText.value;
n.split('+');
n.split('-');
n.split('*');
n.split('/');
console.log(n);
}
What i get is the whole hiddenText.value, and not an array of all numbers. Any tips?
First, I'd match all of the basic math operators to get their order:
const operatorsArr = n.match(/\+|\-|\/|\*/g)
Then, split the string:
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = hiddenText.value;
n = n.replace(/\+|\-|\/|\*/g, '|');
n = n.split('|');
console.log(n);
}
Then, you will have an array of numbers, in which you can mutate the last number easily:
n[n.lengh-1] *= -1;
Now we can combine the two arrays together:
let newArr;
for (let i = 0; i < n.length; i++) {
newArr.push(n[i]);
if (operatorsArr[i]) newArr.push(operatorsArr[i]);
}
At last, you can rejoin the array to create the new String with a seperator of your choosing. In this example I'm using a space:
newArr = newArr.join(' ')
Please let me know how that works out for you.
Let's say the string is "100/5*30-60+333". The result i want is
"100/5*30-60+(-333)", and i want to convert it back to positive
("100/5*30-60+333").
The following code does that:
let mathStr = '100/5*30-60+333';
console.log(mathStr);
let tokens = mathStr.split('+');
let index = tokens.length - 1;
let lastToken = tokens[index];
lastToken = '('.concat('-', lastToken, ')');
let newMathStr = tokens[0].concat('+', lastToken);
console.log(newMathStr); // 100/5*30-60+(-333)
console.log(mathStr); // 100/5*30-60+333
EDIT:
... and i want to convert it back to positive ("100/5*30-60+333").
One way is to declare mathStr (with the value "100/5*30-60+333") as a var at the beginning and reuse it, later as you need. Another way is to code as follows:
let str = "100/5*30-60+(-333)";
str = str.replace('(-', '').replace(')', '');
console.log(str); // 100/5*30-60+333
To get numbers You can use replace function and split check code bellow :
function posNeg() {
// hiddenText is a <input> element. This is not shown.
let n = "100/5*30-60+333";
n = n.replace('+','|+');
n = n.replace('-','|-');
n = n.replace('*','|*');
n = n.replace('/','|/');
n=n.split('|');console.log(n);
// to use any caracter from array use it in removeop like example
// if we have array (split return) have 100 5 30 60 333 we get 100 for example
// we need to make removeop(n[0]) and that reutrn 100;
// ok now to replace last value to negative in string you can just make
// var lastv=n[n.length-1];
// n[n.length-1] ='(-'+n[n.length-1])+')';
//var newstring=n.join('');
//n[n.length-1]=lastv;
//var oldstring=n.join('');
}
function removeop(stringop)
{
stringop = stringop.replace('+','');
stringop = stringop.replace('-','');
stringop = stringop.replace('*','');
stringop = stringop.replace('/','');
return stringop;
}
If you really need to add "()", then you can modify accordingly
<script>
function myConversion(){
var str = "100/5*30-60-333";
var p = str.lastIndexOf("+");
if(p>-1)
{
str = str.replaceAt(p,"-");
}
else
{
var n = str.lastIndexOf("-");
if(n>-1)
str = str.replaceAt(n,"+");
}
console.log(str);
}
String.prototype.replaceAt=function(index, replacement) {
return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}
</script>

Generate string of random number that includes some number and exclude some number

I have a problem about generating string in javascript.
I have an array of number that string should contains atleast 1, and 1 number(up to 7 digits) that must not contains in a string. String length must be 7.
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ... //input from user
I tried to generate it by random select from array, random position and random other number around selected number. Then check if string contains excluded number, generate it again.
//random select number
var getRandom = incNumber[Math.floor(Math.random() * incNumber.length)];
//random position of number
var position = Math.floor(Math.random() * 6);
//length of other string after selected number
var afterlen = 7 - (position+2);
//genNum(...) is my function that use to generate string of number in specific length.
var nstr = genNum(position)+getRandom+genNum(afterlen);
while (nstr.includes(exclude)) {
nstr = genNum(position)+getRandom+genNum(afterlen);
}
but doing this take too long time or sometimes freeze my browser. How should I fix it.?
edited: It's my homework about phonenumber.
final string should be like "37915002"
Edited my code again
Does that now match your needs? It has got pretty messy and I'm not sure if it's correct (I'm never sure.. xD) hope you can get some inspiration though.
// Variables
var initialList = ["100", "5", "19", "88", "10", "90"];
var excludeList = ["9", "10"];
var resultLength = 7;
var finalString = "";
// Create a third final array that is filtered
var finalList = initialList.filter(element => {
let shouldBeIncluded = true;
excludeList.forEach(excluder => {
Array.from(excluder).forEach(excluderFragment => {
if (element.includes(excluderFragment)) shouldBeIncluded = false;
});
});
if (shouldBeIncluded) return true;
});
// Check if all were excluded
if (finalList.length == 0) {
// Do error handling here
} else {
// Create the list
for (let i = 0; i < resultLength; i++) {
finalString += finalList[Math.floor(Math.random() * finalList.length)];
}
// Shorten the list because multiple digits values
finalString = finalString.slice(0, 7);
console.log(finalString);
}
You could start by filtering the unwanted number from the incNumber and doing everything the same way but on the new array
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = "12";
var filteredNumbber =incNumber.filter(number=> number!==exclude);
var random = filteredNumbber[Math.floor(Math.random() * filteredNumbber.length)];
if we assume exclude is not a value but instead an array of values you would change the formula to
var incNumber = ["15","51","14","41","55","39","23"];
var exclude = ["15"];
var filteredNumbber =incNumber.filter(number=> !exclude.includes(number));
var random = filteredNumbber[Math.floor(Math.random() * filteredNumbber.length)];
as some people suggested random variable may end up as undefined if we exclude all the numbers inside of incNumber, if that was the case we should add an additional check in case that happens
if (random!==undefined) var nstr = genNum(position)+random+genNum(afterlen);

Permutations filtered with no repeating characters

This is a task from freeCodeCamp.
My goal is to create a function which:
Takes any string with any characters.
Creates an array with all the permutations possible out of that string.
Filters the array and returns only the strings which don't have repeated consecutive letters.
Return the number of total permutations of the provided string that don't have repeated consecutive letters. Assume that all characters in
the provided string are each unique. For example, aab should return 2
because it has 6 total permutations (aab, aab, aba, aba, baa, baa),
but only 2 of them (aba and aba) don't have the same letter (in this
case a) repeating.
I can't figure out what have i wrote wrong. I think the problem lies either in the filter function or the permutation list is faulty.
function permAlone(str) {
if (str.length == 1) {
return str;
}
// Creates all possible Permutations and pushes to an array
var arr = [];
var p = 0; // position of the element which needs to be swapped
// Loop count equal to number of Permutations.
var loops = factorialize(str.length);
for (var i = 0; i < loops; i++) {
// if the position is not the last element in the strig keep swapping with next following character
if (p != str.length - 1) {
var splitStr = str.split('')
arraySwapElements(splitStr, p, p + 1);
str = splitStr.join('');
arr.push(str);
p += 1;
// when position is at the last index, change position to 0
} else {
p = 0;
i -= 1;
}
}
// swaps 2 items in an array
function arraySwapElements(arr, a, b) {
var item = arr[a];
arr[a] = arr[b];
arr[b] = item;
};
// outputs a factorial of a number
function factorialize(num) {
if (num === 0) {
return 1;
} else {
return num * factorialize(num - 1);
}
}
// filters any array which has 2 or more repeating characters
var x = arr.filter(function(str) {
var re = /(.)\1+/;
var result = re.test(str);
if (!result) {
return str;
}
})
// returns the filtered arrays length
return x.length
}
console.log(permAlone('abfdefa'));
When testing:
permAlone("aab") should return a number. // Correct
permAlone("aab") should return 2. // Correct
permAlone("aaa") should return 0. // Correct
permAlone("aabb") should return 8. // Correct
permAlone("zzzzzzzz") should return 0.// Correct
permAlone("a") should return 1.// Correct
permAlone("aaab") should return 0.// Correct
permAlone("abcdefa") should return 3600. // Incorrect
permAlone("abfdefa") should return 2640.// Incorrect
permAlone("aaabb") should return 12. // Incorrect
The issue stems from the logic used in the for loop. While the loop does generate the right number of total permutations, it doesn't generate all permutations.
For example, if our string to be permuted was "abcd", the swapping mechanism would generate strings like this:
bacd bcad bcda
cbda cdba cdab
dcab dacb dabc
adbc abdc abcd
Uh oh! That last arrangement is the same as the starting string. When we start swapping again, we're going to get the same set that we did on the first pass. We're never going to get a permutation like "acbd". Thus the resulting array contains higher numbers of some permutations and lower numbers of others.
I'm not sure how to fix it with the approach you're using, but a recursive function to get permutations could be written like this:
// Returns an array of all permutations of a string
function getPerms(str) {
// Base case. If the string has only one element, it has only one permutation.
if (str.length == 1) {
return [str];
}
// Initialise array for storing permutations
let permutations = [];
// We want to find the permutations starting with each character of the string
for (let i = 0; i < str.length; i++) {
// Split the string to an array
let splitStr = str.split('');
// Pull out the character we're checking for permutations starting with
let currentElem = splitStr.splice(i, 1)[0];
// Get permutations of the remaining characters
let subPerms = getPerms(splitStr.join(''));
// Concat each of these permutations with the character we're checking
// Add them to our list
subPerms.forEach(function (combination) {
permutations.push(currentElem.concat(combination));
});
}
// return our list
return combinations;
}

How to make a single string into a multitude of strings?

I have a string called e3 which holds the string 1,2,4,5,3,6. I want to add up all of those numbers up to make the number 21 I was considering doing a for loop for this however I do not know how to turn part of a string into its own value.
I anyone has any better idea of what to do please comment, or answer.
You could use String#split for the string and use Array#reduce for summing.
var e3 = '1,2,4,5,3,6',
sum = e3.split(',').reduce(function (a, b) {
return a + +b; // +b forces b to number
}, 0);
console.log(sum);
If you are sure that it is always a comma separated list of numbers, you could split it on the comma into an array and then use array.reduce() to sum them
var asString = '1,2,4,5,3,6';
var asArray = asString.split(',');
var total = asArray.reduce(function(prev, current){
return prev + parseInt(current, 10);
}, 0);
console.log(total) // outputs 21;
You can do it like this:
var e3 = "1,2,4,5,3,6";
// Split by separator ','
var stringsArr = e3.split(',');
var sum = 0;
// Loop through array of string numbers
stringsArr.forEach(function(str) {
// get Int from a string
var strVal = parseInt(str, 10);
sum += strVal;
});
here's the fiddle
Here is working code to do what you need: https://plnkr.co/edit/8LSkZi0oC8msbHI0qOrz?p=preview
At first you use the split method - this separates a string into an array of strings, based on some separator value. In our case, the separator is a comma, but it could be a blank space or something else:
var testString = '1,2,4,5,3,6';
var separator = ',';
function splitStringOnCommasAndGetArray(string, separator){
var arrayOfStrings = string.split(separator);
return arrayOfStrings;
}
After that, we loop through the array and turn each value into a number. We add the numbers, like so:
function addUpArray(arrayOfStrings){
var totalNumber = 0;
for(var i = 0; i < arrayOfStrings.length; i++){
var currentNum = parseInt(arrayOfStrings[i]);
console.log(currentNum);
totalNumber += currentNum;
}
return totalNumber;
}

Splitting a number into an array

Alright so I'm trying to completely split a number into an Array. So for example:
var num = 55534;
var arr = []; <- I would want the Array to look like this [5,5,5,3,4]
Basically i want to to completely split the number apart and place each Number into its own element of the array. Usually in the past i would just convert the number into a string then use the .split() function. This is how i use to do it:
num += "";
var arr = num.split("");
But this time i actually need to use these numbers, so they can not be strings. What would you guys say be the way of doing this?
Update, after the edit for some reason my code is crashing every run:
function DashInsert(num) {
num += "";
var arr = num.split("").map(Number); // [9,9,9,4,6]
for(var i = 0; i < arr.length; i++){
if(arr[i] % 2 === 1){
arr.splice(i,0,"-");
}// odd
}
return arr.join("");
}
String(55534).split("").map(Number)
...will handily do your trick.
You can do what you already did, and map a number back:
55534..toString().split('').map(Number)
//^ [5,5,5,3,4]
I'll do it like bellow
var num = 55534;
var arr = num.toString().split(''); //convert string to number & split by ''
var digits = arr.map(function(el){return +el}) //convert each digit to numbers
console.log(digits); //prints [5, 5, 5, 3, 4]
Basically I'm converting each string into numbers, you can just pass Number function into map also.

Categories

Resources