How to print this pattern using javascript - javascript

I am trying to print this pattern using javascript
10
10 20
10 20 30
10 20 30 40
10 20 30 40 50
So far I've tried a for loop
for (i=10; i<=50; i+=10){
document.write(i+' \b');
}
How should I enhance the code?

var i, p = [];
for (i=10; i<=50; i+=10){
p.push(i);
document.write(p.join(' ') + '<br>');
}
Edit for #macmee
var i, p = [];
for (i=1; i<=5; i++){
p.push(i*10);
document.write(p.join(' ') + '<br>');
}

This leaves no trailing spaces at the end of any lines.
var p = "";
for (var i = 10; i <= 50; i += 10){
p += ' ' + i;
document.write(p.trim() + '<br>');
}

Ignoring the issues with using document.write for a task like this:
var prevEntry = "";
for (i=10; i<=50; i+=10){
prevEntry += i+' \b';
document.write(prevEntry + '<br>');
}

This seems like a homework question because document.write should really never be used, but anyway:
// store answer here
var str = '';
// makes sure 1 number is printed on line 1, 2 on line 2, etc
for(var i = 0; i < 5; i++) {
// makes sure 1 number is printed on row 1, 2 on row 2, etc
for(var j = 0; j <= i; j++) {
str += (j+1)*10 + ' ';
}
str += '<br>';
}
// write it to the document (please consider using jquery instead)
document.write(str);

Related

add x number of every 10th element

I want to add number of every 10th element.
For example,
function myFunction() {
for (var i = 1; i <= 100; i++)
{
var d = i;
document.getElementById("demo").innerHTML += d+"<br/>";
}
}
Output:
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100
But, I want like this
1,2,3,4,5,6,7,8,9,10,16,17,18,19,20,21,22,23,24,25,31,32,33,34,35,36,37,38,39,40....
I want to add 5 after 10th number, add 10 after 20th number, add 15 after 30th number, add 20 after 40th number, add 25 after 50th number. I know this is simple. But, I couldn't get any result.
JsFiddle
You could take an offset and increment this value by five if the result of the index variable is dividable by ten.
var i,
offset = 0,
result = [];
for (i = 1; i <= 100; i++) {
result.push(i + offset);
if (i % 10 === 0) offset += 5;
}
console.log(result.join(' '));
You could use the modulo operator % to check if the current number (i) is a multiple of 10, then if it is, add 5 to i:
if (i % 10 === 0) {
i += 5;
}
Moreover, I recommend that you keep a string of all the numbers you want to append to your page, as querying and adding contents to the DOM each loop iteration is an expensive operation which can be avoided
See example below:
function myFunction() {
var resultStr = ""
for (var i = 1; i <= 100; i++) {
resultStr += i + "<br/>";
if (i % 10 === 0) {
i += 5;
}
}
document.getElementById("demo").innerHTML += resultStr;
}
myFunction();
<div id="demo"></div>
I used a counter to account for in increment on the 10th element, and am simply putting the results on the console. Obviously there are some that would simply just add 5, the counter option is just a design preference.
var arr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21];
function myFunction(arr){
var counter = 0;
for(var i = 0; i<arr.length; i++){
if (i%10 ==0){
counter++;
}
arr[i] = arr[i]+(5*(counter-1));
}
console.log(arr);
};
myFunction(arr);
Do something like:
function myFunction() {
for (var i = 1; i <= 100; i++)
{
var j=Math.floor(i/10);
var x=5*j;
var d = x+i;
document.getElementById("demo").innerHTML += d+"<br/>";
}
}
Expanding on the performance issue presented by Nick Parsons
var resultStr = ""
for (var i = 1; i <= 100; i++) {
resultStr += i + "<br/>";
if (i % 10 === 0) {
i += 5;
}
}
document.getElementById("demo").innerHTML += resultStr;
innerHTML is just horribly slow.
Consider the following code that employs a document fragment and the vanilla .append() method
const fragment = document.createDocumentFragment();
for (var i = 1; i <= 100; i++)
{
if( i % 10 === 0 )
i += 5;
fragment.append( document.createTextNode( i ) );
fragment.append( document.createElement('BR') );
}
document.getElementById('demo').append( fragment );
From my testing, it's about 2000(!) times faster to use a document fragment.
Change your fucntion like that:
function myFunction() {
for (var i = 1; i <= 100; i++) {
var d = i;
if (i > 1 && i % 10 === 1) {
d = (i % 10) * 5 + i;
}
document.getElementById("demo").innerHTML += d + ",";
}
}

