Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript identify sum of array elements randomly located within array

So.. currentArray=[n1, n2, n3, n4, sum(currentArray), n5, n6] <–psuedocode obv

So another way would be currentArray.push(sum(oldArray)).shuffle(random) <–psuedo

I thought this would be as easy as using Math.max(...array), like in this example..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

I would be looking for the 12 here, as removing the 12 would result in 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

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..

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()

>Solution :

For both examples you can simply add all vars togehther and divide the sum by 2

sum(array)/2

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading