I'm, starting to learn javascript and I have a problem with this code. The code asks for two numbers (the first must be lower than the second) and then it shows the multiplication from the first to the second number. If you type 5 and 7, it shows the multiplication of 5, 6 and 7.
The problem comes when the second number is typed is 10 (except if you type 1 and 10, it shows all). If I type 2 and 10 it shows nothing.
Thanks in advance.
<script>
function multiply() {
do {
do {
var i1 = prompt("Type first number from 1 to 10", "");
} while (i1 < 1 || i1 > 10);
do {
var i2 = prompt("Type second number from 1 to 10 (number must be higher than the first one", "");
} while (i2 < 1 || i2 > 10);
var check = i2 - i1;
if (check >= 0) {
for (var i = i1; i <= i2 ; i++) {
for (var j = 1; j <= 10; j++) {
document.write("<br>" + i + " x " + j + " = " + i * j);
}
document.write("<p>" );
}
} else {
alert("First number is higher than the second, PLease try again.")
}
} while (check < 0)
}
</script>
The return-value of prompt () is a string. So you need to parseInt() to get integers.
do {
do {
var i1 = parseInt (prompt("Type first number from 1 to 10", ""));
} while (i1 < 1 || i1 > 10);
do {
var i2 = parseInt (prompt("Type second number from 1 to 10 (number must be higher than the first one", ""));
} while (i2 < 1 || i2 > 10);
var check = i2 - i1;
if (check >= 0) {
for (var i = i1; i <= i2 ; i++) {
for (var j = 1; j <= 10; j++) {
document.write("<br>" + i + " x " + j + " = " + i * j);
}
document.write("<p>" );
}
} else {
alert("First number is higher than the second, PLease try again.")
}
} while (check < 0)
Related
I'm trying to output the pascal triangle. So i stored the previous output in an array(for ex:1,2,1).Then i'm trying to obtain sum of two elements in array(like array[0]+array[1] then array[1]+array[2]).But the loop which i use for getting the sum restarts on it's own (i.e after o is equal to array.length-1 o becomes equal to zero.
Also any help with proper code formatting and how i could do this in a better way is welcome.
I have tried setting array length to zero when the variable o is equal to array length but then too loop starts to run again from zero.
var count=0,sum=0;
let arr=[],arr1=[],arr2=[];
//For Rows
for (let i = 1; i <= 4; i++) {
//For Spaces
for (var k = 4; k >= i; k--) {
document.querySelector('#a').innerHTML += " ";
}
//For addition logic (This Restarts automatically)
for (let j = 1; j <= i; j++) {
if (j == 1 || j == i) {
document.querySelector('#a').innerHTML += " " + 1;
} else {
for (let o = 0; o < arr2.length; o++) {
sum += parseInt(arr2[o]);
if (o % 2 == 1 && i > 3) {
document.querySelector('#a').innerHTML += " " + sum;
sum = parseInt(arr2[o]);
}
}
document.querySelector('#a').innerHTML += " " + sum;
}
count += 1;
}
if (i > 1) {
sum = 0;
arr.length = 0, arr1.length = 0, arr2.length = 0;
arr.push(document.querySelector('#a').innerText);
arr1 = Array.from(arr[0]);
arr2 = arr1.filter(rem)
function rem(value) {
return value > 0;
}
var temp = 0;
while (temp < count - i) {
arr2.shift();
temp++;
}
}
document.querySelector('#a').innerHTML += "<br/>";
}
<html>
<head></head>
<body>
<div id="a"></div>
</body>
</html>
1
1 1
1 2 1
1 3 3 1
Expected Result
1
1 1
1 2 1
1 3 3 6 3 1
Actual Result
You could take a loop for getting the wanted length of the array and another for calculating the sum of two elements of the array.
This approach starts with a single element and takes for every round one at start and one at the end and all other value from the array.
var length = 4,
array = [1],
temp,
i,
element = document.querySelector('#a');
element.innerHTML += array.join(' ');
while (array.length < length) {
temp = [1];
for (i = 0; i < array.length - 1; i++) {
temp.push(array[i] + array[i + 1]);
}
temp.push(1);
array = temp;
element.innerHTML += '<br>' + array.join(' ');
}
<div id="a" style="text-align: center"></div>
I need to create java script program who print mirror numbers triangle from N. I tested some ways and get the 50% from task:
let n = 5;
function generatePyramid(num) {
let number = '';
for (let i = 1; i <= num; i += 1) {
console.log(number += i);
}
}
generatePyramid(n);
This code print triangle only from 1 to 5. How to print triangle from 5 to 1?
Also my print need to be with space between 1 2 3 4 5... not 12345.
I have similar code from java with array, but can't transform it to JS: https://pastebin.com/9dqqE8J6
This is the final output:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
One option would be to add a while loop that slices off characters from the number string until it's empty:
let n = 5;
function generatePyramid(num) {
let number = '';
for (let i = 1; i <= num; i += 1) {
console.log(number += i);
}
while (number.length > 1) {
number = number.slice(0, number.length - 1);
console.log(number);
}
}
generatePyramid(n);
To add spaces as well, one option is:
let n = 5;
const log = str => console.log(str.replace(/.(?!$)/g, '$& '))
function generatePyramid(num) {
let number = '';
for (let i = 1; i <= num; i += 1) {
log(number += i);
}
while (number.length > 1) {
number = number.slice(0, number.length - 1);
log(number);
}
}
generatePyramid(n);
<script>
let n = 5;
function generatePyramid(num) {
let number = '';
for (let i = 1; i <= num; i += 1) {
for (let j = 1; j <= i; j += 1)
document.writeln(j+" ");
document.writeln("<br>")
}
for (let i = 4; i >= 1; i -= 1) {
for (let j = 1; j <= i; j += 1)
document.writeln(j+" ");
document.writeln("<br>")
}
}
generatePyramid(n);
</script>
Try This using the same code but i have taken another loop named j
I want to calculate how many Y's & N's appear in an array / range defined:
Cell Range: D4:D42
function myFunction() {
var count = SpreadsheetApp.getActiveSheet().getRange(5, 3, 40, 1);
var numRows = count.getNumRows();
var numCols = count.getNumColumns();
var y = 0;
var n = 0;
for (var i = 1; i <= numRows; i++) {
for (var j = 1; j <= numCols; j++) {
var currentValue = count.getCell(i, j).getValue();
if (currentValue = "y") {
y = y + 1;
} else if (currentValue = "n") {
n = n + 1;
}
}
}
Browser.msgBox("There are " + y + " paid & " + n + " not paid");
}
This returns 40 Y's and 0 N's
Not sure what I am doing wrong here but I think it's a simple fix!
The problem is in this line:
if (currentValue = "y") {
You are assigning "y" to currentValue. To actually check for equality, you should try the "===" operator. Try this and see if it solves your problem:
function myFunction() {
var count = SpreadsheetApp.getActiveSheet().getRange(5, 4, 39, 1);
var numRows = count.getNumRows();
var numCols = count.getNumColumns();
var y = 0;
var n = 0;
for (var i = 1; i <= numRows; i++) {
for (var j = 1; j <= numCols; j++) {
var currentValue = count.getCell(i, j).getValue();
if (currentValue === "y") {
y = y + 1;
} else if (currentValue === "n") {
n = n + 1;
}
}
}
Browser.msgBox("There are " + y + " paid & " + n + " not paid");
}
I also updated the getRange() parameters to match D4:D42. In your code, they matched C5:C44. See the getRange() function documentation.
For a given number N, print the grid as shown below using JavaScript, where N is a positive
integer greater than 2.
Example output for N=3
1 1 1
1 0 1
1 1 1
Example output for N=4
1 1 1 1
1 0 0 1
1 0 0 1
1 1 1 1
function printMatrix(n) {
for (var i = 0; i<n; i++) {
var x = "";
for (var j = 0; j <n; j++) {
if (i == 0 || i == (n-1)) {
x += "1";
} else {
if (j == 0 || j == (n-1) ) {
x +="1";
} else {
x += "0";
}
}
}
$("#result").append(x + "<br>");
}
}
$("#btn").click(function() {
$("#result").empty();
printMatrix($("#index").val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='number' id='index'>
<input type='button' value='print' id='btn'>
<div id="result">
</div>
even if you didn't try anything, there is my working solution :
function printMatrix(n) {
for (var i = 0; i<n; i++) {
var x = "";
for (var j = 0; j <n; j++) {
if (i == 0 || i == (n-1)) {
x += "1";
} else {
if (j == 0 || j == (n-1) ) {
x +="1";
} else {
x += "0";
}
}
}
$("#result").append(x + "<br>");
}
}
printMatrix(5);
You can improve it easily
Here the JSFiddle
Explicit loops are so passé; here's a little something I put together using the ES6 Array.prototype.fill() method:
let makeSquare = (size, hJoin="", vJoin="\n") => {
let m = Array(size).fill(0, 1, size-1);
m[0] = m[size-1] = 1;
let s = Array(size).fill(m.join(hJoin), 1, size-1);
s[0] = s[size-1] = Array(size).fill(1).join(hJoin);
return s.join(vJoin);
};
console.log(makeSquare(5));
console.log(makeSquare(3, " "));
document.body.innerHTML = makeSquare(4, " ", "<br>");
Browser support may vary, in the sense that IE doesn't support .fill(), but there is a .fill() polyfill...
Of course you can't polyfill arrow functions and function argument defaults, but you can rewrite them ES5 style if you care about older IE:
var makeSquare = function(size, hJoin, vJoin) {
if (hJoin === undefined) hJoin = "";
if (vJoin === undefined) vJoin = "\n";
var m = Array(size).fill(0, 1, size-1);
m[0] = m[size-1] = 1;
var s = Array(size).fill(m.join(hJoin), 1, size-1);
s[0] = s[size-1] = Array(size).fill(1).join(hJoin);
return s.join(vJoin);
};
Demo with polyfill that works in IE.
My results for numbers between 1 and 28321 (limit)
sum of all numbers: 395465626
sum of all abundant numbers: 392188885
sum of all non abundant numbers: 3276741 (correct answer is 4179871)
var divisors = function(number){
sqrtNumber = Math.sqrt(number);
var sum = 1;
for(var i = 2; i<= sqrtNumber; i++)
{
if (number == sqrtNumber * sqrtNumber)
{
sum += sqrtNumber;
sqrtNumber--;
}
if( number % i == 0 )
{
sum += i + (number/i);
}
}
if (sum > number) {return true;}
else {return false;}
};
var abundent = [], k = 0;
var upperLimit = 28123;
for (var i = 1; i <= upperLimit; i++)
{
if (divisors(i))
{abundent[k] = i; k++};
}
var abundentCount = abundent.length;
var canBeWrittenAsAbundant = [];
for (var i = 0; i < abundentCount; i++){
for (var j = i; j < abundentCount; j++){
if (abundent[i] + abundent[j] <= upperLimit){canBeWrittenAsAbundant[abundent[i]+abundent[j]] = true;}
else {
break;
}
}
}
for (i=1; i <= upperLimit; i++){
if (canBeWrittenAsAbundant[i] == true){continue;}
else {canBeWrittenAsAbundant[i] = false;}
}
var sum = 0;
for (i=1; i <= upperLimit; i++)
{
if (!canBeWrittenAsAbundant[i]){
sum += i;
}
}
console.log(sum);
I'm using http://www.mathblog.dk/project-euler-23-find-positive-integers-not-sum-of-abundant-numbers/ as guidance, but my results are different. I'm a pretty big newb in the programming community so please keep that in mind.
You do not need to calculate the sum of all numbers using a cycle, since there is a formula, like this:
1 + 2 + ... + number = (number * (number + 1)) / 2
Next, let's take a look at divisors:
var divisors = function(number){
sqrtNumber = Math.sqrt(number);
var sum = 1;
for(var i = 2; i<= sqrtNumber; i++)
{
if (number == sqrtNumber * sqrtNumber)
{
sum += sqrtNumber;
sqrtNumber--;
}
if( number % i == 0 )
{
sum += i + (number/i);
}
}
if (sum > number) {return true;}
else {return false;}
};
You initialize sum with 1, since it is a divisor. However, I do not quite understand why do you iterate until the square root instead of the half of the number. For example, if you call the function for 100, then you are iterating until i reaches 10. However, 100 is divisible with 20 for example. Aside of that, your function is not optimal. You should return true as soon as you found out that the number is abundant. Also, the name of divisors is misleading, you should name your function with a more significant name, like isAbundant. Finally, I do not understand why do you decrease square root if number happens to be its exact square and if you do so, why do you have this check in the cycle. Implementation:
var isAbundant = function(number) {
var sum = 1;
var half = number / 2;
for (var i = 2; i <= half; i++) {
if (number % i === 0) {
sum += i;
if (sum > number) {
return true;
}
}
}
return false;
}
Note, that perfect numbers are not considered to be abundant by the function.
You do not need to store all numbers, since you are calculating aggregate data. Instead, do it like this:
//we assume that number has been initialized
console.log("Sum of all numbers: " + ((number * (number + 1)) / 2));
var abundantSum = 0;
var nonAbundantSum = 0;
for (var i = 0; i <= number) {
if (isAbundant(i)) {
abundantSum += i;
} else {
nonAbundantSum += i;
}
}
console.log("Sum of non abundant numbers: " + nonAbundantSum);
console.log("Sum of abundant numbers: " + abundantSum);
Code is not tested. Also, beware overflow problems and structure your code.
Below is the Corrected Code for NodeJS..
var divisors = function (number) {
sqrtNumber = Math.sqrt(number);
var sum = 1;
var half = number / 2;
for (var i = 2; i <= half; i++) {
if (number % i === 0) { sum += i; }
}
if (sum > number) { return true; }
else { return false; }
};
var abundent = [], k = 0;
var upperLimit = 28123;
for (var i = 1; i <= upperLimit; i++) {
if (divisors(i)) { abundent[k] = i; k++ };
}
var abundentCount = abundent.length;
var canBeWrittenAsAbundant = [];
for (var i = 0; i < abundentCount; i++) {
for (var j = i; j < abundentCount; j++) {
if (abundent[i] + abundent[j] <= upperLimit) { canBeWrittenAsAbundant[abundent[i] + abundent[j]] = true; }
else {
break;
}
}
}
for (i = 1; i <= upperLimit; i++) {
if (canBeWrittenAsAbundant[i] == true) { continue; }
else { canBeWrittenAsAbundant[i] = false; }
}
var sum = 0;
for (i = 1; i <= upperLimit; i++) {
if (!canBeWrittenAsAbundant[i]) {
sum += i;
}
}
console.log(sum);