How to decrease numbers from an array in javascript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
There are numbers in an array like 54321
array = ["54321"] ;
Now how can I print in console
54321
5432
543
54
5
I don't want to print it manually, I want to print it dynamically..
Thanks in advance.

const array = ["54321"];
const print = ([x]) => {
if (x.length === 0) return;
console.log(x);
print([x.slice(0, -1)]);
}
print(array)

You can split the string into array and the use reduce function
ler arr = array[0].split('');
let result = arr.reduce((acc,i) => {
acc.newarr.push(arr.slice(0,acc.counter).join(''));
acc.counter--;
return acc;
},
{newarr:[],counter:5});
console.log(result);

const array = ["54321"];
const un_print = ([str]) =>
Array.from(
{ length: str.length },
(_, i) => (i + 1) + '. ' + str.slice(0, str.length - i)
)
.forEach((v) => console.log(v));
un_print(array);

Related

Make a recursive function in JavaScript [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I am trying to make a recursive function for this parameters. Function should determine the nth element of the row
a_0 = 1
a_k = k*a_(k-1) + 1/k
k = 1,2,3...
I am trying really hard to do this but i cant get a result. Please help me to do this
I came up with this but it is not a recursive function. I can not do this as a recursive function
let a = 1
let k = 1
let n = 3
for (let i = 1; i<=n; i++){
a = i*a + 1/i
}
console.log(a)
Here's the recursive function you're looking for, it has two conditions:
k == 0 => 1
k != 0 => k * fn(k - 1) + 1/k
function fn(k) {
if(k <= 0) return 1;
return k * fn(k - 1) + 1/k;
}
console.log(fn(1));
console.log(fn(2));
console.log(fn(3));
console.log(fn(4));
Note: I changed the condition of k == 0 to k <= 0 in the actual function so it won't stuck in an infinite loop if you pass a negative k

Need help for an algo [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
I make a site where the color of the div is randomly generating compared to this array:
let pastelColor = [
'ffaacc','ffbbcc','ffcccc','ffddcc','ffeecc','ffffcc','ffaadd','ffbbdd','ffccdd','ffdddd','ffeedd','ffffdd',
'ffaaee','ffbbee','ffccee','ffddee','ffeeee','ffffee','ffaaff','ffbbff','ffccff','ffddff','ffeeff','ffffff',
'ccaaff','ccbbff','ccccff','ccddff','cceeff','ccffff','ccaaee','ccbbee','ccccee','ccddee','cceeee','ccffee',
'ccaadd','ccbbdd','ccccdd','ccdddd','cceedd','ccffdd','ccaacc','ccbbcc','cccccc','ccddcc','cceecc','ccffcc'
]
I tried several Algo with Case Switch but the function took too much room, I was wondering in curiosity if an algo would be able to generate this array ?
Thank you in advance for those who answer
if an algo would be able to generate this array ?
Sure. If you need that array in that exact order:
let pastelColor = Array.from("abcdef".repeat(8), (ch, i) =>
(([a,...r]) => a+a+ch+ch+r[~~(i/6)%4].repeat(2))(i<24 ? "fcdef" : "cfedc")
);
console.log(pastelColor);
If you are not really interested in the array with color codes, but only in the generation of a random color from it, then:
let pick = str => str[Math.floor(Math.random() * str.length)].repeat(2);
let pastelColor = pick("cf") + pick("abcdef") + pick("cdef");
console.log(pastelColor);
You need to fill the array with the converted hexadecimal color with randomly generated integers ranging from 0 to 255 like this:
const getRandomInt = (min, max) => {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min);
}
const getRandomColorUnit = () => {
const color = getRandomInt(0, 256).toString(16);
if (color.length < 2) return '0' + color;
return color;
};
const getRandomColor = () => `#${getRandomColorUnit()}${getRandomColorUnit()}${getRandomColorUnit()}`;
const colors = new Array(100).fill(0).map(getRandomColor);
console.log(colors);

Javascript. Object.values(...).reduce [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 1 year ago.
Improve this question
Can anyone explain in detail how this piece of code works?
const yourAmazingFunction = (salaries) => Object.values(salaries).reduce((acc, el) => acc + el, 0);
specifically this:
((acc, el) => acc + el, 0);
Here's all the code:
const nonEmptySalaries = {
John: 100,
Ann: 160,
Pete: 130
};
const emptySalaries = {};
const yourAmazingFunction = (salaries) => Object.values(salaries).reduce((acc, el) => acc + el, 0);
const firstResult = yourAmazingFunction(nonEmptySalaries)
const secondResult = yourAmazingFunction(emptySalaries)
console.log(firstResult); // 390
console.log(secondResult); // 0 ```
Take all of the values (in this case an array [100, 160, 130])
Loop over the array values, setting acc to the result of the last call of the callback, or 0 if this is the first call, and el to the current element. Basically add together each number (callback(0, 100) then callback(100, 160) then callback(260, 130) to return 390).

How can loop be rewritten as anonymous function? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
how can this type of loop be overwritten
let num - fieldOffset[0];
for (let i = 1; i < fieldOffset.length; i++) {
if (fieldOffset[i] < fieldOffset[i - 1]) {
num += fieldOffset[i];
}
}
as an anonymous function of the following type:
const reducer = (accumulator, currentValue) => accumulator + currentValue;
array1.reduce(reducer)
Using the third (optional) argument of Array.prototype.reduce should do the trick:
num = fieldOffset.reduce((acc, value, index) => acc += (index && (value > fieldOffset[index - 1])) ? value : 0, 0);

Find extra character between two strings [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
How can I find an extra character between two strings in an optimal way.
Ex1: S1 - 'abcd', S2 - 'abcxd', output - 'x'
Ex2: S1 - '100001', S2 - '1000011', output - '1'
We can do this by traversing linearly and comparing each character in O(n). I want this to be done in much more optimal way, say in O(logn)
Baseline method (O(n)): Just comparing chars and narrowing in on both sides each cycle.
function findDiffChar(base, baseExtraChar) {
let extraLastIndex = base.length;
let lastIndex = extraLastIndex - 1;
for (let i = 0; i < extraLastIndex / 2; i++) {
console.log(`Loop: ${i}`);
if (base[i] !== baseExtraChar[i])
return baseExtraChar[i];
if (base[lastIndex - i] !== baseExtraChar[extraLastIndex - i])
return baseExtraChar[extraLastIndex - i];
}
return false;
}
console.log(findDiffChar('FOOOOOAR', 'FOOOOOBAR')); // B
Improved method using binary search (O(log n)): Compare halves until you've narrowed it down to one character.
function findDiffChar(base, baseExtraChar) {
if (baseExtraChar.length === 1) return baseExtraChar.charAt(0);
let halfBaseLen = Number.parseInt(base.length / 2) || 1;
let halfBase = base.substring(0,halfBaseLen);
let halfBaseExtra = baseExtraChar.substring(0,halfBaseLen);
return (halfBase !== halfBaseExtra)
? findDiffChar(halfBase, halfBaseExtra)
: findDiffChar(base.substring(halfBaseLen),baseExtraChar.substring(halfBaseLen));
}
console.log(findDiffChar('FOOOOAR', 'FOOOOBAR')); // B
console.log(findDiffChar('---------', '--------X')); // X
console.log(findDiffChar('-----------', '-----X-----')); // X
console.log(findDiffChar('------------', '---X--------')); // X
console.log(findDiffChar('----------', '-X--------')); // X
console.log(findDiffChar('----------', 'X---------')); // X

Categories