Comments

Ergonomic compress3 months ago

// this is what we use to find the most common line equation

const findLargestMB = (lineEqns) => {
  let count = 0
  let largestEqn = ''
  
  for(let eqn in lineEqns){
    if(lineEqns[eqn] > count){
      count = lineEqns[eqn]
      largestEqn = eqn
    }
  }
  
  if(count === 0){
    return {}
  }
  const [m,b] = largestEqn.split(',')
  return { m:Number(m), b:Number(b)}
}

// often, because of javascript, we often don't get perfect decimals
const truncateTo = (num, decPl) => {
  const [whole, decimals='0'] = num.toString().split('.')
  return [whole, decimals.slice(0,decPl)].join('.')
}

// used to get the slope for any given point pair
const getSlope = (x1,x2,y1,y2) => {
  return (y1 - y2)/(x1-x2)
}

//used to get the line equations for all point combinations
const getLineEqns = (intArray) => {
    let lines = {}
  for(let i = 0; i < intArray.length - 1; i++){
    let [x1,y1] = intArray[i]
    for(let j = i + 1; j < intArray.length;j++){
      let [x2,y2] = intArray[j]
      if(x1 === x2){
        continue
      }
      let m = getSlope(x1,x2,y1,y2)
      let b = y1 - m*x1
      
      const eqn = `${truncateTo(m,3)},${truncateTo(b,3)}`
      if(!lines[eqn]){
        lines[eqn] = 0
      }
       lines[eqn] =  lines[eqn] + 1
    }
  }
  return lines
}

const solve = (intArray) => {
  const lines = getLineEqns(intArray)
  const {m=0,b=0} = findLargestMB(lines)

  const linePoints = intArray.reduce((acc, [x,y]) => {
    if(y === (m*x + b)){
      return acc + 1
    } 
    
    return acc
    
  },0)
  return linePoints
};

Ergonomic compress3 months ago

I guess we just choose the line with the most number of points?