如何使用javascript以所有六种可能的方式将三个数字除以另外三个数字

问题描述

我有两个数组,每个数组由三个数字组成,实际上是指两个盒子的维度。

const BoxOne = [BoxOneWidth=20,BoxOneLength=40,BoxOneHeight=60];
const BoxTwo = [BoxTwoWidth=2,BoxTwoLength=4,BoxTwoHeight=5];

我想将 BoxOne 的维度划分为 BoxTwo 的维度。但是我需要使用六个可能的场景顺序来帮助自己做一个更复杂的计算。

更具体地说,我需要以更短的方式进行以下计算,否则我将不得不编写大量代码

const BoxOneOpt1 = (BoxOne[0]/BoxTwo[0]) * (BoxOne[1]/BoxTwo[1]) * (BoxOne[2]/BoxTwo[2]);
const BoxOneOpt2 = (BoxOne[0]/BoxTwo[0]) * (BoxOne[1]/BoxTwo[2]) * (BoxOne[2]/BoxTwo[1]);
const BoxOneOpt3 = (BoxOne[0]/BoxTwo[1]) * (BoxOne[1]/BoxTwo[0]) * (BoxOne[2]/BoxTwo[2]);
const BoxOneOpt4 = (BoxOne[0]/BoxTwo[1]) * (BoxOne[1]/BoxTwo[2]) * (BoxOne[2]/BoxTwo[0]);
const BoxOneOpt5 = (BoxOne[0]/BoxTwo[2]) * (BoxOne[1]/BoxTwo[0]) * (BoxOne[2]/BoxTwo[1]);
const BoxOneOpt6 = (BoxOne[0]/BoxTwo[2]) * (BoxOne[1]/BoxTwo[1]) * (BoxOne[2]/BoxTwo[0]);

我知道,它是纯 javascript。我试图使用 for 循环来解决它,但不知何故我无法弄清楚。有人可以帮忙吗?提前致谢。

解决方法

对于这个问题可能是一种天真的方法,但这应该有效:

/**
 * @description return all possible combinations of items in the given array
 * @param { array } xs - array of items
 * @return { array[array] } - permutations
 */
function perm(xs) {
  let ret = [];

  for (let i = 0; i < xs.length; i = i + 1) {
    let rest = perm(xs.slice(0,i).concat(xs.slice(i + 1)));

    if (!rest.length) {
      ret.push([xs[i]]);
    } else {
      for (let j = 0; j < rest.length; j = j + 1) {
        ret.push([xs[i]].concat(rest[j]));
      }
    }
  }
  return ret;
}

const boxOne = [(boxOneWidth = 20),(boxOneLength = 40),(boxOneHeight = 60)];
const boxTwo = [(boxTwoWidth = 2),(boxTwoLength = 4),(boxTwoHeight = 5)];

// get all possible arrangements of the indexes
/*
  Here each number in the array(being passed in as the parameter) corresponds to an index in just one array
  So,if you have three arrays to perform the calculation on,it'll be 
  something like this: [0,1,2,2]
  This can be easily auto-generated based on the arrays.
*/
const arrangements = perm([0,2]);
let finalResult = {};
arrangements.forEach((arrangement,index) => {
  const result = (boxOne[arrangement[0]] / boxTwo[arrangement[1]]) * (boxOne[arrangement[2]] / boxTwo[arrangement[3]]) * (boxOne[arrangement[4]] / boxTwo[arrangement[5]])
  finalResult[`boxOneOpt${index+1}`] = result
})
console.log(finalResult);

,

由于所有 6 个结果始终相同,因此您只需要进行一次计算。例如:const boxOneOpt123456 = (boxOne[0]*boxOne[1]*boxOne[2]) / (boxTwo[0]*boxTwo[1]*boxTwo[2]);