Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
82 views
in Technique[技术] by (71.8m points)

javascript - Find the opposite number in the array

I'm trying to find the opposite number in the array.

Let's say we have this array: [1,3,4,-3]

What I want is:

{ '1': 1, '3': 2, '4': 1 } // as we have two 3

and what I tried is :

  const arr = [1,3,4,-3]
  let holder = {}
  arr.map(a => {
    holder[a] = (holder[a] ||0)+1
  })
      
  console.log(holder)
question from:https://stackoverflow.com/questions/65910492/find-the-opposite-number-in-the-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The rules can be summed up as follow:

Let v be the array Let x a positive number in the array

  1. if x is in v but not -x, keep {[x]:1}
  2. if x is in v and -x also, keep {[x]:2}

Let y a negative number in the array

  • if y is in v and -y also do nothing (symetry of 2.)
  1. if y is in v but not -y, keep {[y]:1}

Now it is pretty straightforward:

  • build a set of values of v
  • check all the positive keys
  • foreach one, check if there exists its opposite and apply 1. or 2.
  • delete any opposite keys
  • for the remaining keys (which are then negative and have no opposite) apply 3.

const v = [1,1,1,-2, 3,3,-3, 4,-4,-4]
const output = {}
const s = new Set(v)
const positives = [...new Set(v.filter(x => x>= 0))]
positives.forEach(p => {
  if (s.has(-p)) {
    output[p] = 2
    s.delete(-p)
  } else {
    output[p] = 1
  }
  s.delete(p)
})
;[...s].forEach(negative => {
  output[negative] = 1
})

console.log('output', output)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...