explain problem: When you click the button, the background color changes randomly. I am trying to count the number of cases where the color blue appears.
summarize the problem: The number of color arrays and the number of blues are not output. I don’t know how to implement 4C2 in JavaScript
Describe tried: I tried to check the number of arrays in console.log in advance Analyze the code of https://craftjj.neocities.org/index.1.html I’ve been trying to find a way to implement combinations in javascript.
JavaScript
x
30
30
1
const body = document.querySelector('body')
2
const btn = document.querySelector('.btn')
3
const cBtn = document.querySelector('.cbtn')
4
5
const color = ['red','blue','pink','blue','yellow']
6
7
function conbination(){
8
const colorNum = color.length//color배열 개수[color array count]
9
const blueNum = color['blue'].length//blue개수[blue count]
10
console.log(colorNum)
11
console.log(blueNum)
12
}
13
14
/*const n = 4
15
const r = 2
16
17
function c(n, r) {
18
return Math.floor(p(n, r) / times(1,r));
19
}
20
*/
21
btn.addEventListener("click",()=>{
22
let n = Math.floor(Math.random() * 5);
23
body.style.backgroundColor = color[n]
24
})
25
26
27
function init(){
28
cBtn.addEventListener('click',conbination)
29
}
30
Advertisement
Answer
JavaScript
1
10
10
1
const combination=function(n,k){
2
let nfact=1,kfact=1;
3
for(let i=n;i>n-k;i--){
4
nfact*=i;
5
}
6
for(let i=k;i>0;i--){
7
kfact*=i;
8
}
9
return Math.floor(nfact/kfact);
10
}
This will give you the roundoff value of combination for C(n,k)…