I'm trying to take numbers inputted by a user. Store those number inside an array and then add up all values inside the array to get a total number. I'm using numbers 1 -7 to test.
I print the output of the array and I get:
1,2,3,4,5,6,7
returned so it seems that storing the data in an array is working. However when I try to add the values inside the array I get:
01234567
Which makes it look like the function is just pushing the numbers together. I feel like I'm missing something really obvious here but I can't figure out what it is. Any help would be appreciated.
var again = "no";
var SIZE = 7;
var pints = [];
var totalPints = 0;
var averagePints = 0;
var highPints = 0;
var lowPints = 0;
getPints(pints[SIZE]);
getTotal(pints[SIZE]);
println(pints);
println(totalPints);
function getPints()
{
counter = 0;
while (counter < 7)
{
pints[counter] = prompt("Enter the number of pints");
counter = counter + 1;
}
}
function getTotal()
{
counter = 0;
totalPints = 0
for (var counter = 0; counter < 7; counter++)
{
totalPints += pints[counter]
}
}
You can use parseInt to convert the pints values like this
totalPints += parseInt(pints[counter], 10);
And you don't have to hardcode the length like this
for (var counter = 0; counter < 7; counter++)
instead you can use pints.length like this
for (var counter = 0; counter < pints.length; counter++)
Your array contains the strings instead of their integer values, instead of
totalPints += pints[counter];
Try using something like this -
totalPints += parseInt(pints[counter], 10);
That happens since each number is read as a string, not a number. Change:
pints[counter] = prompt("Enter the number of pints");
to:
pints[counter] = +prompt("Enter the number of pints");
to convert the value to a Number so that you get addition instead of concatenation from the + operator.
["1", "2", "3", "4", "5", "6", "7"]
01234567
This is the output produced by your code. Note that values in the array are in quotes, so that means their type is String. When using + with strings you get string concatenation.
That's why you have to convert them to a number.
There are multiple ways to do so.
-> parseInt("5")
-> 5
-> "5" * 1
-> 5
-> Number("5")
-> 5
Change
totalPints += pints[counter]
to
totalPints += parseInt(pints[counter])
parseInt will convert the string values to integers.
Related
Convert the ASCII value sentence to its equivalent string
This is for writing a similar program given above. I tried to convert the input directly to string value for the iteration.
What is happening is, assume the input value is
var num = 23511011501782351112179911801562340161171141148;
When I convert this number to string
num.toString()
I'm getting the result like this:
"2.351101150178235e+46"
There are so many similar questions asked in SOF, but I didn't see any proper answers.
Can someone help me with how to iterate each value in the input?
Thanks in advance.
If I understand you mean correctly, you can replace the code char ch = (char)num; with var ch = String.fromCharCode(num);. Like this:
var result = [];
function asciiToSentence(str, len)
{
var num = 0;
for (var i = 0; i < len; i++) {
// Append the current digit
num = num * 10 + (str[i] - '0');
// If num is within the required range
if (num >= 32 && num <= 122) {
// Convert num to char
var ch = String.fromCharCode(num);
result.push(ch)
// Reset num to 0
num = 0;
}
}
}
var str = "7110110110711510211111471101101107115";
var len = str.length;
asciiToSentence(str, len);
console.log(result.join(''));
Reference: String.fromCharCode()
Explanation:
First, inside the function asciiToSentence, we need 2 parameters str and len (str is a string while len is the length of that string).
Next, we make a temporary num to calculate the number inside the string based on this table: ASCII Printable Characters
We trying to parse one-by-one character to a number and multiply it with 10. Then, we compare it between 32 and 122 (based on the number in the table above).
If the number we have is inside the range, we parse that number to a character using String.fromCharCode function and reset the value num. Otherwise, we continue the loop and increase the value num
Let's say I have a string variable called myString, and another string variable called myChar.
var myString = "batuhan"; // it's user input.
var myChar = "0"; // will be one character, always
What I need is, a function that returns all the combinations of myString and myChar.
Like:
"batuhan","batuha0n","batuh0an","batuh0a0n","batu0han","batu0ha0n","batu0h0an","batu0h0a0n","bat0uhan","bat0uha0n","bat0uh0an","bat0uh0a0n","bat0u0han","bat0u0ha0n","bat0u0h0an","bat0u0h0a0n","ba0tuhan","ba0tuha0n","ba0tuh0an","ba0tuh0a0n","ba0tu0han","ba0tu0ha0n","ba0tu0h0an","ba0tu0h0a0n","ba0t0uhan","ba0t0uha0n","ba0t0uh0an","ba0t0uh0a0n","ba0t0u0han","ba0t0u0ha0n","ba0t0u0h0an","ba0t0u0h0a0n","b0atuhan","b0atuha0n","b0atuh0an","b0atuh0a0n","b0atu0han","b0atu0ha0n","b0atu0h0an","b0atu0h0a0n","b0at0uhan","b0at0uha0n","b0at0uh0an","b0at0uh0a0n","b0at0u0han","b0at0u0ha0n","b0at0u0h0an","b0at0u0h0a0n","b0a0tuhan","b0a0tuha0n","b0a0tuh0an","b0a0tuh0a0n","b0a0tu0han","b0a0tu0ha0n","b0a0tu0h0an","b0a0tu0h0a0n","b0a0t0uhan","b0a0t0uha0n","b0a0t0uh0an","b0a0t0uh0a0n","b0a0t0u0han","b0a0t0u0ha0n","b0a0t0u0h0an","b0a0t0u0h0a0n"
Rules: myChar shouldn't follow myChar
How can I do that? Really my brain dead right now :/
It's possible to implement what you want using recursion.
// Example: allCombinations("abcd", "0") returns the array
// ["abcd", "abc0d", "ab0cd", "ab0c0d", "a0bcd", "a0bc0d", "a0b0cd", "a0b0c0d"]
function allCombinations(str, chr) {
if (str.length == 1)
return [str];
var arr = allCombinations(str.substring(1), chr);
var result = [];
var c = str.charAt(0);
for (var i = 0; i < arr.length; i++)
result.push(c + arr[i]);
for (var i = 0; i < arr.length; i++)
result.push(c + chr + arr[i]);
return result;
}
You may or may not have noticed this but this is basically counting in binary. If we define bit 0 to be the absence of myChar and bit 1 to be the presence of myChar, then the following sequence:
var myString = ".....";
var myChar = "1";
var sequence = [
".....1",
"....1.",
"....1.1",
"...1.."
];
is basically counting from 1 to 4 in binary:
var sequence = [
0b0000001,
0b0000010,
0b0000011,
0b0000100
];
Therefore, all you need is a for loop to count up to the bit amount of the length of the string plus 1 (because the position at the end of the string is also legal):
var len = Math.pow(2,myString.length+1);
for (var x = 0; x < len; x++) {
// x in binary is all the possible combinations
// now use the "1" bits in x to modify the string:
// Convert myString to array for easy processing:
var arr = myString.split('');
arr.push(""); // last position;
for (var i = myString.length; i >= 0; i--) {
if ((x >> i) & 0x01) { // check if bit at position i is 1
arr[i] = myChar + arr[i];
}
}
console.log(arr.join('')); // print out one combination
}
Of course, this works only for small strings of up to 31 characters. For larger strings you'd need to do the binary counting using things other than numbers. Doing it in a string form is one option. Another option is to use a bigint library such as BigInteger.js to do the counting.
I have 2 arrays of numbers. I want to go through each array and find the number of times 1 number from each array adds up to the particular amount x.
If the particular amount x is reached as many times as another set number n then the function should print 'YES'. If x does not reach the set number of n then the function should print 'NO'.
The values of x , n and both arrays are in a string input. These values have been split into arrays as seen below in the code.
I have set up 2 for loops to run through each array and an if statement that checks for the condition of x meeting n.
The arrays I'm using in this code should print out the result of 'YES' however every time I run the code I'm getting 'NO' ? I've tried tinkering with the code but nothing has worked.
Any idea on where this code is broke and how to fix the problem?
Thanks :)
code:
var input = '2\n3 10\n2 1 3\n7 8 9';
function processData(input) {
var inputArray = input.split('\n');
var n = inputArray[1][0];
var x = inputArray[1].split(' ')[1];
var arrayA = inputArray[2].split(' ');
var arrayB = inputArray[3].split(' ');
var total = 0;
for(var i = 0; i < arrayA.length; i++) {
for(var j = 0; j < arrayB.length; j++) {
if(arrayA[i] + arrayB[j] == x) {
total = total + 1;
} if (total == n) {
return 'YES';
}
}
}
return 'NO';
}
console.log(processData(input));
arrayA[i] and arrayB[j] are strings, so arrayA[i] + arrayB[j] will be the concatenation of them (ex: '2' + '3' === '23').
If your logic is correct (i didn't quite understand what you are trying to do), it should be enough to convert them to numbers before adding them, using parseInt or some other method:
if(+arrayA[i] + (+arrayB[j]) == +x) { // used unary + to convert to number
total = total + 1;
} if (total == n) {
return 'YES';
}
PS: A cleaner version would be to convert each string in the array to number, but that involves more than adding 3 characters to your code.
PS2: You have a weird way of getting the input data. If you get it from another place in your JS code, you could simply pass it as an object with the relevant structure, otherwise you could pass it around in a more ... common format, like JSON.
Im trying to get the total combined value of a set of numbers.
Im getting the numbers as the text in an element tag storing them in an array then adding them all together. My problem is that its not inserting the numbers into the array as pairs.. it adding them as single integers .what am doing wrong.
check the jsfiddle too see example
http://jsfiddle.net/Wd78j/
var z = $('.impressions').text();
var x = [];
for(var i = 0; i < z.length; i++){
x.push(parseInt(z[i]));
}
console.log(x);
var total = 0;
$.each(x,function() {
total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
When you get text, it's taking all the numbers and concatenating them into a string. The below takes each element one at a time and pushes it.
var x = [];
$('.impressions').each( function( ) {
var z = $(this).text();
x.push(parseInt(z, 10));
})
Of course, you could build the sum up inside that each function, but I did it like this to more closely mirror your code.
text() returns the concatenated text of all of your impressions elements, of which you're adding together each character.
You want to loop through each impressions element, and keep a running sum going. Something like this should work
var sum = 0;
$('.impressions').each(function(){
sum = sum + (+$(this).text());
});
Updated Fiddle
Or to keep your original structure (don't forget the radix parameter to parseInt):
var z = $('.impressions');
var x = [];
z.each(function(){
x.push(parseInt($(this).text(), 10));
});
console.log(x);
var total = 0;
$.each(x,function() {
total += this;
});
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
Updated fiddle
You are iterating over a string, you could just use $.map to build the array instead, if you need it, otherwise just iterate and sum up the values :
var x = $.map($('.impressions'), function(el,i) {return parseInt($(el).text(), 10);}),
total = 0,
n = x.length;
while(n--) total += x[n] || 0;
$('#impressTotals').append("[Total:" +total + "]");
$('#array').append("[Array:"+x+"]");
FIDDLE
I am NOT talking about adding elements together, but their values to another separate variable.
Like this:
var TOTAL = 0;
for (i=0; i<10; i++){
TOTAL += myArray[i]
}
With this code, TOTAL doesn't add mathematically element values together, but it adds them next to eachother, so if myArr[1] = 10 and myArr[2] = 10 then TOTAL will be 1010 instead of 20.
How should I write what I want ?
Thanks
Sounds like your array elements are Strings, try to convert them to Number when adding:
var total = 0;
for (var i=0; i<10; i++){
total += +myArray[i];
}
Note that I use the unary plus operator (+myArray[i]), this is one common way to make sure you are adding up numbers, not concatenating strings.
A quick way is to use the unary plus operator to make them numeric:
var TOTAL = 0;
for (var i = 0; i < 10; i++)
{
TOTAL += +myArray[i];
}
const myArray = [2, 4, 3];
const total = myArray.reduce(function(a,b){ return +a + +b; });
Make sure your array contains numbers and not string values. You can convert strings to numbers using parseInt(number, base)
var total = 0;
for(i=0; i<myArray.length; i++){
var number = parseInt(myArray[i], 10);
total += number;
}
Use parseInt or parseFloat (for floating point)
var total = 0;
for (i=0; i<10; i++)
total+=parseInt(myArray[i]);