I am trying to come up with an algorithm to generate a nested array of consecutive numbers using only one loop. I feel it should be solved somehow using remainder operator but can't quite come up with a general solution. Anyone has any suggestion or hints?
input: 4
output: 1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4
You would use the modulo operator (%), but note that you should loop from zero and up, and the result from modulo is also from zero and up, so you have to add one to it.
var input = 4;
for (var i = 0; i < input * input; i++) {
var n = (i % input) + 1;
document.write(n + '<br>');
}
Something like that should do the trick:
int input = ...
int i = 0;
while(i<=(input*input)){
int output = (i % input) + 1;
i++;
}
Related
As you can see int he code below I separate the n variable and convert back to an integer array. When I put these numbers into my for loop they come out in the billions. Any help would be greatly appreciated.
var n = [86]
var p = [1]
n = n.toString().split("").map(function(value) {
return(parseInt(value))
})
var total = 0;
for(i=0;i<n.length;i++) {
total += (Math.pow(n[i],(p+i))
}
console.log(total)
You need the conversion from strings to numbers and you are adding an array to numbers.
You cannot sum an array to an integer [1]+0, it doesn't result in a number. It will do a concatenation.
var n = [86]
var p = [1]
n = n.toString().split("").map(val => Number(val))
var total = 0;
for (i = 0; i < n.length; i++) {
total += Math.pow(n[i], (p[0] + i))
}
console.log(total);
p is an array not an individual number, in your for loop, when it is running (p+i), that value ends up being 10 and 11. So your first loop is running Math.pow(8,10) and the second time it runs it is running Math.pow(6,11), which, will result in a number in the billions
I have a <p id="rabbits">1 2 9 4</p>' And i'm trying to calculate all the 1,2,9,4
However, I'm stuck at this part:
var rabbits = $('#rabbits').text()
var rabbits_array = rabbits.split(/(\s+)/);
for (i in rabbits_array) {
console.log(i) // prints 1,2,9,4
}
How do add all of these numbers together (which is 16 if you count manually) in javascript?
Can map array to number and use reduce
var rabbits = $('#rabbits').text()
var total = rabbits.split(" ").map(Number).reduce((a,c) => a + c)
console.log(total)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="rabbits">1 2 9 4</p>
There are a variety of ways to do this.
var rabbits = $('#rabbits').text()
var rabbits_array = rabbits.split(/(\s+)/);
var total = 0;
rabbits_array.forEach(function(element) {
total += element * 1;
});
console.log(total);
You could use a standard for loop:
for (var i = 0; i < rabbits_array.length;i++) {
total += rabbits_array[i] * 1;
}
You could replace the "multiply by 1" (which would have to validate beforehand that it's actually a number and not a letter), with parseInt or parseFloat. Using these methods can do some of this validation for you, but may also give you odd results.
total += parseFloat(rabbits_array[i]);
https://www.w3schools.com/jsref/jsref_parseint.asp
There are other ways to do this as well, but these are just a few examples to get you going. I'd suggest Googling "javascript loops" to read more about this kind of thing.
Try this:
var rabbits = $('#rabbits').text()
var rabbits_array = rabbits.split(" ");
var total = 0;
for (var i = 0; i < rabbits_array.length; i++) {
total = total + parseInt(rabbits_array[i]);
}
console.log(total)
You need to convert the string version of the number (from your split function) to an actual number before adding them together
edit: without giving me too much of the answer to how i can do it in a for loop. Could you give me the logic/pseudocode on how to achieve this? the one part i am stuck at is, ok i know that i have to take the first index number and add array.length-1 zeros to it (2 zeros), but i am confused as to when it arrives at the last index, do i put in a if statement in the for loop?
In the below example 459 would be put in an array [4,5,9]
Now I want to take 4 add two zeros to the end because it has two numbers after it in the array
Then I want to take 5 and add one zero to it because there is one number after it in the array.
then 9 would have no zeros added to it because there are no numbers after it.
So final output would be 400,50,9
how can i best achieve this?
var num=459;
var nexint=num.toString().split("");
var finalint=nexint.map(Number);
var nextarr=[];
You need to use string's repeat method.
var num=459;
var a = (""+num).split('').map((c,i,a)=>c+"0".repeat(a.length-i-1))
console.log(a);
Here's another possible solution using a loop.
var num = 459;
var a = ("" + num).split('');
var ar = [];
for (var i = 0; i < a.length; i++) {
var str = a[i];
str += "0".repeat(a.length-i-1);
ar.push(str);
}
console.log(ar);
You could use Array#reduce and Array#map for the values multiplied by 10 and return a new array.
var num = 459,
result = [...num.toString()].reduce((r, a) => r.map(v => 10 * v).concat(+a), []);
console.log(result);
OP asked for a solution using loops in a comment above. Here's one approach with loops:
var num = 459
var numArray = num.toString().split('');
var position = numArray.length - 1;
var finalArray = [];
var i;
var j;
for(i = 0; i < numArray.length; i++) {
finalArray.push(numArray[i]);
for(j = 0; j < position; j++) {
finalArray.push(0);
}
position--;
}
console.log(finalArray);
The general flow
Loop over the original array, and on each pass:
Push the element to the final array
Then push X number of zeros to the final array. X is determined by
the element's position in the original array, so if the original
array has 3 elements, the first element should get 2 zeros after it.
This means X is the original array's length - 1 on the first pass.
Adjust the variable that's tracking the number of zeros to add before
making the next pass in the loop.
This is similar to #OccamsRazor's implementation, but with a slightly different API, and laid out for easier readability:
const toParts = n => String(n)
.split('')
.map((d, i, a) => d.padEnd(a.length - i, '0'))
.map(Number)
console.log(toParts(459))
I'm trying to sort numbers from user input (.prompt) from largest to smallest using the insertion sort method. I'm having difficulty understanding how to apply this method in my html code. Any advice is greatly appreciated!
The only difference according to me might be with interface part as
prompt take input as a string where you can take input as csv then split on commas and get an array of substrings, then parseInt and use in sorting as usual.
Note that this assumes the user is only going to input numbers. You will want to modify this code to account for users entering all kinds of data.
Updated Answer
This is self-explanatory if you're familiar with map and parseFloat. parseFloat just converts a string to a floating point number (1.5, 6.004, etc). map calls a callback function on each element of an array, and returns an array that contains the results. In this code, map is doing parseFloat on each element of the array and returning the result.
Oh, and one more thing that isn't obvious; sort sorts according to string Unicode code points (see here for more info). Therefore, 10 comes before 2 because 1 comes before 2. That's why we need .sort((a,b) => (a-b)), which I got from a comment on this answer.
const numberArray = prompt('Enter several numbers with a space between each').split(' ');
numberArray.map(element => parseFloat(element)).sort((a,b) => (a-b)).reverse();
First answer, but sorts 6 as greater than 10 because 6 comes before 1 in ASCII I think.
const numberArray = prompt('Enter several numbers with a space between each').split(' ');
numberArray.map(element => parseFloat(element));
function insertionSort(array) {
for (let i = 0; i < array.length; i += 1) {
const temp = array[i];
let j = i - 1;
while (j >= 0 && array[j] > temp) {
array[j + 1] = array[j];
j -= 1;
}
array[j + 1] = temp;
}
return array.reverse();
}
insertionSort(numberArray);
I got the insertion sort algorithm from Benoit Vallon's blog
As mentioned in the previous answer.. It is the same as you would do with any other language.
You need however to update your question to reflect exactly what have you tried and ask something more acurate.
Nevertheless, here is a simple sample of how you can achieve this. Take note that I did not do any type validation or or conversion. So it's on you to make sure the user inputs a number
var toSort=[];
$('#sort').on('click',function(){
var result= insertionSort(toSort);
$('p').html(result.toString());
});
$('#prompt').on('click',function(){
toSort.push(prompt("Enter a number",0));
});
/* from http://blog.benoitvallon.com/sorting-algorithms-in-javascript/the-insertion-sort-algorithm/ */
function insertionSort(array) {
for(var i = 0; i < array.length; i++) {
var temp = array[i];
var j = i - 1;
while (j >= 0 && array[j] > temp) {
array[j + 1] = array[j];
j--;
}
array[j + 1] = temp;
}
return array;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="prompt">Prompt</button>
<button id="sort">Sort</button>
<h1>End result:</h1>
<p></p>
I have two arrays set up that I wish to multiply each value within each together. Then I want to get the total value in the form of a variable. I will post what I have below. I think my problem may be that I am not sure how to get each run of the code to add together?
var flatQty=[];
flatQty[0]= document.getElementById("flats1").value;
flatQty[1]= document.getElementById("flats2").value;
flatQty[2]= document.getElementById("flats3").value;
flatQty[3]= document.getElementById("flats4").value;
flatQty[4]= document.getElementById("flats5").value;
var flatWidth=[];
flatWidth[0]=document.getElementById("flatwidth1").value;
flatWidth[1]=document.getElementById("flatwidth2").value;
flatWidth[2]=document.getElementById("flatwidth3").value;
flatWidth[3]=document.getElementById("flatwidth4").value;
flatWidth[4]=document.getElementById("flatwidth5").value;
for (var i=0;i<5;i++)
{
var flatCharge=flatWidth[i]*2*flatQty[i];
}
document.getElementById("flatTest").innerHTML=flatCharge;
When I run the code nothing is printed into the id="flatTest".
Your problems is that you are redefining your flatCharge inside the loop, therefore it's not correct outside the loop. In addition, you are not adding the values, but replacing them on every iteration of the loop. Change the loop to this:
var flatCharge = 0;
for (var i = 0; i < 5; i++) {
flatCharge += flatWidth[i] * 2 * flatQty[i];
};
document.getElementById("flatTest").innerHTML = "" + flatCharge;
and it should work.
.value properties are strings, not numbers. so you should be careful how you handle them. Multiplication actually works for strings, but not for addition where the + operator performs concatenation instead.
There are numerous methods of converting from string to number:
+s - will convert the expression s into a number
parseFloat(s)
parseInt(s, 10) for whole numbers
The actual problem in your code is that you're overwriting the calculated value in each pass using the = operator instead of +=.
I suggest refactoring your entire code thus to avoid all of the repetition:
var flatCharge = 0;
for (var i = 1; i <= 5; ++i) {
var qty = +document.getElementById('flats' + i).value;
var width = +document.getElementById('flatwidth' + i).value;
if (!isNaN(qty) && !isNaN(width)) {
flatCharge += 2 * qty * width;
}
}