Skip to content
Advertisement

title: Number of cases where blue color appears in the background color Error while implementing with JavaScript

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.

const body = document.querySelector('body')
const btn = document.querySelector('.btn')
const cBtn = document.querySelector('.cbtn')

const color = ['red','blue','pink','blue','yellow']

function conbination(){
    const colorNum = color.length//color배열 개수[color array count]
    const blueNum = color['blue'].length//blue개수[blue count]
    console.log(colorNum)
    console.log(blueNum)
}

/*const n = 4
const r = 2

function c(n, r) {
    return Math.floor(p(n, r) / times(1,r));
}
*/
    btn.addEventListener("click",()=>{
        let n = Math.floor(Math.random() * 5);
        body.style.backgroundColor = color[n]
    })


function init(){
    cBtn.addEventListener('click',conbination)
}

Advertisement

Answer

const combination=function(n,k){
  let nfact=1,kfact=1;
  for(let i=n;i>n-k;i--){
    nfact*=i;
  }
  for(let i=k;i>0;i--){
    kfact*=i;
  }
  return Math.floor(nfact/kfact);
}

This will give you the roundoff value of combination for C(n,k)…

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement