You are given an array of integers a and two integers l and r. You task is to calculate a boolean array b, where b[i] = true if there exists an integer x, such that a[i] = (i + 1) * x and l ≤ x ≤ r. Otherwise, b[i] should be set to false.
function boundedRatio(a, l, r) {
let b = []
for (let i = l; i <= r; i++) {
//
for (let j = 0; j < a.length; j++) {
let result = (j + 1) * i
if ((j + 1) * i === a[j] && l <= i <= r) {
b.push(true)
} else {
b.push(false)
}
}
}
return b
boundedRatio([8, 5, 6, 16, 5], 1, 3)
// [false, false, true, false, true]
Your main loop should be over the array a. For each of them, you need a loop over l through r. In that loop you should just set a variable to inidcate whether the bounded value is found. Once you find it you can break out of the loop. Then you push that onto the result.
The main loop and push can be combine with map().
function boundedRatio(a, l, r) {
let b = a.map((el, i) => {
let bounded = false;
for (let x = l; x <= r; x++) {
if ((i + 1) * x == el) {
bounded = true;
break;
}
}
return bounded;
})
return b;
}
console.log(boundedRatio([8, 5, 6, 16, 5], 1, 3));
Here's how it looks with a for loop instead of map().
function boundedRatio(a, l, r) {
let b = [];
for (let i = 0; i < a.length; i++) {
let bounded = false;
for (let x = l; x <= r; x++) {
if ((i + 1) * x == a[i]) {
bounded = true;
break;
}
}
b.push(bounded);
}
return b;
}
console.log(boundedRatio([8, 5, 6, 16, 5], 1, 3));