I want the pattern printing using Javascript - javascript

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.

Related

Why does the for loop in my code restart automatically?

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>

count 9's from 1 to n - 5kyu Kata

I am working on this kata https://www.codewars.com/kata/count-9-s-from-1-to-n/train/javascript
and i have written this code for it, but its not working. This question is similar to this one Count the number of occurrences of 0's in integers from 1 to N
but it is different because searching for 9's is practically very different to searching for 0's.
think part of the problem with this code is that it takes too long to run...
any advice appreciated!
function has9(n) {
var nine = [];
var ninearr = n.toString().split('');
for (var j = 0; j < ninearr.length; j++) {
if (ninearr[j] == '9') {
nine.push(ninearr[j]);
}
}
return nine.length;
}
function number9(n) {
var arr = [];
var arrnew = [];
for (var i = 0; i <= n; i++) {
arr.push(i);
}
for (var l = 0; l < arr.length; l++) {
arrnew.push(has9(l));
}
var sum = arrnew.reduce((a, b) => a + b, 0);
return sum;
}
Why not a regex based solution? (Too slow as well?)
const count9s = num => num.toString().match(/9/g).length
console.log(count9s(19716541879)) // 2
console.log(count9s(919191919191919)) // 8
console.log(count9s(999)) // 3
console.log(count9s(999999)) // 6
I have taken the above hint and completely re written the code, which I now feel should work, and it does for most inputs, but codewars is saying it fails on some of them. any ideas why?
function nines(n){
if(n>=100){
var q= Math.floor(n/100);
var nq= q * 20;
var r = (n%100);
var s = Math.floor(r/9);
if (r<=90){
return s + nq;
}
if (r == 99){
return 20 + nq;
}
if (90 < r < 100 && r!= 99){
var t = (r-90);
return nq + s + t;
}
}
if (n<100){
if (n<=90){
var a = Math.floor(n/9);
return a ;
}
if (n == 99){
return 20
}
if (90 < n < 100 && n!= 99){
var c = (n-90);
return 10 + c;
}
}
}
=== UPDATE ===
I just solved your kata using
function number9Helper(num) {
var pow = Math.floor(Math.log10(num));
var round = Math.pow(10, pow);
var times = Math.floor(num / round);
var rest = Math.abs(num - (round * times));
var res = pow * (round==10 ? 1 : round / 10) * times;
if (num.toString()[0] == '9') res += rest;
if (rest < 9) return res;
else return res + number9Helper(rest);
}
function number9(num) {
var res = number9Helper(num);
res = res + (num.toString().split('9').length-1);
return res;
}
== Function below works but is slow ===
So, could something like this work for you:
for (var nines=0, i=1; i<=n; i++) nines += i.toString().split('9').length-1;
Basically, there are many way to achieve what you need, in the end it all depends how do you want to approach it.
You can test it with
function nines(n) {
for (var nines=0, i=1; i<=n; i++) nines += i.toString().split('9').length-1;
return nines;
}
function number9(n) {
if (n < 8) {
return 0
};
if (n === 9) {
return 1
};
if (n > 10) {
let str = ''
for (let i = 9; i <= n; i++) {
str += String(i)
}
return str.match(/[9]/g).length
}
}

Why is my program not working?

I'm trying to write a simple program to calculate the biggest even number from an array.
An array of 10 elements is used.
function biggestEven(array) {
var numberOfNumbers = array.length;
var biggestYet = 0;
var theNumber;
for (var i = 0; i < numberOfNumbers; i++) {
if(array[i] % 2 = 0) {
biggestYet = array[i];
}
if(array[i] % 2 = 0 && array[i] > biggestYet) {
theNumber = biggestYet;
}
}
return theNumber;
}
var myArray = [];
for (var i = 0; i < 10; i++) {
myArray[i] = window.prompt("Enter number " + (i+1) + "of 10:");
}
console.log("The biggest even number is: " + biggestEven(myArray));
Please help I am stuck. The program won't lead in chrome.
You're giving a value, not comparing:
if(array[i] % 2 = 0) {
biggestYet = array[i];
}
And also you were returning the wrong element:
function biggestEven(array) {
var numberOfNumbers = array.length;
var biggestYet = 0;
var theNumber = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] % 2 === 0) {
biggestYet = array[i];
}
if (array[i] % 2 === 0 && array[i] > biggestYet) {
theNumber = biggestYet;
}
}
return biggestYet;
}
var myArray = [];
for (var i = 0; i < 2; i++) {
myArray[i] = window.prompt("Enter number " + (i+1) + " of 10:");
}
console.log("The biggest even number is: " + biggestEven(myArray));
This might help:
console.log(Math.max(...[267, 306, 108, 307].filter(function(value) { return value % 2 === 0 })));
You need to change
if(array[i] % 2 = 0) {
biggestYet = array[i];
}
to
if(array[i] % 2 == 0) {
biggestYet = array[i];
}
Here is a solution for your problem
function biggestEven(array) {
return Math.max(...array.filter(function(num){
return num%2==0;
}));
}
var myArray = [1,2,36,45,51,16,7];
alert(biggestEven(myArray));

How can I check a value in a cell in an array Google Sheets?

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.

Project Euler #23 in JS

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

Categories