Reputation: 2837
The algorithm is supposed to sum two elements of the array and insert them between the two elements used in the sum.
Example input ==> output :
[1, 2, 3, 4] ==> [ 1, 3, 2, 5, 3, 7, 4]
function growArray() {
var sequence = [];
sequence = window.prompt("Enter a number sequence", "1 2 3 4");
for (var i = 0; i < sequence.length - 1; i += 2) {
if (!((i + 1) in sequence)) {
return;
} // prevent out of bounds access
var new_value = sequence[i] + sequence[i + 1];
sequence.splice(i + 1, 0, new_value); // insert value at i + 1
}
for (var v in sequence) {
document.write(v + ", ");
}
}
<p>
<input id="f1" type="button" value="Function 1" onclick="growArray();" />Click to expand array
</p>
Upvotes: 3
Views: 288
Reputation: 189
here is what gets the output
function growArray() {
var input = window.prompt("Enter a number sequence", "1 2 3 4");
var sequence = input.split(" ");
for (var i = 0; i < sequence.length - 1; i += 2) {
if (i + 1 > sequence.length) {
return;
} // prevent out of bounds access
var new_value = parseInt(sequence[i]) + parseInt(sequence[i + 1]);
sequence.splice(i + 1, 0, new_value); // insert value at i + 1
}
document.write(sequence.toString());
}
<p>
<input id="f1" type="button" value="Function 1" onclick="growArray();" />Click to expand array
</p>
Upvotes: 2
Reputation: 4653
You have to split
user input into an array (sequence).
This array contains string values because user input is string. So you have to map those values in int, in order to add them.
var sequence = '1 2 3 4'.split(' ').map(Number);
for(var i=0; i<sequence.length - 1; i+=2) {
sequence.splice(i+1, 0, sequence[i] + sequence[i+1]);
}
document.write(sequence.join(', '));
working example
Upvotes: 0
Reputation: 2781
There are several points to look upon your code.
sequence
is an array, but you did not defined a type, or even parsed the inputs. It is a String array as far as I can read.
Documentation states: The split() method splits a String object into an array of strings by separating the string into substrings.
Then, your array keeps getting altered while you work on it. While this is no error, it is "weird" for the task at hand, and the apparent dominium you have over the language.
example(){
var original = [1, 2, 3, 4];
var result=[];
for(var i=0;i<original.length;i++){
result.push(original[i]);
if(i<original.length-1){
result.push(original[i]+original[i+1]);
}
}
alert(result);
}
Upvotes: 0