Javascript multiplication table specifics - javascript

I am trying to complete a multiplication table but am running into an issue, this is my code...
function multiTable(number) {
var table = '';
for (i = 1; i < 11; i++) {
if (i == 1 || number == 2 || number == 3 || number == 4 || number == 5 || number == 6 || number == 7 || number == 8 || number == 9) {
table += i + " * " + number + " = " + (i * number) + "\n";
} else if (i = 10) {
table += i + " * " + number + " = " + (i * number);
}
}
return table;
}
When I put it through the tests provided I get ...
'1 * 5 = 5\n2 * 5 = 10\n3 * 5 = 15\n4 * 5 = 20\n5 * 5 = 25\n6 * 5 = 30\n7 * 5 = 35\n8 * 5 = 40\n9 * 5 = 45\n10 * 5 = 50\n'
I am supposed to get ...
'1 * 5 = 5\n2 * 5 = 10\n3 * 5 = 15\n4 * 5 = 20\n5 * 5 = 25\n6 * 5 = 30\n7 * 5 = 35\n8 * 5 = 40\n9 * 5 = 45\n10 * 5 = 50'
To save anyone some time the only difference is the very end, the \n after 50.
I don't know if this will help but this is the test:
Test.describe("Basic tests",() => {
Test.assertEquals(multiTable(5), '1 * 5 = 5\n2 * 5 = 10\n3 * 5 = 15\n4 * 5 = 20\n5 * 5 = 25\n6 * 5 = 30\n7 * 5 = 35\n8 * 5 = 40\n9 * 5 = 45\n10 * 5 = 50');
})

function multiTable(number) {
var table = '';
for(var i = 1; i < 10; i += 1){ // print 9 times with \n
table += i + " * " + number + " = " + (i * number) + "\n";
}
table += 10 + " * " + number + " = " + (10 * number); // and last line
return table;
}
console.log(multiTable(5));
.as-console-wrapper { max-height: 100% !important; top: 0; }

i figured out the solution here it is
function multiTable(number) {
var table = '';
for(i=1;i<11;i++){
if(i === 10){
table += i+ " * " +number+ " = " +(i*number);
}else{
table += i+ " * " +number+ " = " +(i*number)+ "\n";
}
}
return table;
}

Related

Find all possible combinations which make a specific number JavaScript

