吹牛逼的正确方式

附件

  

 

 

 

 

1、代码简洁、可读性

2、考虑时间O、空间复杂度

 

1、业务函数向一般工具函数的抽象,避免重复造轮子

2、经典问题都已有“最佳”解(学习设计模式、数据结构算法)

  写法已经相对最优、较高人效

 

1、自己平时当然要造足够多的轮子

// 剩余7人瓜分34鲜币,每个人获得鲜币数随机获得

// 方案1: 14个留出来,每人至少2个

/*
*
*total 总数                 物品数
*person 被分配人数           容器数
*least  每个人最少分配几个    保底数
*
*业务----> 抽象  ---> 脱离业务的工具函数
*算法最优  时间复杂度O最小

先实现再优化,注意边界条件


代码编写过程 需要单元测试和eslint语法检测
代码执行结果需要  可视化配合看效果
*/
function random(total = 34, person = 7, least = 2){
  let reserve = person * least; //14
  if(total < reserve){
    console.error("参数不合法")
  }
  let result = new Array(person).fill(least)
   
  let distribution = total - reserve; //20

for(let i = 0; i < person; i++){
    let cur = Math.floor(Math.random()*distribution)
  result[i] = cur+least

  if(distribution - cur <= 0){
    break;
  }else{
    distribution = distribution - cur
  }
}


  return result;
}

 

posted @ 2019-03-20 18:51  翰弟  阅读(276)  评论(0编辑  收藏  举报