Nested Loop to add numbers

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.

Quickest way to achieve this sequence?

I'm trying to create a simple algorithm that builds an array with a dynamic length.
Then, it will, one by one, replace an item, and then two, then three and so on until the only items left are the first and last.
like this:
12345
1*345 // it never touches the first
12*45
123*5 // it doesn't ever touch the last item
1**45
12**5
1***5 // done, nowhere else to go
I put together a simple demo to show what I'm trying to do.
var length = 6,
array = [],
log = document.getElementById("log"),
edited,
j,
i;
for (i = 1; i <= length; i++) {
array.push(i);
}
log.innerHTML += array.join(" ") + "<br><br>";
for (i = 1; i < (length - 1); i++) {
edited = array.concat();
for (j = i; j < (length - 1); j++) {
edited[j] = "*";
log.innerHTML += edited.join(" ") + "<br>";
}
log.innerHTML += "<br>";
}
Fiddle
It works fine, the only problem is it's out of order.
Right now it seems to only iterate by number of asterisks, then by index. I need it to do the opposite.
// it does this
12345
1*345
1**45
1***5
12*45
12**5
123*5 // out of order
If someone could help that would be great because I am really at a loss!
This should get it done.
var a = 6, // array length
b = [], // array
log = document.getElementById("log"),
c,
d,
e;
for (c = 1; c <= a; c++) {
b.push(c);
}
log.innerHTML += b.join(" ") + "<br><br>";
//the size of the asterisk chunk
for(i = 1; i < b.length - 1; i ++)
{
//position to start asterisk chunk
for(j = 1; j < b.length - i; j ++)
{
var tempArr = b.concat();
//the position inside of the asterisk chunk
for(k = 0; k < i; k ++)
{
tempArr[k + j] = "*";
}
log.innerHTML += tempArr.join(" ") + "<br>";
}
}
JSFiddle
This seems to work well:
str = "1234567"
len = str.length;
for(var stars = 1; stars < len - 1; stars++) {
for(var pos = 1; pos < len - stars; pos++) {
var s = str.substr(0, pos)
+ new Array(stars + 1).join("*")
+ str.substr(pos + stars);
document.write(s + "<br>");
}
}

Loop to print iterations separated with a comma, with no comma at the end

