Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

How do i generate and sum up random numbers from an array in javascript and python

I have a function that takes an array and a target number. The goal is two generate any two random numbers from the array and sum them up. If the sum of the two random integers is equal to the target number, I then have to return the index of the two random numbers in the array.

Here is my code so far, I keep getting a stderr. How do you recommend I go about this.

function twoSum (numbers, target) {
  let numIdx = [];
  let sum = 0;
  let firstValue = 0;
  let secValue = 0

  while(sum !== target) {
    firstValue = Math.floor(Math.random() * numbers.length);
    secValue = Math.floor(Math.random() * numbers.length);
    sum = firstValue + secValue;
    
    if (sum === target) {
      numIdx.push(numbers[firstValue])
      numIdx.push(numbers[secValue])
      return numIdx
    }
  }
}

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

1 Reply

0 votes
by (71.8m points)

Loop through array of numbers

Then for each one of those numbers loop through again and check if number1 + number2 is equal to your target and also that number1 and number2 arent at the same position in the array (unless that's okay with you)

and return each index

function twoSum(numbers, target) {
  // Loop through the array of numbers
  for (let i = 0; i < numbers.length; i++) {
    const number1 = numbers[i];

    for (let j = 0; j < numbers.length; j++) {
      const number2 = numbers[j];
      // Check if number1 + number2 is equal to target and also make sure number1 and number2 aren't at the same index in the array
      if (number1 + number2 === target && i !== j) {
        return `index 1: ${i}, index 2: ${j}`
      }
    }
  }
}

for instance calling this twoSum([1,2,3], 4) would result in index 1: 0, index 2: 2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...