Loops & Control Flow - javascript

When I run this I can't seem to get the rest of the values.
Write a function mergingTripletsAndQuints which takes in two arrays as arguments. This function will return a new array replacing the elements in array1 if they are divisible by 3 or 5. The number should be replaced with the sum of itself added to the element at the corresponding index in array2.
function mergingTripletsAndQuints(array1, array2) {
let result = [];
let ctr = 0;
let x = 0;
for (let i = 0; i < array1.length; i++) {
for (let j = 0; j < array2.length; j++) {
ctr = array1[i] + array2[j];
if (ctr % 3 === 0 || ctr % 5 === 0) {
result.push(ctr);
} else {
return array1[i];
}
}
}
return result;
}
console.log(mergingTripletsAndQuints([1, 2, 3, 4, 5, 15], [1, 3, 6, 7, 8, 9])); // expected log [1, 2, 9, 4, 13, 24]
console.log(mergingTripletsAndQuints([1, 1, 3, 9, 5, 15], [1, 2, 3, 4, 5, 6])); // expected log [1, 1, 6, 13, 10, 21]
It is only logging [1], [1]

I'm not sure, but I suppose there is a typo returning array1[i] in nested loop. I suppose you mean result.push(array1[i]) instead.
I think it should be something like this:
function mergingTripletsAndQuints(array1, array2) {
let result = [];
for (let i = 0; i < array1.length; i++) {
if (array1[i]% 3 === 0 || array1[i]% 5 === 0) {
result.push(array1[i] + array2[i]);
} else {
result.push(array1[i]);
}
}
return result;
}
console.log(mergingTripletsAndQuints([1, 2, 3, 4, 5, 15], [1, 3, 6, 7, 8, 9])); // expected log [1, 2, 9, 4, 13, 24]
console.log(mergingTripletsAndQuints([1, 1, 3, 9, 5, 15], [1, 2, 3, 4, 5, 6])); // expected log [1, 1, 6, 13, 10, 21]

A nested for loop is not necessary, look at this code:
function mergingTripletsAndQuints(array1, array2) {
let sum = [];
for (let i = 0; Math.max(i < array1.length, i < array2.length); i++) {
if (array1[i] % 3 == 0 || array1[i] % 5 == 0) {
sum.push(array1[i] + array2[i])
} else {
sum.push(array1[i])
}
}
return sum;
}

Related

How to log how many possibilities fulfil the if statement javascript

const grades = [9, 8, 5, 7, 7, 4, 9, 8, 8, 3, 6, 8, 5, 6];
for (let i = 0; i < grades.length; i++) {
if (grades[i] >= 8) {
console.log(grades[i])
}
}
I'm trying to log how many items from the array fulfil the condition. the output I'm looking for is : 6 (because 6 of the numbers are equal or greater than 8)
tried
let count = 0;
for (let i = 0; i < grades.length; i++) {
if (grades[i]>= 8){
count++
console.log(count)
}
}
function countGreaterThan8(grades){
// initialize the counter
let counter = 0;
for (let i = 0; i < grades.length; i++) {
// if the condition satisfied counter will be incremented 1
if (grades[i] >= 8) {
counter++;
}
}
return counter;
}
const grades = [9, 8, 5, 7, 7, 4, 9, 8, 8, 3, 6, 8, 5, 6];
console.log(countGreaterThan8(grades)); // 6
You can call Array.filter to create a new array containing only items that fulfill the condition. You can then make use of the length of the array however you want. Like this
const grades = [9, 8, 5, 7, 7, 4, 9, 8, 8, 3, 6, 8, 5, 6];
const gradesThatPassCondition = grades.filter(grade => grade > 6);
console.log(gradesThatPassCondition.length);

Comparing Elements Values In An Array, and returning Boolean