I'm a student and am writing a JavaScript "for" loop that prints into innerHTML. Every concatenation of the string is added to the last followed by a comma. how do I make it so the comma is not printed after the last iteration? Just for piece of mind, the commas aren't part of the assignment, I'm just trying to add practical application. no jQuery tho please
window.onload = function(){
var mySeven = 0;
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
mySeven += i;
printSeven.innerHTML += i + ',' + ' ';
}
}
};
Thanks!
You should use join() instead. It's much cleaner and you don't need to worry about edge cases:
var printSeven = document.getElementById('multiples_seven');
var sevens = [];
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
sevens.push(i);
}
}
printSeven.innerText = sevens.join(", ");
Or an approach that avoids the if() statement and unnecessary iterations:
var printSeven = document.getElementById('multiples_seven');
var sevens = [];
for (i = 7; i <= 1000; i += 7){
sevens.push(i);
}
printSeven.innerText = sevens.join(", ");
And for the sake of understanding, here's how you could do this without join():
var printSeven = document.getElementById('multiples_seven');
var maxValue = 1000;
var list = "";
for (i = 7; i <= maxValue; i += 7){
list += i;
if(i + 7 <= maxValue){
list += ", ";
}
}
printSeven.innerText = list;
Use this function:
function reorderData(){
var sevens = Array();
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
sevens.push(i);
}
}
var newDisplaySelectedArray = sevens.join(",");
jQuery( "#multiples_seven" ).val(newDisplaySelectedArray);
}
First off it is better to not manipulate the DOM inside a loop. You should construct your output in a string or array then add it to the DOM in a single operation :
window.onload = function () {
var mySeven = '';
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
mySeven += i + ', ';
}
}
printSeven.innerHTML += mySeven;
};
To delete the trailing comma you have two options : don't add it in the first place or remove it before adding it to the DOM.
Most other answers have concentrated on not adding it, here is a solution which removes it :
window.onload = function () {
var mySeven = '';
var printSeven = document.getElementById('multiples_seven');
for (i=1; i <= 1000; i++){
if (i % 7 == 0){
mySeven += i + ', ';
}
}
printSeven.innerHTML += mySeven.slice (0, -2);
};
A word of caution, if your for loop does not execute at least one iteration you may remove characters you want to display. In the generic case it is easier to build an array and use the join function as shown in other answers here.
It's easier to check if you are at the first item than if you are at the last, so simply add the commas before the number:
window.onload = function(){
var mySeven = 0;
var printSeven = '';
for (i = 1; i <= 1000; i++) {
if (i % 7 == 0){
mySeven += i;
printSeven += (printSeven.length > 0 ? ', ' : '') + i;
}
}
document.getElementById('multiples_seven') += printSeven;
};

Count numbers and output one char at time

I've tried hard, but I just can't figure it out.
I want to output numbers, but only one character of the number at time. I need to create something like this:
This should be created within a for-loop:
http://jsfiddle.net/jv7H8/
But as you can see there is more than one character in a cell when number > 10.
The desired result should be for example:
1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 1, 1, 1, 2, 1, 3, 1, 4....
Any suggestions? :)
First concatenate the numbers into a string:
var s = '';
for (var i = 1; i <= 42; i++) s += i.toString();
Then loop the characters in the string:
for (var i = 0; i < s.length; i++) {
// output s[i]
}
Here is your jsfiddle updated with my approach: http://jsfiddle.net/jv7H8/2/
The pertinent aspects that I changed was adding a for loop that processed through the length of the number you were going to output:
var str = number.toString(); // the current number as you're looping through
for (var k = 0; k < str.length; k++) {
var oneLetterAtATime = str.charAt(k); // get the digits one at a time
output += "<td>" + oneLetterAtATime + "</td>";
}
number++;
Edit: If you need there to only be nineteen columns, then you'll need to update your column counter for every instance where you are displaying another <td> but not looping back around to increment your column counter. I.e.,
if (k > 0) {
j++;
}
Here is an updated version displaying how this would work: http://jsfiddle.net/jv7H8/21/
Notably, there isn't a very good way to not go past the 19th column when you are in the middle of displaying a number in the 19th column that has more than one digit.
Take all the characters in a string like this:
var t = '';
var limit=100;
for (var j = 1; j<= limit; j++) t += j.toString();
var output='';
for (var j = 0; j < t.length; j++) {
output=output+','+t[i];
}
alert(output);
Please check your updated fiddle here
This will server your purpose.
Following is the code, most of it is your code only:
rows = 3;
columns = 19;
number = 1;
var str = "";
output = '<table style="width:100%;">';
for(var i = 0; i < rows; i++) {
output += "<tr>";
for(var j = 0; j < columns; j++) {
output += "<td>" + number + "</td>";
str +=number;
number++;
}
output += "</tr>";
}
output += "</table>";
$("#game").html(output);
var strvalue="";
$.each(str, function(e,v){
if (e > 0){
strvalue = strvalue + ", "+ v;
}
else{
strvalue += v;
}
});
alert(strvalue);

Categories