前几日练习Swift 在Xcode上一顿操作
这几天要完成算法作业 想写C Xcode问我access
这事我也不知道啊
一气之下打开VSCode继续愉快地JavaScript
正题
分治法入门题——求伪币(基础版)
/**
* 声明全局变量
* 开始
*/
const COIN_SIZE = 16 //硬币数目
const COIN_WEIGHT = 10 //硬币标准质量
const FAKE_WEIGHT = 9 //伪币质量
let calcTimes = 0 //计算次数
let coinArray = new Array() //初始化硬币质量数组
let findOrder //计算得到的伪币位置
/**
* 程序入口
* 执行main函数
*/
main()
/**
* 分治法寻找伪币
* 核心算法
* 开始
*/
function findFake(coinArray, left, right) {
let LeftWeight
let RightWeight
calcTimes++//每进行一次查找,计数器+1
LeftWeight = Weight(coinArray, left, parseInt(left + (right - left) / 2))//左侧质量
RightWeight = Weight(coinArray, parseInt(left + (right - left) / 2 + 1), right) //右侧质量
if (LeftWeight > RightWeight) {//如果左侧质量大于右侧质量,说明伪币在右侧
if (left == right - 1) {//如果仅剩下两枚硬币了,则就是右边那一枚
findOrder = right
} else {//不止两枚硬币的话,则在右侧再进行一次查找
findFake(coinArray, parseInt(left + (right - left) / 2 + 1), right)
}
} else if (LeftWeight < RightWeight) {//如果左侧质量小于右侧质量,说明伪币在左侧
if (left == right - 1) {//如果仅剩下两枚硬币了,则就是左边那一枚
findOrder = left
} else {//不止两枚硬币的话,则在左侧再进行一次查找
findFake(coinArray, left, parseInt(left + (right - left) / 2))
}
} else {
console.log("-----------Error----------")
}
}
/**
* 计算固定范围内硬币总质量
* 开始
*/
function Weight(coinArray, left, right) {
let weightTemp = 0
for (i = left; i <= right; i++) {
weightTemp += coinArray[i]
}
return weightTemp
}
/**
* 随机生成伪币位置
* 开始
*/
function newFakeCoin(coinArray) {
let fakeOrder = parseInt(Math.random() * 16)//随机生成伪币位置
coinArray[fakeOrder] = FAKE_WEIGHT//为伪币质量赋值
console.log("随机生成的伪币位置:" + (fakeOrder + 1))//打印随机伪币位置
}
/**
* 主函数入口
* 开始
*/
function main() {
console.log("------------New-----------")
for (i = 0; i < COIN_SIZE; i++) {//为硬币质量数组赋标准值
coinArray[i] = COIN_WEIGHT
}
newFakeCoin(coinArray)//随机生成伪币位置并打印
findFake(coinArray, 0, COIN_SIZE - 1)//寻找伪币位置
console.log("计算得到的伪币位置:" + (findOrder + 1))//打印返回伪币位置
console.log(" 累计计算次数:" + calcTimes)//打印计算次数
console.log("------------End-----------")
}
实际测试
[Running] node "伪币问题.js"
------------New-----------
随机生成的伪币位置:6
计算得到的伪币位置:6
累计计算次数:4
------------End-----------
[Done] exited with code=0 in 0.09 seconds
[Running] node "伪币问题.js"
------------New-----------
随机生成的伪币位置:8
计算得到的伪币位置:8
累计计算次数:4
------------End-----------
[Done] exited with code=0 in 0.099 seconds
[Running] node "伪币问题.js"
------------New-----------
随机生成的伪币位置:14
计算得到的伪币位置:14
累计计算次数:4
------------End-----------
[Done] exited with code=0 in 0.091 seconds
[Running] node "伪币问题.js"
------------New-----------
随机生成的伪币位置:6
计算得到的伪币位置:6
累计计算次数:4
------------End-----------
[Done] exited with code=0 in 0.104 seconds
待完善
- 生成随机位置不完美
- 伪币质量需比真币质量小
- 以及各自不完美
PS
过几天闲下来 VSCode跑C试试
还要什么Xcode
以上。