I want to find the sums of a set of numbers from a for loop
I currently have
var num = "";
for(var i = 1; i < 11; i +=1){
num = num + i;
}
console.log(num)
which gives me 12345678910 in the JS console
I want to produce 1+2+3+4+5+6+7+8+9+10=SUM
I have tried adding a "+" string:
num = num + i + "+";
but it gives me 1+2+3+4+5+6+7+8+9+10+
My question is how to add the "+" and "=" into the code and get the sum.
If you want the + to display AND the actual sum, then do this
var realSum = 0;
var num = "1";
for(var i = 2; i < 11; i +=1){
realSum = realSum + i;
num = num + "+" + i;
}
num = num + "=" + realSum;
Try this : http://jsfiddle.net/kx9b7qu7/2
Using Eval
var num = [];
for(var i = 1; i < 11; i +=1){
num.push(i)
}
var equation = num.join('+');
var sum = eval(equation);
console.log('Method 1: ',equation + '=' + sum)
Without using Eval
var num = [];
var sum = 0;
for(var i = 1; i < 11; i +=1){
num.push(i)
sum += i
}
var equation = num.join('+');
console.log('Method 2: ',equation + '=' + sum)
Make an util out of it for later use ;) There are also other ways that make use of functional approach (reduce, map) and things that aren't widely supported yet (generators, array comprehensions).
Here are some example functions for consideration and tweaking:
// kind of usual
var sumRange = function (from, to, step) {
var i,
sum = from,
str = from;
for (i = from + step; i <= to; i += step) {
sum += i;
str += '+' + i;
};
str += '=' + sum;
return str;
};
// sum of elements in arithmetic progression
var sumRangeAP = function (from, to, step) {
var i,
n,
str = from;
n = ((to - from) / step) + 1;
for (i = from + step; i <= to; i += step) {
str += '+' + i;
};
str += '=' + ((from + to) / 2) * n;
return str;
};
// memory efficiency (not creating hell a lot of strings) together with some functional stuff
// on the other hand it looks like assignment operators (+, +=) win with .join in terms of speed sometimes
// in many cases, I think, you may not give a shit about whether you use this or that
var sumRangeME = function (from, to, step) {
var i,
sum = from,
str = [from];
for (i = from + step; i <= to; i += step) {
str.push(i);
};
return str.join('+') + '=' + str.reduce(function (prevVal, curVal) { return prevVal + curVal; });
};
console.log(sumRange(0,20,1));
console.log(sumRangeAP(0,20,1));
console.log(sumRangeME(0,20,1));
console.log(sumRange(1,21,1));
console.log(sumRangeAP(1,21,1));
console.log(sumRangeME(1,21,1));
console.log(sumRange(7,36,1));
console.log(sumRangeAP(7,36,1));
console.log(sumRangeME(7,36,1));
In javascript + can also concatenate a string, if that's what seems best - it thinks you are putting two strings together so it concatenates them. Make num start as 0 instead, that should fix it.
Instead of var num="" try with var num=0, because this way the operator + is used as string concatenation. num=0 will do the job.
EDIT: I thought you wanted to see the "math" equation try the following:
var numbers = 0;
for (var i = 1; i < 11; i += 1){
numbers += i;
}
console.log(numbers);
Try this:
var numbers = [];
for (var i = 1; i < 11; i += 1){
numbers.push(i);
}
var string = numbers.join("+");
string += "=" + eval(numbers.join("+"));
console.log(string);
If you're really trying to concatenate then
num = num + "+" + i;
Related
I need to generate 1000 images each with different numbers. Doing this is found a script online which works fine, but it doesn't work with 00 in front of the increments.
I can't just add 00 in front of every number because when it hits 10 it's doing 0010 instead of 010 like I want it to.
That means I need to change the code a bit. And it's probably REALLY basic, but I just can't figure it out. There is no log sadly, because I am running the script in Photoshop.
Here is the code I have trouble with. And underneath is the result:
for (var i=1; i <= numImages; i++) {
if(layer.textItem.contents < 10) {
layer.textItem.contents = "00" + i.toString();
} else if(layer.textItem.contents >= 10) {
layer.textItem.contents = "0" + i.toString();
} else {
layer.textItem.contents = i.toString();
}
SavePNG(directory + imageName + '_'+ i +'.png');
};
Any assistance is highly appreciated! I don't need to be fed by a spoon! I need to learn from my mistakes!
Here is the entire code in the script (Forgot to add this, edited afterwards)
var imageName = 'Oppmoteskjema';
var numImages = 15;
function SavePNG(saveFile){
var pngOpts = new ExportOptionsSaveForWeb;
pngOpts.format = SaveDocumentType.PNG
pngOpts.PNG8 = false;
pngOpts.transparency = false;
pngOpts.interlaced = false;
pngOpts.quality = 10;
activeDocument.exportDocument(new File(saveFile),ExportType.SAVEFORWEB,pngOpts);
}
var layer = activeDocument.layers[0];
if (layer.kind == 'LayerKind.TEXT') {
for (var i=1; i <= numImages; i++) {
layer.textItem.contents = i.toString();
var str = "" + i;
var pad = "000";
var ans = pad.substring(0, pad.length - str.length) + str;
SavePNG(directory + imageName + '_'+ ans +'.png');
}
};```
You could try it this way:
for (var i=1; i <= numImages; i++) {
var str = "" + i;
var pad = "000";
var ans = pad.substring(0, pad.length - str.length) + str;
layer.textItem.contents = ans;
SavePNG(directory + imageName + '_'+ ans +'.png');
};
You can change pad template as you wish. The output of this will be:
1 -> 001
97 -> 097
999 -> 999
1234 -> 1234
If you're just trying to manipulate a variable based off the index of the loop then the below would suffice.
for (var i = 1; i <= 1000; i++) {
// Result will be '00' | '0' | ''
const result = i < 10 ? '00' : i < 100 ? '0' : '';
// The result is prepended to the current index
// Aka (001, 010, 100)
const contents = result + i;
// Set the text item object contents to value of contents
layer.textItem.contents = contents;
// Saves the Image
SavePNG(directory + imageName + '_' + contents + '.png');
}
This
i < 10 ? '00' : i < 100 ? '0' : ''
Is a ternary operator btw, it's essentially a shorthand if statement.
You can add the number to a string of zeroes, and then slice the resulting string based on desired length:
var template = "0000";
var num = 0;
var targetNumber = 1000;
for(let i = 0; i <= targetNumber; i++) {
// add i to the template. Javascript will automatically to this type-coerceon since we're adding string + number
let numStr = template + i;
// strip leading zeroes to match the template length
numStr = numStr.slice(numStr.length - template.length);
console.log(numStr);
}
var n = "reversestrings", k=3;
want to reverse string in chunk of 'k',
Answer would be : ver sre tse nir gs;
if Last word less then 'k' then don't need to reverse.
I am using below code but not getting expected answer.
var n = 'stringreverses', k = 3, str = '', s = '';
var c = 0;
for( var i=0; i<n.length; i++ ){
if( c<k ){
c++
str += n[i];
s=str.split('').reverse().join('');
}
else{
console.log("-" + s);
c=0;
}
}
First we need to split input to chunks with the same size (the last one can be smaller), next we reverse every chunk and concatenate at the end.
var input = "123456",
chunks = input.match(new RegExp('.{1,' + k + '}', 'g'));
var result = chunks.map(function(chunk) {
return chunk.split('').reverse().join('');
}).join('');
Homework or not, here is a good use case to start with strings.
Here is a C approach but you have more in Javascript.
In fact you want to reverse by chunk so deal with chunk. How to create a chunk of string ? a way is to use slice https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/slice
var str = "abcdef";
console.log(str.slice(0,2));
So you have an easy way to slice your string into chunk.
Then you have to iterate over it, there is no good way of doing it actually there is dozen but you could do it from backward to the beginning of the string:
for( i=str.length ; i>0 ; i -= k ){
// i will go from the end of your str to
// the beginning by step of k(=3) and you can use i - k and i
// to slice your string (as we see it before)
// you have to take care of the last part that could be less than
// 3
}
then you have to format the result, the most easy way to do that is to concatenate results into a string here it is :
var strRes = "";
strRes += "res 1";
strRes += "res 2";
console.log(strRes); // should screen "res 1res 2"
As it is homework, I wont make a jsfiddle, you have here all the pieces and it's up to you to build the puzzle.
hope that help
$(function() {
var n = 'reversestrings', k = 3;
var revString = "";
for (var i =0; i<=n.length; i++) {
if (i%k == 0) {
l = parseInt(k) + parseInt(i);
var strChunk = n.substring(i,l);
var innerStr = "";
for (var j =0; j<strChunk.length; j++) {
var opp = parseInt(strChunk.length) - parseInt(j) - 1;
innerStr = innerStr + strChunk.charAt(opp);
}
revString = revString + " "+innerStr;
}
}
alert(revString);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
My take on this. Pure JS without even built-in functions:
function reverseSubStr(str) {
var right = str.length - 1, reversedSubStr = '';
while(right >= 0) {
reversedSubStr += str[right];
right--;
}
return reversedSubStr;
}
function reverseStr(str) {
var initialStr = str, newstr = '', k = 3, substr = ''
for(var i = 1; i <= initialStr.length; i++) {
substr += initialStr[i - 1]; // form a substring
if(i % k == 0) { // once there are 3 symbols - reverse the substring
newstr += reverseSubStr(substr) + " "; // ... and add space
substr = ''; // then clean temp var
}
}
return newstr += substr; // add the remainder of the string - 'gs' - and return the result
}
var str = 'reversestrings';
console.log(reverseStr(str)); //ver sre tse nir gs
I like #Jozef 's approch but here is mine as well for those who are not much into Regex -
//Taking care of Tail Calling
function reverStrInChunk(str, k, r=''){
let index=0, revStr,
res = str.substring(index, k), remStr;
revStr = res.split("").reverse().join("");
remStr = str.substring(k, str.length);
r = r + revStr;
if(remStr.length>k){
return reverStrInChunk(remStr,k, r+" ");
}
else if(remStr.length<k) {
return r +" "+remStr;
}else{
return r +" "+ remStr.split("").reverse().join("");
}
}
var aStr = reverStrInChunk('reversestrings',3);//ver sre tse nir gs
console.log(aStr);
I am currently trying to create a double nested loop that adds a number to itself, given the number of instances you want it to be added by.
So when you input something in the Number, for example "5" and you input "3" for the number of instances, then the following would be printed:
5=5
5+5=10
5+5+5=15
More information on my JsFiddle
<div>
<h2>Loop</h2>
Number
<input type='text' id='tbox'>
<br>
Number of Instances
<input type='text' id='theNumber'>
<button onclick=doubleLoop;>
Add Numbers.
</button>
</div>
<div id="content">
</div>
<script>
function doubleLoop(){
var theText = document.getElementById('tbox').value;
var theNumber = document.getElementById('theNumber').value;
var content = document.getElementById('content');
content.innerHTML = '';
for (var i = 0; i < theNumber; i++) {
content.innerHTML = content.innerHTML + (i + 1) + ')';
//start of the second part of the Double Loop
for (var j = 0; j < (i + 1); j++){
if (i === 0){
content.innerHTML = content.innerHTML + theText + '=' + theText + '<br>';
} else if (i > 0) {
content.innerHTML = content.innerHTML + theText.repeat(j) + '=' + (theText * (i+1));
}
}
}
}
</script>
Here you go
https://jsfiddle.net/mkarajohn/qkn2ef4L/
function createString(number, times) {
/*
* We will create each side of the equation separately and we will concatenate them at the end
*/
var leftSide = '',
rightSide = '',
i;
for (i = 1; i <= times; i++) {
leftSide += number.toString();
if ((times > 1) && (i < times)) {
leftSide += '+';
}
}
rightSide = number * times
return (leftSide + '=' + rightSide);
}
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
output += createString(theText, i);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
If there is something that is not clear feel free to ask.
EDIT: If you are hell bent on doing it with two nested loops, here's how it would go:
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
var leftSide = '',
rightSide = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
leftSide = '';
for (var j = 1; j <= i; j++) {
leftSide += theText.toString();
if ((i > 1) && (j < i)) {
leftSide += '+';
}
}
rightSide = theText * i;
output += (leftSide + '=' + rightSide);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
First things first: You're naming your variables very poorly, it's really difficult to understand what you're trying to do, specially when you don't say what you want directly in the question. doubleLoop says how your function works but not what it does. getMultiplicationProcess would have been a better name. Also, you could be passing the values as arguments and just returning the result, it would look A LOT better.
Anyway, I couldn't figure how you were trying to achieve this. I've renamed your variables and did everything my way. Never name a variable theNumber or theText because doing so says nothing about what information it holds. You could have named them firstInput and secondInput but even that way it would not be clear.
Here's the code, scroll down for explanation:
var submit = document.getElementById("submit"),
firstInput = document.getElementById("tbox"),
secondInput = document.getElementById("theNumber"),
answerField = document.getElementById("content");
submit.addEventListener("click", function () {
answerField.innerHTML = getMultiplicationProcess(Number(firstInput.value), Number(secondInput.value), "<br/>");
});
function getMultiplicationProcess(multiplicand, multiplier, lineBreak) {
var result = "";
for (var i = 0; i < multiplier; ++i) {
for (var j = 0; j < i + 1; ++j) {
if (i === j) {
result += multiplicand + " = " + (multiplicand * (i + 1));
} else result += multiplicand + " + ";
}
result += lineBreak || "\n";
}
return result;
}
JSFiddle
Explanation:
The outer for loop runs as many times as the second input, or multiplier. So if you input 5 and 3 respectively this loop will run three times. It represents each line of the resulting string.
The inner loop runs as many times as the current iteration number of the outer loop more one. So for our example inputs it will run like this:
0: 1; 1: 2; 2: 3;
I use it to place the multiplicand multiple times in the current line.
The first line will contain a single 5 (not including the answer for this multiplication) so j is i + 1 which is 1 because during the first iteration from the outer loop i equals 0:
5 = 5
The second line contains 2 5s and i is 1 because we're in the second iteration for the outer loop, so j = i + 1 = 2 which is how many fives we'll place in the string:
5 + 5 = 10
if it's the last iteration of the inner loop instead of adding "5 + " to the resulting string it places "5 = (i + 1) * multiplier" which will be the result for the current line. Then the inner loop ends, the outer loop adds a line break and restarts the process for the next line.
I have an array of latitudes and longitudes in javascript, like this:
a = [lat1, lon1, lat2, lon2, lat3, lon3, ...] // assert(a.length % 2 = 0)
and I would like to create a string like this:
s = "lat1,lon1 lat2,lon2 lat3,lon3 ..."
that is, each latlon pair has a comma separating the pair, and the pairs are separated by a space.
I'm a bit stuck here (mostly because I know very little of javascript):
function polylineToKml(p)
{
var s = "";
for (var i = 0; i < p.length; i+=2)
{
var lat = p[i];
var lon = p[i+1]
// now what?
}
}
In a more functional way:
function polylineToKml(p) {
return p.map(function(el, i) {
return el + (i % 2 > 0 ? " " : ",");
}).join("").trim();
}
And if your environment supports ES6:
var polylineToKml = p =>
p.map((el, i) => el + (i % 2 > 0 ? " " : ",")).join("").trim();
One way:
var s = [];
for (var i = 0; i < a.length; i+=2)
{
s.push(a[i] + "," + a[i+1]);
}
s = s.join(" ");
function polylineToKml(p) {
var s = "";
for (var i = 0, l = p.length; i < l; i += 2) {
var lat = p[i];
var lon = p[i + 1];
s += lat + ',' + lon;
// don't add a space at the end
if (i !== l - 2) s += ' ';
}
return s;
}
DEMO
one more way...
function polylineToKml(p){
var s = "";
for (var i = 0; i < p.length - 1; i++){
s += p[i] + ",";
}
s += p[p.length - 1];
return s;
}
You should adopt a proper way to organize your data set, one way is to use JSON array with key-value pairs, e.g.
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var a = [1.234, 2.345, 3.456, 5.456, 4.653, 2.567]
var coordinates = [];
for (var i=0; i < a.length; i=i+2){
coordinates[i/2] = {"latitude":a[i], "longitude":a[i+1]}
}
for (var i=0; i < coordinates.length; i++){
document.getElementById("demo").innerHTML +=
coordinates[i].latitude + ", " + coordinates[i].longitude + "<br>";
}
</script>
</body>
</html>
In this way, the coordinates will be represented as such:
coordinates = [
{"latitude":"1.234", "longitude":"2.345"},
{"latitude":"3.456", "longitude":"5.456"},
{"latitude":"4.653", "longitude":"2.567"}
];
Find out more on http://www.w3schools.com/json/default.asp
With an array, how would I append a character to each element in the array? I want to add the string ":" after each element and then print the result.
var a = [54375, 54376, 54377, 54378, 54379, 54380, 54381, 54382, 54383, 54384, 54385, 54386, 54387, 54388, 54389, 54390, 54391, 54392, 54393, 54394, 54395, 54396, 54397, 54400, 54402, 54403, 54405, 54407, 54408];
For example: 54375:54376:54377
a = a.map(function(el) { return el + ':'; });
Or if you want to join them into a string:
var joined = a.join(':');
If you are looking for a way to concatenate all the elements with :, you can use this
var result = "";
for (var i = 0; i < a.length; i += 1) {
result += a[i] + ":";
}
result = result.substr(0, result.length-1);
Or even simpler, you can do
a = a.join(":");
If you are looking for a way to append : to every element, you can use Array.prototype.map, like this
a = a.map(function (currentItem) {
return currentItem + ":";
});
console.log(a);
If your environment doesn't support map yet, then you can do this
for (var i = 0; i < a.length; i += 1) {
a[i] = a[i] + ":";
}