Encounter Algorithm - Dividing Apples

divided apples

A and B divide the apples into two piles. A wants to divide the apples equally according to his calculation rule. His calculation rule is to calculate according to binary addition, and does not calculate the carry 12+5=9 (1100 + 0101 = 9), The calculation rule of B is decimal addition, including normal carry, and B hopes to get the most weight of apples when A is satisfied.

Example 1:

There are 3 apples with weights 12, 5, and 9. Then according to the requirements of the title, the best way to divide is: A gets two apples with weights 12 and 5, and B gets an apple with a weight of 9. At this time, it just meets the requirements of B - the weights of the two apples obtained by A are 12 and 5. The binary number of 12 is 1100, and the binary number of 5 is 0101. The sum of these two binary numbers ignoring the carry is equal to 1001. For the decimal number, it is 9, which is exactly the weight of the apple allocated by B.

Example 2:

There are 3 apples with weights 3, 5, and 6. Then according to the requirements of the title, the best way to divide is: A gets two apples with weights 5 and 6, and B gets an apple with a weight of 3. At this time, it just meets the requirements of B - the weights of the two apples obtained by A are 5 and 6, the binary number of 5 is 0101, and the binary number of 6 is 0110. The sum of these two binary numbers ignoring the carry is equal to 0011, and the conversion The decimal number is 3, which is exactly the weight of the apple that B gets.

code

function cutApple(s) {
  const list = s.split(' ');
  const len = list.length;
  if (len === 1) {
    console.log(-1);
  } else {
    const total = list.reduce((a, b) => Number(a) + Number(b));
    let result = -1;
    const dfs = (level, sum, xor) => {
      if (level === list.length) {
        const diff = total - sum;
        if (diff === xor && level !== 0 && diff !== 0) {
          result = Math.max(result, sum);
        }

        return;
      }
      dfs(level + 1, sum + Number(list[level]), xor ^ Number(list[level]));
      dfs(level + 1, sum, xor);
    };
    dfs(0, 0, 0);
    console.log('result', result);
  }
}

var testList = ['3 5 6', '7258 6579 2602 6716 3050 3564 5396 1773', '12 5 9'];

testList.forEach((v) => {
  cutApple(v);
});

Optimized

function cutApple(s) {
  const list = s.split(' ');
  const len = list.length;
  if (len === 1) {
    console.log(-1);
  } else {
    let c = 0;
    for (let i = 0; i < list.length; i++) {
      c = c ^ Number(list[i]);
    }
    if (c === 0) {
      list.sort((a, b) => Number(a) - Number(b));
      const t = list.reduce((a, b) => Number(a) + Number(b));
      console.log(t - list[0]);
    } else {
      console.log(-1);
    }
  }
}

var testList = ['3 5 6', '7258 6579 2602 6716 3050 3564 5396 1773', '12 5 9'];
//var testList = ['3 5 6', '12 5 9'];

testList.forEach((v) => {
  cutApple(v);
});

Guess you like

Origin juejin.im/post/7120929832208171038