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);
Related
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 writing some JS and I can't seem to figure out how to write a function that will give a true or false statement back.
The way I want to write it is:
Loop function 5 times
on each loop give 1 of 8 random prizes
then check the probability of getting the prize, e.g 1 out of 10,000.
One of the loops has to provide with 1 as true
Any help is appreciated.
This is what I have tried, in terms of getting the probability
function prob(n) {
var old = n - 1;
var val = (n += 1);
return Math.floor(Math.random() * val) == old;
}
console.log(prob(2));
I generally use these helper functions if I need random
const chance = (percentage) => Math.random() * 100 < percentage;
const getRandomInt = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;
const getRandomArbitrary = (min, max) =>
Math.random() * (max - min) + min;
console.log(chance(50));
console.log(getRandomInt(1, 10));
console.log(getRandomArbitrary(0, 5));
// Full code
const prizes = [{
name: 'Bear',
probability: 5,
},
{
name: 'Car',
probability: 0.02,
},
{
name: 'Poster',
probability: 90,
},
];
let count = 5;
while (count--) {
const prize = prizes[getRandomInt(0, prizes.length - 1)];
const win = chance(prize.probability);
console.log(`Prize: ${prize.name} - Won: ${win}`);
}
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);
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 3 years ago.
Improve this question
I'am newbie in Python and i'am having a hard time trying to translate this Javascript arrow function into Python. I'am not able to make the part where i use substring in JS to get the next 3 values in my loop when i find '\x1D'. Any tips or suggestions ?
module.exports = edi => {
let decompressedEdi = ''
let lastCompressor = 0
for (let i = 0; i <= edi.length; i++) {
if (edi[i] === '\x1D') {
let decimal = parseInt(edi.substring(i + 1, i + 3), 16)
let repeater = edi[i + 3]
decompressedEdi +=
edi.substring(lastCompressor, i) + repeater.repeat(decimal)
lastCompressor = i + 4
}
}
decompressedEdi += edi.substring(lastCompressor, edi.length)
return decompressedEdi.replace(/(\r\n|\n|\r)/gm, '')
}
In python, strings can be sliced like arrays :
for i, c in enumerate(edi):
if c == '\x1D':
decimal = int(edi[i+1:i+3], 16)
The int function has the following signature: int(str, base)
from re import sub
def decompress(edi):
decompressed = ""
last_compressor = 0
for i, c in enumerate(edi):
if c == "\x1D":
repetitions = int(edi[i + 1: i + 3], 16)
repeating_char = edi[i + 3]
decompressed += edi[last_compressor:i] + repeating_char * repetitions
last_compressor = i + 4
decompressed += edi[last_compressor:-1]
return sub("\r\n|\n|\r", decompressed)
How I read the code
Feel free to ignore this bit, but it might help.
Given edi which has a len, for each edi that matches \x1D, get the substring of edi from the index + 1 to index + 3 as a hexadecimal integer as set as decimal. The repeater is the index + 3'th element of edi for each element and it is expected to be a str. It will be repeated the hexadecimal number of times defined in decimal, but only after the substring of edi from lastCompressor to the current index. On each iteration where \x1D is matched, the lastCompressor is increased by 4.
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
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.