add x number of every 10th element - javascript

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 + ",";
}
}

Related

How to create 100 random numbers between 1 and 9999 with 4 digits, and place numbers in 10 rows of 10 numbers?

Having an issue figuring out how to get this solved, and I've searched and looked for answers, but they don't resemble what I'm looking for.
This is beginner stuff, I realize but any help would be highly appreciated.
The code below was given by my teacher and it works for creating one random number. For the life of me I can't figure out how to make this create 100 random numbers and make a 10 x 10 square of them.
eg. 5468 2367 1587 2587 2310 9802 0154 8753 4965 2571
3249 3248 2158 4659 1321 1278 9871 0123 4654 4587
etc. for 10 rows.
<div id="answer"></div>
<script type="text/javascript">
function giveValues() {
var length, zeroes;
var number = Math.round((Math.random() * 9999));
// toString()-method and lenght to set amount of digts
zeroes = 4 - number.toString().length;
for (var j = 1; j <= zeroes; j++) {
number = "0" + number;
}
return number;
}
document.getElementById("answer").innerHTML = giveValues();
I also know that there is if (j % nameofvar == 0) { for making a new line, but am unable to make that work.
Considering that you haven't learned arrays yet, try the following as I think it's best inline with what you're looking for. Here is a Plunker as well http://plnkr.co/edit/LltYPtSfR9Ndo46kYmVN?p=preview.
<div id="answer"></div>
<script>
function giveValues() {
var length, zeroes;
var number = Math.round((Math.random() * 9999));
// toString()-method and lenght to set amount of digts
zeroes = 4 - number.toString().length;
for (var j = 1; j <= zeroes; j++) {
number = "0" + number;
}
return number;
}
var columns = 10;
var total = 100;
var bigString = "";
for (var i=0; i<total; i++) {
if (i != 0 && i % columns == 0) {
bigString += "<br/>";
}
bigString += giveValues(i).toString() + " ";
}
var answer = document.getElementById("answer");
answer.innerHTML = bigString;
</script>
Most basic way:
function lpad(number) {
while (number.toString().length < 4) {
number = "0"+number;
}
return number;
}
var max = 9999;
var matrix = [];
var size = 10;
for (var i = 0; i < size * size; i++) {
if (i % size === 0) {
matrix.push([]);
}
var number = lpad(Math.ceil(Math.random() * max));
matrix[matrix.length - 1].push(number);
}
document.getElementById("answer").innerHTML = matrix.join("<br />");
<div id = "answer"></div>
Using arrays is more effective, but you can also simply concatenate too.
You could just generate a large random number, and then limit it to 4 digits.
Try this:
function giveValues() {
var number = Math.round((Math.random() * 999999999));
return number.toString().substr(0, 4);
}
var arr = [];
for(var i = 0; i < 10; i++){
arr.push([giveValues(), giveValues(), giveValues(), giveValues(), giveValues(), giveValues(), giveValues(), giveValues(), giveValues(), giveValues()]);
}
document.getElementById("answer").innerHTML = arr.join(' <br/>').replace(/,/g,' ');
https://jsfiddle.net/moshekarmel1/34spm4hh/

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.

Javascript: Keep count of even and odd random numbers and get the sum of each

When I run this program I am only getting the even number count and the odd sum. The odd count and even sum just gives me 0 every time.
Does anyone have any idea what I am missing? Thanks!
I am trying to generate 100 random numbers and keep count of the evens/odds and then get the sum of each.
var min = 1;
var max = 1000;
var randomNumArray = []
var oddCount = []
var evenCount = []
var oddSum = []
var evenSum = []
function isEven(x){
if (x % 2 == 0)
return true;
else
return false;
}
function sumOfArray(evenSum){
for(i = 0; i< evenSum.length; i++){
if (isEven){
return(evenSum);
}
else{
return (oddSum);
}
}
}
for( i = 0; i < 100; i++){
var randNumber = Math.floor(min + (Math.random() * max));
randomNumArray.push(randNumber);
}
for( i = 0; i< randNumber.length; i++){
if (isEven(evenCount[i])){
return evenCount;
}
else{
return oddCount;
}
}
console.log('Even Number Count: ' + evenCount);
console.log('Odd Number Count: ' + oddCount);
console.log('Sum Even: ' + evenSum);
console.log('Sum Odd: ' + oddSum);
I would just use 1 function to check if its even or odd and then decide to add the sum by the number itself and the count by 1. You are making it way more complicated and I'm wondering why u are using arrays.
Try something like this:
for( i = 0; i < 100; i++){
var randNumber = Math.floor(min + (Math.random() * max));
if(isEven(randNum)){
evenSum = evensum+randNum;
evenCount ++;
}else{
oddSum= oddSum+randNum;
oddSum++;
}
}
var oddCount = 0
var evenCount = 0
for(i=0; i<randomNumArray.length; i++) {
if(randomNumArray[i] % 2 == 0) {
evenCount++
} else {
oddCount++
}
};
Something like that should work?

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;
};

