Javascript识别随机位于数组中的数组元素的总和

Bri*_*son 1 javascript arrays sorting

所以.. currentArray=[n1, n2, n3, n4, sum(currentArray), n5, n6]<--伪代码 obv

所以另一种方式是 currentArray.push(sum(oldArray)).shuffle(random)<--psuedo

我认为这就像使用 一样简单Math.max(...array),就像在这个例子中一样。

shuffled=[1, 12, 3, 6, 2]

我会在这里寻找 12,因为删除 12 将导致 sum(array)=12。

然而,当输入包含正数和负数时,它会变得混乱和困难。正如在这个例子中..

shuffled=[1, -3, -5, 7, 2]

在这种情况下,解决方案将为 1,因为删除 1 将导致 sum(array)=1

更新

问题有一个非常简单但不明显的解决方案,至少对我来说哈哈。这是更新后的工作代码。

Array.prototype.polysplice = function (criteria)  {
    this.splice(this.indexOf(criteria),1)
    return this }
    
Array.prototype.polysort = function () {
    return this.sort((a, b) => a - b)  }
    
Array.prototype.polysum = function (subject) {
    return this.reduce((a,b) => a + b, 0) }

const solution = shuffled => shuffled.polysplice(shuffled.polysum()/2).polysort()
Run Code Online (Sandbox Code Playgroud)

原来的

我的代码,但显然它没有布埃诺..

Array.prototype.sliceAll = function (criteria) {
    return this.filter(e=>e !== criteria) }
    
Array.prototype.polysort = function () {
    return this.sort((a, b) => a - b)  }
    
const solution = shuffled => shuffled.sliceAll(Math.max(...shuffled)).polysort()
Run Code Online (Sandbox Code Playgroud)

小智 6

对于这两个示例,您只需将所有变量加在一起并将总和除以 2

总和(数组)/2

  • 这比我要发布的解决方案还要简单,即对数组求和,然后减去数组的每个元素并检查结果是否等于该元素。 (2认同)