简体   繁体   中英

finding first occurrence of each digit in an array

Taking each four digit number of an array in turn, return the number that you are on when all of the digits 0-9 have been discovered. If not all of the digits can be found, return "Missing digits!"

ive tried to loop through then set a conditional if (i != i+1) push into new array this just gave me the array, its apperent my logic is wrong. could anyone help me out

for example calling this function with arr =findAllDigits([5175, 4538, 2926, 5057, 6401, 4376, 2280, 6137, 8798, 9083]) should return 5057

while calling arr=findAllDigits([4883, 3876, 7769, 9846, 9546, 9634, 9696, 2832, 6822, 6868]) should return "missing numbers"

    function findAllDigits(arr) {
  newArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] != arr[i + 1]) newArr.push(arr[i]);
    console.log(newArr);
  }
}

do i need to split because it is taking everything before the comma as one number? then itterate over?

You can use Set here

Loop over the array and then create a set , You have to return the current number if set size becomes 10 because you need to check 0-9

 function findAllDigits(arr) { const set = new Set(); for (let n of arr) { String(n) .split("") .forEach((c) => set.add(c)); if (set.size === 10) return n; } return "Missing digits!"; } const arr1 = [5175, 4538, 2926, 5057, 6401, 4376, 2280, 6137, 8798, 9083]; const arr2 = [4883, 3876, 7769, 9846, 9546, 9634, 9696, 2832, 6822, 6868]; console.log(findAllDigits(arr1)); console.log(findAllDigits(arr2));

Your for loop is only checking to see if the array entry is equal to the next one. You need to split up the digits inside each entry and store them individually:

function findAllDigits(arr) {
  newArr = [];
  for (let i = 0; i < arr.length; i++) {
    // now iterate the individual digits
    const entryAsString = arr[i].toString();
    for (let j = 0; j < entryAsString.length; j++) {
      // if we haven't seen the digit before, add it to the array
      if(!newArr.includes(j) {
        newArr.push(j);
      }
    }
    // we know we have all digits when newArr is 10 entries long
    if (newArr.length) {
      console.log(arr[i]);
      // you can also return this value here
    }
  }
}

One more solution:

const arr1 = [5175, 4538, 2926, 5057, 6401, 4376, 2280, 6137, 8798, 9083];
const arr2 = [4883, 3876, 7769, 9846, 9546, 9634, 9696, 2832, 6822, 6868];
            
const findAllDigits = (arr) => {
  const digits = new Set();
  return arr.find((curr) => (
    [...String(curr)].forEach(digits.add, digits),
    (digits.size === 10)
  )) ?? "Missing digits!";
};
                
console.log(findAllDigits(arr1)); //5057
console.log(findAllDigits(arr2)); //Missing digits!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM