Why is the infinite loop error happening? - javascript

I can't understand why does it say it will create an infinite loop.It doesn't seem like it will.What's the problem?
function smallestCommons(arr) {
var max = arr.reduce(function (a, b) {
return Math.max(a, b);
});
var min = arr.reduce(function (a, b) {
return Math.min(a, b);
});
var allNums = [];
for (var i = min; i <= max; i++) {
for (var j = 1; j <= (max ^ 3); i++) {
allNums.push(i * j);
}
}
}
smallestCommons([1, 6]);

for(var j=1;j<=(max^3);i++)
Should be
for(var j=1;j<=(max^3);j++)

Looks like j is never increasing so it always matches the condition in j<=(max^3) inside your for loop.
I think there is a typo:
for(var j=1;j<=(max^3);i++) {
should be
for (var j=1; j <= (max^3); j++) {

You have to change for(var j = 1 ; j <= (max^3) ; i++) to for(var j = 1 ; j <= (max^3) ; j++)

Your nested for loop never increments your var j.
for (var i = min; i <= max; i++) {
for (var j = 1; j <= (max ^ 3); j++) {
allNums.push(i * j);
}
}

Related

How to fix ' ReferenceError: matrixo is not defined'

i require matrixo function that in random.js, but in server.js but program cant find this function. Where do i need require random .js for fixing?
server.js
var matrix = matrixo(40, 40);
let random = require('./modules/random.js');
random.js
function matrixo(m) {
var matrix = [];
for (var i = 0; i < m; i++) {
matrix.push([]);
for (var j = 0; j < m; j++) {
matrix[i][j] = Math.floor(Math.random() * 3);
}
for (var j = 0; j < m; j++) {
matrix[i][j] = Math.floor(Math.random() * 4);
}
for (var j = 0; j < m + 3; j++) {
matrix[i][j] = Math.floor(Math.random() * 5);
}
for (var j = 0; j < m; j++) {
matrix[i][j] = Math.floor(Math.random() * 6);
}
for (var j = 0; j < m; j++) {
matrix[i][j] = Math.floor(Math.random() * 7);
}
}
return matrix;
}
module.exports = matrixo;
error - ReferenceError: matrixo is not defined
You need to assign the return value (which is the exported value) to the variable you are trying to use, and you need to do it before you use that variable.
let matrixo = require('./modules/random.js');
var matrix = matrixo(40, 40);

How many times needed to Sort a number in an Array Javascript

I want to count how many times needed for an array to be sorted
var array = [4,2,3,1]
var yourCounter = 0;
for (var i = 0; i < array.length; i++) {
for (var j = 1; j < array.length-j; j++)
if (array[j - 1] > array[j]) {
yourCounter++;
} }
it will return 4 , it should be 5
but if I input array [1,2,3] will correctly return 0 , and if I input array [3,2,1] it will correctly return 3
You could take the given code and swap the values while counting.
for (int i = 0; i < n; i++) {
for (int j = 0; j < n - 1; j++) {
// Swap adjacent elements if they are in decreasing order
if (a[j] > a[j + 1]) {
swap(a[j], a[j + 1]);
}
}
}
var array = [4, 2, 3, 1],
counter = 0,
i, j, n = array.length;
for (i = 0; i < n; i++) {
for (j = 0; j < n - 1; j++) {
if (array[j] > array[j + 1]) {
[array[j + 1], array[j]] = [array[j], array[j + 1]];
++counter;
}
}
}
console.log(counter);
console.log(array);
I found the solution
var a = [4,2,3,1]
function sortArray(a){
let swapCount = 0;
let swapOccurred = true;
let index = 0;
while (swapOccurred == true && index < a.length){
swapOccurred == false;
if (a[index] > a[index+1]){
let holder = a[index]
a[index] = a[index+1];
a[index+1] = holder;
swapOccurred == true;
swapCount ++;
index = -1;
}
index ++
}
function countSwaps(a) {
let swapCount = 0;
[a, swapCount] = sortArray(a)
console.log(swapCount)
}
return [a, swapCount]
}

Performance: why is the first implementation of the same algorithm significantly faster

The algorithm is taken from LeetCode: https://leetcode.com/problems/maximum-product-of-word-lengths/description/
Here is the jsperf I created (I have some local tests which gives the same result): https://jsperf.com/maximum-product-of-word-lengths
Here is the first "slow" implementation:
function maxProduct (words) {
if (!words || !words.length) return 0;
let len = words.length;
let values = [];
// console.log(values)
for (let i = 0; i < len; ++i) {
let tmp = words[i];
let num = 0, len = tmp.length;
for (let j = 0; j < len; ++j) {
num |= 1 << (tmp.charCodeAt(j) - 'a'.charCodeAt(0));
}
values[i] = {
num: num,
len: tmp.length
};
}
let maxProduct = 0;
for (let i = 0; i < len; ++i) {
for (let j = 0; j < len; ++j) {
if ((values[i].num & values[j].num) == 0) {
maxProduct = Math.max(maxProduct, values[i].len * values[j].len);
}
}
}
return maxProduct;
};
Here is the "fast" implementation:
function maxProductFast (words) {
var temp = [];
for(var i = 0; i < words.length; i++){
var tempObj = {};
tempObj.item = words[i];
var num = 0;
for(var j = 0; j < words[i].length; j++){
num |= 1 << (words[i].charCodeAt(j) - 97);
}
tempObj.num = num;
temp.push(tempObj);
}
var res = 0;
for(var i = 0; i < temp.length; i++){
for(var j = i + 1; j < temp.length; j++){
var item1 = temp[i];
var item2 = temp[j];
if((item1.num & item2.num) == 0) {
res = Math.max(res, item1.item.length * item2.item.length);
}
}
}
return res;
}
They're not the same. The second algorithm has a loop with a complexity of (n*(n+1))/2 where each progressive step is from i+1 to the length of temp. the first algorithm has a two nested for loops each with a cost of n^2. the complexity of both will reduce to O(n^2). I believe that both of these will have a similar performance with a significantly large enough set.
The reason you would do n+1 for each sub iteration is because you are trying to find the max of any pair of items. if you place your elements in a grid you will notice that any diagonal pair a_3 * a_2 = a_2 * a_3 produces the same value. you can basically halve the collection and save a few cycles.

I want to add together the numbers of a nested array

This is what I came up with:
var nestedArr = [[[1,2],[3,4]],[[5,6]]];
function sumTotal() {
for(var i = 0; i < nestedArr.length; i++) {
for(var j = 0; j < nestedArr[i].length; j++) {
for(var k = 0; k < nestedArr[i][j].length; k++) {
var arrNumSum = nestedArr[i][j][k];
arrNumSum += arrNumSum;
return arrNumSum;
}
}
}
}
sumTotal();
You can instead create recursive function using reduce()
var nestedArr = [[[1,2],[3,4]],[[5,6]]];
function sum(arr) {
return arr.reduce(function(r, e) {
return r + (Array.isArray(e) ? sum(e) : e)
}, 0)
}
console.log(sum(nestedArr))
You're overwriting arrNumSum each time through the loop. Moreover, you're returning too soon, right after the first iteration. Try this instead:
var nestedArr = [[[1,2],[3,4]],[[5,6]]];
function sumTotal() {
var arrNumSum = 0;
for(var i = 0; i < nestedArr.length; i++) {
for(var j = 0; j < nestedArr[i].length; j++) {
for(var k = 0; k < nestedArr[i][j].length; k++) {
arrNumSum += nestedArr[i][j][k];
}
}
}
return arrNumSum;
}
console.log(sumTotal());
You could use a recusive call of Array#reduce with a named function as callback.
var array = [[[1, 2], [3, 4]], [[5, 6]]],
total = array.reduce(function add(r, a) {
return Array.isArray(a) ? a.reduce(add, r) : r + a;
}, 0);
console.log(total);

Print prime numbers between 0 and 100

I'm trying to print all prime number between 0 and 100, but when executing this code the browser's tab just outputs nothing!!
for(var i = 2; i < 100; i++)
{
var prime = [];
for(var j = 0; j <= i; j++)
{
var p = i % j;
}
if(p != 0) prime.push(i);
else continue;
}
for(var k = 0; k < prime.length; k++)
{
document.writeln(prime[k], "<br>");
}
Try this one. I have also optimise the code (you only need to check upto sqrt(i) ).
var prime = [];
prime.push(2); //smallest prime
var flag = 0;
for(var i = 3; i < 100; i=i+2) //skip all even no
{
for(var j = 3; j*j <= i; j=j+2) //check by upto sqrt(i), skip all even no
{
if(i % j == 0) {
flag = 0;break; //not a prime, break
}
flag = 1;
}
if (flag == 1) prime.push(i); //prime, add to answer
}
for(var k = 0; k < prime.length; k++)
{
document.writeln(prime[k], "<br>");
}
Because you blank your list of primes EVERY loop cycle, move it outside the for loop
You need to make your variable prime outside of your loop
This is the code you have re-written
var prime = [];
for(var i = 2; i < 100; i++)
{
for(var j = 0; j <= i; j++)
{
var p = i % j;
}
if(p != 0) prime.push(i);
else continue;
}
for(var k = 0; k < prime.length; k++)
{
document.writeln(prime[k], "<br>");
}
I'm a fan of the sieve of Eratosthenes.
The following code should do what you wanted.
var prime = Array(101).fill(true);
for (var i = 2; i < 100; ++i){
if (prime[i]){
document.writeln(i, "<br>");
for (var j = i*i; j < 100; j += i){
prime[j] = false;
}
}
}
Or since it's only up to 100 you could just manually type the list (but, hey where's the learning if you do it that way?).
(1) Move prime outside the for loop, (2) start j at 2 and end when j < i, (3) check when p == 0 with a boolean flag and break inner loop.
var prime = []; //put prime out here so it does not reassign
for(var i = 2; i < 100; i++)
{
var isPrime = true;
for(var j = 2; j < i; j++) //start j at 2
{
var p = i % j;
if(p == 0)
{
isPrime = false;
break;
}
}
if(isPrime) prime.push(i);
}
for(var k = 0; k < prime.length; k++)
{
document.writeln(prime[k], "<br>");
}

Categories

Resources