所以.. currentArray=[n1, n2, n3, n4, sum(currentArray), n5, n6]<--psuedocode 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()
原來的
我的代碼,但 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()
uj5u.com熱心網友回復:
對于這兩個示例,您可以簡單地將所有變數相加并將總和除以 2
總和(陣列)/2
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/495965.html
標籤:javascript 数组 排序