Function to count how many numbers are there with the digits and division value specified

I started making a function that will be able do the following: Count how many 6 digit numbers you can make with the digits 0,1,2,3,4 and 5, that can be divided by 6?
How I currently try to start, is I make an array of all the possible numbers, then take out every number that has any of the numbers' arrays elements in it, then remove the ones that are not dividable with 6.
I got stuck at the second part. I tried making 2 loops to loop in the array of numbers, then inside that loop, create an other one for the length of the allnumbers array to remove all matches.
Then I would use the % operator the same way to get every element out that doesn't return 0.
The code needs to be flexible. If the user asks for eg. digit 6 too, then the code should still work. Any way I could finish this?
My Code is:
var allnumbers = [],j;
var biggestnumber = "999999999999999999999999999999999999999999999999999999999999";
function howmanynumbers(digits,numbers,divideWith){
if (digits && numbers && divideWith){
for (var i = 0; i < 1+Number(biggestnumber.substring(0,digits)); i++ ){
allnumbers.push(i);
}
for (j = 0; j < numbers.length; j++ ){
var matchit = new RegExp(numbers[j]);
}
//not expected to work, I just had this in for reference
if ( String(allnumbers[i]).match(matchit) != [""]){
j = 0;
allnumbers.splice(i,1);
var matchit = new RegExp(numbers[j])
}
}
else {
return false;
}
}
This is my take on the entire solution:
var i;
var allowedDigitsPattern = /^[0-5]+$/i;
var numbers = [];
for (i = 100000; i < 555555; i++) {
if (allowedDigitsPattern.test(i.toString())
&& i % 6 === 0) {
numbers.push(i);
}
}
And you can look at your results like this:
document.write('There are ' + numbers.length + ' numbers<br>');
// write out the first ten!
for (i = 0; i < 10; i++) {
document.write(numbers[i] + '<br>');
}
Update based on comments...
The configurable version of this would be:
var i;
var lowestDigit = 0;
var highestDigit = 5;
var numberOfDigits = 6;
var allowedDigitsPattern = new RegExp('^[' + lowestDigit + '-' + highestDigit + ']+$', 'gi');
var smallestNumber = '1';
for (i = 1; i < numberOfDigits; i++) {
smallestNumber += '0';
}
var biggestNumber = '';
for (i = 0; i < numberOfDigits; i++) {
biggestNumber += highestDigit.toString();
}
var numbers = [];
for (i = smallestNumber; i < biggestNumber; i++) {
if (allowedDigitsPattern.test(i.toString())
&& i % 6 === 0) {
numbers.push(i);
}
}
document.write('There are ' + numbers.length + ' numbers<br>');
You need to change the smallest and largest numbers based on the configuration. I have made both the allowable digits and the length of the number configurable.

Categories