My problem is I have a number for example 17; I also have three other constant numbers: 2, 5, 7;
I need to find all possible combinations which make the specific number 17 or any other number;
5 + 5 + 7 = 17 (1 combination)
5 + 5 + 5 + 2 = 17 (2 combinations)
2 + 2 + 2 + 2 + 2 + 7 = 17 (3 combinations)
2 + 2 + 2 + 2 + 2 + 2 + 5 = 17 (4 combinations)
So the answer is 4.
I created my script which working correctly with the number 17 but wrong with bigger numbers as 20 or 30. How to make it working with all numbers ?
const seek = 30;
const firstNum = 2;
const secondNum = 5;
const thirdNum = 7;
let combinations = 0;
const maxDivisor = Math.round(seek / 2);
for (let i = 1; i <= maxDivisor; i += 1) {
if (secondNum * i + thirdNum === seek) {
combinations++
} else if (secondNum * i + firstNum === seek) {
combinations++
} else if (firstNum * i + secondNum === seek) {
combinations++
} else if (firstNum * i + thirdNum === seek) {
combinations++
} else if (thirdNum * i + firstNum === seek || thirdNum * i + secondNum === 0) {
combinations++
} else if (firstNum + secondNum + thirdNum === seek) {
combinations++
} else if (firstNum * i === seek || thirdNum * i === seek || secondNum * i === seek) {
combinations++
}
}
console.log(combinations);
Simple solution is to first calculate max multipliers for each number and then keep summing all the possible combinations.
/** LOGIC **/
function getCombinations(inputNumber, pieceNumbers) {
const combinations = []
const initial = maxes(inputNumber, pieceNumbers);
let divs = initial;
const sum = createSum(pieceNumbers);
while (!allZeros(divs)) {
if (sum(divs) === inputNumber) {
combinations.push(divs);
}
divs = decrement(divs, initial);
}
return combinations;
}
/**
* returns max multiplier for each number
* that is less than input number
* ie. for [2, 5] and input 17
* you get [8 (17 / 2); 3 (17 / 5)]
*/
function maxes(inputNumber, pieceNumbers) {
return pieceNumbers.map((num, i) =>
inputNumber / num | 0
)
}
/**
* decrements list of numbers till it contains only zeros
* if we have divs [2, 0] and initial [2, 5] the result
* will be [1, 5]
*/
function decrement(divs, initial) {
const arr = divs.slice();
let i = arr.length;
while (i--) {
if (arr[i] > 0) {
return [...arr.slice(0, i), arr[i] - 1, ...initial.slice(i + 1)];
}
}
}
function allZeros(divs) {
return divs.every(div => div === 0);
}
function createSum(pieceNumbers) {
return (divs) => divs.reduce((acc, itm, i) => acc + itm * pieceNumbers[i], 0);
}
function toPrint(combinations, pieceNumbers) {
const printable = combinations.map(nums =>
nums.map(
(n, i) => Array(n).fill(pieceNumbers[i]).join(" + ")
)
.filter(x => x)
.join(" + ")
).join("\n");
return printable;
}
/** VIEW **/
const addPieceEl = document.querySelector(".js-add-piece-number");
const removePieceEl = document.querySelector(".js-remove-piece-number");
const calculateEl = document.querySelector(".js-calculate");
const displayEl = document.querySelector(".js-display-result");
addPieceEl.addEventListener("click", () => {
addPieceEl.insertAdjacentHTML("beforebegin", ` <input type="number" class="js-piece-number number" value="7" /> `)
})
removePieceEl.addEventListener("click", () => {
addPieceEl.previousElementSibling.remove()
})
calculateEl.addEventListener("click", () => {
const inputNumber = Number(document.querySelector(".js-input-number").value);
const pieceNumbers = Array.from(document.querySelectorAll(".js-piece-number")).map(el => Number(el.value))
const combinations = getCombinations(inputNumber, pieceNumbers);
const total = `There are ${combinations.length} combinations for ${inputNumber} with ${pieceNumbers.join(", ")}:\n`;
displayEl.textContent = total + toPrint(combinations, pieceNumbers);
});
.number {
width: 30px;
}
Input Number: <input type="number" class="js-input-number number" value="17"/>
<br/>
<br/>
Piece Numbers:
<input type="number" class="js-piece-number number" value="2"/>
<input type="number" class="js-piece-number number" value="5"/>
<input type="number" class="js-piece-number number" value="7"/>
<button class="js-add-piece-number">+</button>
<button class="js-remove-piece-number">-</button>
<br/>
<br/>
<button class="js-calculate">calculate</button>
<pre class="js-display-result"/>
You can test all combinations
const n = 30;
console.log('Number to reach: n = ' + n);
const k = [7, 5, 2];
console.log('Numbers to use: k = ' + k);
console.log('n can be wrote: n = a*k[0] + b*k[1] + c*k[2]');
console.log('Let\'s found all combinations of [a, b, c]');
let t = [];
for (let a = 0; n >= a*k[0]; a++)
for (let b = 0; n >= a*k[0] + b*k[1]; b++)
for (let c = 0; n >= a*k[0] + b*k[1] + c*k[2]; c++)
if (n == a*k[0] + b*k[1] + c*k[2])
t.push([a, b, c]);
console.log('Number of combinations: ' + t.length);
for (let i = 0; i < t.length; i++)
console.log(
n + ' = ' + new Array()
.concat(new Array(t[i][0]).fill(k[0]).join(' + '))
.concat(new Array(t[i][1]).fill(k[1]).join(' + '))
.concat(new Array(t[i][2]).fill(k[2]).join(' + '))
.filter(e => e.length > 0)
.join(' + ')
);
I am assuming you only want solutions that are unique in the sense that 2+5 and 5+2 aren't unique.
Using recursion you can create an algorithm that can solve this problem for every number and every list of constants.
const seek = 17;
const numbs = [2,5,7];
const minNum = Math.min(...numbs);
let numberOfCombinations = 0;
seekCombinations(seek, numbs);
function seekCombinations (toSeek, numbs) {
for (let i = 0; i < numbs.length; i++) {
let newToSeek = toSeek - numbs[i];
if (newToSeek === 0) { //you found a combination
numberOfCombinations++;
} else if (newToSeek >= minNum) { //The new number to seek can still form a combination
//remove numbers from your list of constants that are smaller then then the number that is already in your current combination so you'll only get unique solutions.
let index = numbs.indexOf(numbs[i]);
let newNumbs = numbs.slice(index, numbs.length);
//recursively call seekCombinations
seekCombinations (newToSeek, newNumbs, currentCombination)
}
}
}
so whats the question?
whats wrong with your script or how to do it?
in case you missed it,
multiplying the number with i doesnt solve this problem. because:
30 = 2 + 2 + 5 + 7 + 7 + 7
30 = 2 + 2 + 2 + 5 + 5 + 7 + 7
any number of one of those 3 constants can appear there.
these cases are not covered by your script

