[英]Javascript identify sum of array elements randomly located within array
So.. currentArray=[n1, n2, n3, n4, sum(currentArray), n5, n6]
<--psuedocode obv所以..
currentArray=[n1, n2, n3, n4, sum(currentArray), n5, n6]
<--psuedocode obv
So another way would be currentArray.push(sum(oldArray)).shuffle(random)
<--psuedo所以另一种方法是
currentArray.push(sum(oldArray)).shuffle(random)
<--psuedo
I thought this would be as easy as using Math.max(...array)
, like in this example..我认为这就像使用
Math.max(...array)
一样简单,就像在这个例子中一样..
shuffled=[1, 12, 3, 6, 2]
I would be looking for the 12 here, as removing the 12 would result in sum(array)=12.我会在这里寻找 12,因为删除 12 会导致 sum(array)=12。
However, it got confusing and difficult when the input had positive and negative numbers included.但是,当输入包含正数和负数时,它会变得混乱和困难。 As in this example..
如本例..
shuffled=[1, -3, -5, 7, 2]
In this case, the solution would be 1, as removing the 1 would result in sum(array)=1在这种情况下,解决方案将是 1,因为删除 1 将导致 sum(array)=1
UPDATE更新
Question had a pretty simple, but not obvious solution, at least to me haha.问题有一个非常简单但不明显的解决方案,至少对我来说哈哈。 Here is the updated, working code.
这是更新的工作代码。
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()
ORIGINAL原来的
My code, but obv its no bueno..我的代码,但 obv 它没有 bueno ..
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()
For both examples you can simply add all vars togehther and divide the sum by 2对于这两个示例,您可以简单地将所有变量相加并将总和除以 2
sum(array)/2
总和(数组)/2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.