算法题练习,Solo和koko分糖 ,整数拆分, Cookies 分饼干
作者:互联网
目录
1. Candy Solo和koko分糖
如果可以分给弟弟,必定满足全部异或为0,找出最小的一个给弟弟
function handle1(input) {
let [num, map] = input.split("\n");
map = map.split(/\s+/).map(a => Number(a));
let r = map.reduce((prev, next) => prev ^ next)
if (!!r) {
console.log("NO");
} else {
map.sort((a, b) => a - b)
map.shift();
let sum = map.reduce((prev, next) => prev + next)
console.log(sum);
}
}
function handle2(input) {
let array = input.split("\n")[1].split(' ');
let sum = !eval(array.join('^')) && (eval(array.join('+')) - Math.min(...array)) || 'NO';
console.log(sum);
}
// handle('3\n3 5 6')
// handle('5\n1 2 3 4 5')
// handle('8\n7258 6579 2602 6716 3050 3564 5396 1773')
handle('10\n656660 476531 89825 757604 876771 923382 842461 898174 923083 760991')
2. 整数拆分 3=1+1+1 3=1+2 3=3
function handle(input){
let inputArray = input.split('\n');
inputArray.forEach(item =>{
change(item)
})
}
function change(n, total = n, i = 1, s = '') {
if (total <= 0) return console.log(s);
for (let j = i; j <= total; j++) {
change(n, total - j, j, s === '' ? `${n}=${j}` : `${s}+${j}`);
}
}
handle("3\n4")
3. Cookies 分饼干
function cookies(arr) {
let map = arr.filter((item, index) => index % 2 === 1)
map.forEach(item => {
let itemArr = item.split(' ').map(num => Number(num))
let r = itemArr.reduce((prev, next) => prev + next)
if (r % 2 == 0) { // 累加和是偶数,剔除偶数元素的个数
console.log(itemArr.filter(num => num % 2 === 0).length);
} else { // 反之剔除奇数
console.log(itemArr.filter(num => num % 2 !== 0).length);
}
})
}
function cookies1(arr) {
let map = arr.filter((item, index) => index % 2 === 1)
map.forEach(item => {
let oddNum = item.split(' ').filter(num => num % 2 !== 0).length
console.log(oddNum % 2 != 0 ? oddNum : item.split(' ').length - oddNum);
})
}
cookies(['1', '1', "10", "1 2 2 3 4 4 4 2 2 2", '2', '1 1'])
cookies1(['1', '1', "10", "1 2 2 3 4 4 4 2 2 2", '2', '1 1'])
标签:Solo,Cookies,console,分糖,map,item,num,let,split 来源: https://www.cnblogs.com/echoyya/p/16651668.html