Can anyone help I am nearly there I can get the code to return true for the first 2 test below, but not return false for the next 2 tests, what I need to do is to check that all the numbers in the array are in ascending order so every element number is greater than the last for the length of the array. Any ideas? Kind regards Jon.
Test.expect(inAscOrder([1, 2, 4, 7, 19])
Test.expect(inAscOrder([1, 2, 3, 4, 5])
Test.expect(!inAscOrder([1, 6, 10, 18, 2, 4, 20])
Test.expect(!inAscOrder([9, 8, 7, 6, 5, 4, 3, 2, 1])
function inAscOrder(arr) {
let result = false;
for (let i = 0; i <= arr.length; i++) {
for (let k = 0; k <= arr.length; k++) {
if (arr[i] < arr[k+1]) {
result = true;
}
}
}
return result;
}
You were very close to answer
function inAscOrder(arr) {
let result = true;
for (let i = 0; i <= arr.length; i++) {
if (arr[i] > arr[i+1]) {
result = false;
break;
}
}
return result;
}
Try this,
You can use the functional way instead.
const inAscOrder = arr => arr.slice(1).every((elem,i) => elem > arr[i]);
console.log(inAscOrder([1,2,5]));
The easiest way to compare two arrays, is to convert them to a strings and then compare the strings.
const isAscending = (arr) => arr.join("") == arr.sort((a, b) => a - b).join("");
console.log(isAscending([1, 2, 4, 7, 19]));
console.log(isAscending([1, 2, 3, 4, 5]));
console.log(isAscending([1, 6, 10, 18, 2, 4, 20]));
console.log(isAscending([9, 8, 7, 6, 5, 4, 3, 2, 1]));
For every element in the array, return true if it's the first element or it's greater than the previous element.
const isAscending = (arr) => arr.every((el, i, arr) => i === 0 || el > arr[i - 1]);
console.log(isAscending([1, 2, 4, 7, 19]));
console.log(isAscending([1, 2, 3, 4, 5]));
console.log(isAscending([1, 6, 10, 18, 2, 4, 20]));
console.log(!isAscending([9, 8, 7, 6, 5, 4, 3, 2, 1]));

Count repeated numbers in array and return true (Cognitive Complexity)

I need to check if a number repeats itself at least three times in an array. How can I refactor it to decrease the Cognitive Complexity that Lint keeps complaining about.
Heres my code:
let array11 = [1, 3, 2, 3, 5, 6, 7, 8, 9, 0, 1];
function checkDuplicateNumber (array11) {
for (let i = 0; i < array11.length; i += 1) {
let sameNumberLoop = 0;
for (let i2 = i; i2 < array11.length; i2 += 1) {
if (array11[i] === array11[i2]) {
sameNumberLoop += 1;
if (sameNumberLoop >= 3) {
return true;
}
}
}
}
}
Instead of iterating multiple times, iterate just once, while counting up the number of occurrences in an object or Map:
let array11 = [1, 3, 2, 3, 5, 6, 7, 8, 9, 0, 1];
function checkDuplicateNumber (array) {
const counts = {};
for (const num of array) {
counts[num] = (counts[num] || 0) + 1;
if (counts[num] === 3) return true;
}
return false;
};
console.log(checkDuplicateNumber(array11));
console.log(checkDuplicateNumber([3, 1, 3, 5, 3]));
let array11 = [1, 3, 2, 3, 5, 6, 7, 8, 9, 0, 1]
let array22 = [1, 3, 2, 3, 5, 6, 7, 1, 9, 0, 1]
function checkDuplicateNumber(arr) {
const map = new Map()
return arr.some((v) => (map.has(v) ? (++map.get(v).count === 3) : (map.set(v, { count: 1 }), false)))
}
console.log(checkDuplicateNumber(array11))
console.log(checkDuplicateNumber(array22))

How to replace spaces whilst adding new elements?

I have a stepped array of elements that is filled as follows:
class Funnel{
constructor() {
this.funnelContents = [];
this.layer = 0;
}
get content() {
return this.funnelContents;
}
fill(...nums) {
let index, startIndex = 0;
for(let i = 0; i < this.funnelContents.length; i++){
while ((index = this.funnelContents[i].indexOf(' ', startIndex)) > -1 && nums.length > 0) {
this.funnelContents[i][index] = nums.shift();
startIndex = index + 1;
}
}
return nums
.splice(0, 15 - this.funnelContents.reduce((count, row) => count + row.length, 0))
.filter(num => num < 10)
.reduce((arr, num) => {
if (this.funnelContents.length) {
this.funnelContents[this.funnelContents.length - 1] = this.funnelContents[this.funnelContents.length - 1].filter(char => char !== ' ');
if ((this.funnelContents[this.layer] || []).length !== this.funnelContents[this.layer - 1].length + 1) {
this.funnelContents[this.layer] = [...(this.funnelContents[this.layer] || []), num];
} else {
this.layer++;
this.funnelContents[this.layer] = [num];
}
}
else {
this.layer++;
this.funnelContents = [...this.funnelContents, [num]];
}
}, []);
}
toString() {
let str = '', nums = '', spacesCount = 1;
for(let i = 5; i > 0; i--){
str += '\\';
for(let j = 0; j < i; j++) {
if (this.funnelContents[i - 1] !== undefined) {
if (this.funnelContents[i - 1][j] !== undefined) {
nums += this.funnelContents[i - 1][j];
} else {
nums += ' ';
}
} else {
nums += ' ';
}
}
str += nums.split('').join(' ') + '\/\n' + ' '.repeat(spacesCount);
nums = '';
spacesCount++;
}
return str.substring(0, str.length - 6);
}
}
let funnel1 = new Funnel();
let funnel2 = new Funnel();
let funnel3 = new Funnel();
let funnel4 = new Funnel();
let funnel5 = new Funnel();
let funnel6 = new Funnel();
let funnel7 = new Funnel();
funnel1.fill(5,4,3,4,5,6,7,8,9,3,2,4,5,6,7,5,6,7,8); //15 elements will be added, the rest are ignored
funnel2.fill(5,4,3,4,5,6,7,8);
funnel2.fill(9,3,2,4,5,6,7);
funnel3.fill(' ');
funnel3.fill(1,5,7);
funnel4.fill(1,2,3);
funnel4.fill(' ');
funnel4.fill(3,4,5);
funnel5.fill(1);
funnel5.fill(' ', ' ', ' ');
funnel5.fill(8,2,1);
funnel6.fill(' ',' ');
funnel6.fill(1,8,2,1);
funnel7.fill(' ',' ',' ',' ',' ');
funnel7.fill(1,8,2,1);
console.log(funnel1.toString()); // the output is as expected.
console.log(funnel2.toString()); // the same result
console.log(funnel3.toString()); // expected [ [1], [5,7] ] and it really is
console.log(funnel4.toString()); // expected [ [1], [2,3], [3,4,5] ] and it really is
console.log(funnel5.toString()); // expected [ [1], [8,2], [1] ] and it really is
console.log(funnel6.toString()); // expected [ [1], [8,2], [1] ] but got [ [], [1,8], [2], [1] ]
console.log(funnel7.toString()); // nothing is changed
Here you can see that at the very beginning of the function fill a cycle was written to insert elements that came to the input instead of spaces. I added spaces artificially, in fact, there is another function that adds them. But:
1) For some reason this does not always work, for an array in the example it does not work. With a simpler space search algorithm, it also does not work properly:
for (let i = 0; i < this.funnelContents.length; i++) {
for (let j = 0; j < this.funnelContents[i].length; j++) {
if(this.funnelContents[i][j] === ' '){
this.funnelContents[i][j] = nums.shift();
}
}
}
2) It looks very cumbersome and I would like to do something similar more elegantly. I was thinking of two for loops to find elements I need, but I still hope that I can implement insertion instead of spaces inside reduce function.
You could take a single loop and slice substrings with increasing length.
function funnel(array) {
var i = 0,
l = 0,
result = [];
while (i < array.length) result.push(array.slice(i, i += ++l));
return JSON.stringify(result);
}
console.log(funnel([1]));
console.log(funnel([1, 2]));
console.log(funnel([1, 2, 3]));
console.log(funnel([1, 2, 3, 4]));
console.log(funnel([1, 2, 3, 4, 5]));
console.log(funnel([1, 2, 3, 4, 5, 6]));
console.log(funnel([1, 2, 3, 4, 5, 6, 7]));
console.log(funnel([1, 2, 3, 4, 5, 6, 7, 8]));
console.log(funnel([1, 2, 3, 4, 5, 6, 7, 8, 9]));
console.log(funnel([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));
console.log(funnel([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]));
console.log(funnel([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]));
console.log(funnel([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]));
console.log(funnel([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]));
console.log(funnel([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
As I understand the comment, you have an array in the given style with incrementing count, but some elements are spaces and this elemenst should bereplaced with the given data.
In this case, a nested loop for getting the result set right and another index for getting the value from the data array should work.
class Funnel {
constructor() {
this.funnelContents = [];
}
get content() {
return this.funnelContents;
}
fill(...nums) {
var i = 0,
j = 0,
l = 1,
k = 0,
target = this.funnelContents;
while (k < nums.length) {
if (!target[i]) target.push([]);
if ([undefined, ' '].includes(target[i][j])) target[i][j] = nums[k++];
if (++j === l) {
if (++i > 4) break; // max 15 elements in result set
j = 0;
l++;
}
}
}
}
var funnel = new Funnel;
funnel.fill(' ', ' ', ' ', ' ');
console.log(JSON.stringify(funnel.content));
funnel.fill(1, 2, 3, 4, 5, 6, 7, 8, 9);
console.log(JSON.stringify(funnel.content));
funnel.fill(10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20);
console.log(JSON.stringify(funnel.content));

Adding an if condition to a for loop

I'm trying to make it work on every number divisible by three.
here's my code:
var number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for(var i = 0; i<10 ; i++) {
if (i % 3 === 0) {
console.log(color[i]);
}
}
I think you need to use number[i] % 3 === 0. And what is the color there in your code? Change it into number.
var number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for(var i = 0; i<10 ; i++) {
if (number[i] % 3 === 0) {
console.log(number[i]);
}
}
Try this
var number = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for(var i = 0; i<10 ; i++) {
if (i % 3 === 0) {
console.log(i);
}
}

Categories

Resources