How do I print a reversed times table in Javascript

I'm trying to print to screen this times table in reverse like the photo but can't figure what I need to change to do that.
var digit = 9, multiplier = 9, textresult = "", result = 0;
while (digit > 0) {
for (multiplier = 9; multiplier >= digit; multiplier--) {
result = digit * multiplier;
if (digit == multiplier) {
textresult += digit + " x " + multiplier + " = " + result + "
<br>";}
else {
textresult += digit + " x " + multiplier + " = " + result +
" ";}
}
digit--;}
strong textdocument.write(textresult);
any Ideas?
Try this correction
var digit = 1,
textresult = "<pre><code>",
max = 9;
while (digit <= max) {
for (var multiplier = digit; multiplier <= max; multiplier++) {
var result = digit * multiplier;
textresult += digit + " * " + multiplier + " = " + result;
if (10 > result) {
textresult += " ";
}
if (max == multiplier) {
textresult += "<br/>";
} else {
textresult += " ";
}
}
digit++;
}
textresult += "</pre></code>";
document.write(textresult);
Count from digit of 1 up, rather than from 9 down. On each inner loop, initialize multiplier to digit instead of 9, and similarly, count up with multiplier:
var digit = 1,
textresult = "";
while (digit < 10) {
for (let multiplier = digit; multiplier < 10; multiplier++) {
const result = digit * multiplier;
textresult += digit + " x " + multiplier + " = " + result + (multiplier === 9 ? '<br>' : " ");
}
digit++;
}
document.write(textresult);

Nested loops counting upwards and downwards with stars

I'm trying to solve task with the usage of nested loops. My code below
var n = 5;
var lineOfStars = '';
for (var i = 1; i <= 10; i++) {
for (var j = 1; j <= n; j++) {
if (j <= i) { // 1 <= 5 - 1 - 1 (3)
lineOfStars += ' * ';
} else {
lineOfStars += ' ' + j + ' ';
}
}
lineOfStars += '\n';
}
console.log(lineOfStars);
The result that im looking for is (i want to do it only with nested loops):
* 2 3 4 5
* * 3 4 5
* * * 4 5
* * * * 5
* * * * *
* * * * *
* * * * 5
* * * 4 5
* * 3 4 5
* 2 3 4 5
The code that ive shown does only half of the job. I need help. Thanks in advance
This is closer to what you are wanting, still working on it.
var n = 5;
var lineOfStars = '';
let i, j
for (i = 1; i <= 5; i++) {
for (j = 1; j <= n; j++) {
if (j <= i) {
lineOfStars += ' * ';
} else {
lineOfStars += ' ' + j + ' ';
}
}
lineOfStars += '\n';
}
console.log(lineOfStars)
for (j = 5; j <= 5; j--) {
if (j == 0) break;
for (i = 5; i <= n; i--) {
if (0 == 0) break;
if (i <= j) {
lineOfStars += ' ' + i + ' ';
} else {
lineOfStars += ' * ';
}
}
lineOfStars += '\n';
}
let rev = lineOfStars.split('\n').reverse()
for (let z = 1; z <= rev.length - 1; z++) {
if (rev[z].length != 0) {
console.log(rev[z])
lineOfStars += rev[z]
lineOfStars += '\n';
}
}
console.log(lineOfStars)

Javascript loop calculation

Using the below script
var lvl = 0;
var HappB = 5;
var DecoX = 5;
var DecoY = 5;
while (lvl < 5) {
document.ofrm.UpgSD.value += Math.ceil((Math.exp((HappB + lvl) / ((DecoX * DecoY) * 1.8))) * 1 * 130000 * (Math.tanh((lvl + 1) / 20)) * (Math.tanh((lvl + 1) / 20)));
lvl++;
}
<form name="ofrm">
<input type="text" name="UpgSD" size="50" tabindex="1">
</form>
The result is
363147633676050952513778
The expected output is
363 + 1476 + 3367 + 6050 + 9525 + 13778 = 34559
How can I fix this?
Here's an updated code.
1. Your loop condition needs to be corrected.
2. .value is string. You can set to a variable and then attach it.
var lvl = 0;
var HappB = 5;
var DecoX = 5;
var DecoY = 5;
var number = 0;
while (lvl <= 5) {
number += Math.ceil((Math.exp((HappB + lvl) / ((DecoX * DecoY) * 1.8))) * 1 * 130000 * (Math.tanh((lvl + 1) / 20)) * (Math.tanh((lvl + 1) / 20)));
lvl++;
}
document.ofrm.UpgSD.value = number;
<form name="ofrm">
<input type="text" name="UpgSD" size="50" tabindex="1">
</form>
It looks like document.ofrm.UpgSD.value is being cast into a string (rather than a number).
var lvl = 0;
var HappB = 5;
var DecoX = 5;
var DecoY = 5;
var initialValue = parseInt(document.ofrm.UpgSD.value);
while (lvl < 5) {
initialValue += Math.ceil((Math.exp((HappB + lvl) / ((DecoX * DecoY) * 1.8))) * 1 * 130000 * (Math.tanh((lvl + 1) / 20)) * (Math.tanh((lvl + 1) / 20)));
lvl++;
}
document.ofrm.UpgSD.value = initialValue;

How do I call a function inside a if...else statement?

Is it possible to call a function inside an if else in a function. I want to make a function, who use if else to call 1 function in each.
Live demo
The first js code to call the other functions:
function randomClick(number){
var gamerand = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
if (gamerand == 1){
loseClick();
}else{
winClick();
};
Lose function:
function loseClick(number){
var rand = Math.floor(Math.random() * (150 - 75 + 75)) + 1;
var rprand = Math.floor(Math.random() * (5 - 1 + 1)) + 1;
var xprand = Math.floor(Math.random() * (200 - 100 + 100)) + 1;
xp = parseInt(xp) + xprand;
cookies = parseInt(cookies) + rand;
rp = parseInt(rp) + rprand;
losses = parseInt(losses) + 1;
}
Win function:
function winClick(number){
var rand = Math.floor(Math.random() * (200 - 100 + 100)) + 1;
var rprand = Math.floor(Math.random() * (20 - 1 + 1)) + 1;
var xprand = Math.floor(Math.random() * (300 - 150 + 150)) + 1;
xp = parseInt(xp) + xprand;
cookies = parseInt(cookies) + rand;
rp = parseInt(rp) + rprand;
wins = parseInt(wins) + 1;
}
Thanks in advance.
You have a missing } for your function randomClick
function randomClick(number){
var gamerand = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
if (gamerand == 1){
loseClick();
}else{
winClick();
}
}//This was missing
You missed the } of else inside randomClick().
You can use ternary operator as follow:
function randomClick(number) {
var gamerand = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
gamerand == 1 ? loseClick() : winClick();
}
Demo: http://jsfiddle.net/tusharj/omo9yv9q/5/
You have a missing }. It should work without problems with this fix.
function randomClick(number){
var gamerand = Math.floor(Math.random() * (3 - 1 + 1)) + 1;
if (gamerand == 1){
loseClick();
}else{
winClick();
// missing one bracket here
};

Categories

Resources