Is this an elegant solution? [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
The problem is not complicated. Log randomly a name from an array of names.
My solution comes as this.
var names = [ 'nick', 'rock', 'danieel' ];
function randPicker(names) {
var randNum = Math.floor((Math.random() * 10));
var name = randNum <= (names.length - 1) ? console.log(names[randNum]) : randPicker(arguments[0]);
};
It seems to me that this code is not that beautiful, because im quite sure that there are better ways that perform much faster. Is that true?

The better way is make the function return random element of the array and fix its getting:
function randPicker(a) {
return a[Math.random() * a.length | 0];
}
And the test:
function randPicker(a) {
return a[Math.random() * a.length | 0];
}
var names = ['nick', 'rock', 'danieel'];
for (var q=0; q<16; ++q) {
console.log(randPicker(names));
}

You can get your randNum straight away to retrieve a name:
var names = [ 'nick', 'rock', 'danieel' ];
function randPicker(names) {
var randNum = Math.floor((Math.random() * names.length));
var name = console.log(names[randNum]);
};

You can use
var names = [ 'nick', 'rock', 'danieel' ];
function randomPicker(names) {
return names[Math.floor(Math.random() * (names.length+1))];
}
Explanation:
Math.random() returns a number in range [0,1]
Multiply it by the length of array + 1 to get numbers in range [0,length] with decimals.
Finally use Math.floor to round it to interger.

Related

Maybe someone knows a simple algorithm for finding the number of '0' elements that are between '1' elements in an array? [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 5 months ago.
Improve this question
I need a simple algorithm to find the number of occurrences of 0 between 1 in an array, for example, after performing certain operations on these arrays:
var mas1 = [0,1,0,0,1]
var mas2 = [1,0,0,0,1]
var mas3 = [0,1,0,1,0]
var mas4 = [0,0,0,0,1]
var mas4 = [1,0,1,0,1]
We have to get:
result = 2
result = 3
result = 1
result = 0
result = 2
We can have any number of 1's or 0's in an unlimited array
Any ideas?
You can continuously use indexOf to find the next 1 while accumulating the size of ranges in between consecutive ones.
let arr = [0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1];
let count = 0;
for(let i = arr.indexOf(1); i != -1; ){
const next = arr.indexOf(1, i + 1);
if (next !== -1) count += next - i - 1;
i = next;
}
console.log(count);

Testing a partial prorogram: Why is Modulus function not working? [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 10 months ago.
Improve this question
const marks = [80];
const grade = ['A', 'B', 'C', 'D', 'F'];
let sum = 0;
console.log(checkGrade(marks));
function checkGrade(array) {
for (let item of array)
sum += item;
const avg = sum / array.length;
let gradePoint = Math.floor((100 - avg) / 10);
return gradePoint % 10;
}
as Your code, the avg is = 80
and (100-avg) / 10 = 2 which is gradePoint
and you are returning gradePoint % 10
that means 2 % 10
which is returning 2.
and it is working perfectly. Where is the issue?

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

Create an array of 20 random numbers [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 4 years ago.
Improve this question
I need to create an array of 20 random numbers in the range from -10 to 10 inclusive and Check whether all numbers match the parameters (from -10 to 10).
here is my code:
let array = [];
for (let i = 0; i < array.length; i++) {
array.push(Math.round((Math.random() * 21) - 10));
}
console.log(array);
It should be more like this
let array = [];
for(let i=0; i<20; i++){
array.push(Math.round((Math.random() * 21) - 10));
}
console.log(array);
This will do the trick,
var array = Array(20).fill().map(() => Math.round(Math.random() * 20) - 10);
console.log(array)

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