Найти и вернуть элемент, который чаще всего встречается в массиве

Рабочий пример для Турции, просто измените

d{9}

в соответствии с вашими потребностями и начните использовать его.

function validateMobile($phone)
{
    $pattern = "/^(05)\d{9}$/";
    if (!preg_match($pattern, $phone))
    {
        return false;
    }
    return true;
}

$phone = "0532486061";

if(!validateMobile($phone))
{
    echo 'Incorrect Mobile Number!';
}

$phone = "05324860614";
if(validateMobile($phone))
{
    echo 'Correct Mobile Number!';
}
1
задан Maryam Abbas 24 March 2019 в 23:12
поделиться

2 ответа

Хотелось бы что-нибудь подобное?

export let findMode = (b: number[]): number => {
    // we'll store the values in b and the number of times they occur here
    const counts: Array<{ value: number, count: number }> = [];

    // it helps to check that b is defined before you check length, this avoids ReferenceErrors
    if (!b || !b.length) {
        return 0;
    }

    for (let i = 0; i < b.length; i++) {
        const val = b[i];
        const count = counts.find(count => count.value === val);

        if (count) {
            count.count++;
        } else {
            counts.push({ value: val, count: 1 });
        }
    }

    // get the mode by sorting counts descending and grabbing the most occuring
    const mode = counts.sort((c1, c2) => c2.count - c1.count)[0];

    // and now if you *need* an intermediate array with the index mapped to the value and value mapped to the count:
    const largestNumber = counts.sort((c1, c2) => c2.value - c1.value)[0];
    // initialize an empty as long as the largest number
    let newArr = new Array(largestNumber);
    newArr = newArr.map((val, i) => {
        const count = counts.find(count => count.value === i);
        if (count) {
            return count.count;
        } else {
            return 0; // 'i' occurs 0 times in 'b'
        }
    });
};
0
ответ дан Orion K. 24 March 2019 в 23:12
поделиться

Вы можете использовать метод Array#reduce для достижения результата с дополнительным объектом для ведения счета.

export let findMode = (b: number[]): number => {
  // object for keeping count of each element
  // initially set `0` with 0 count (default value)
  let ref = {
    '0': 0
  };

  return b.reduce((value, num) => {
    // define count as 0 if not defined 
    ref[num] = ref[num] || 0;

    // increment element count
    ref[num]++;
    // if number count is gretater than previous element count
    // then return current element
    if (ref[num] > ref[value]) {
      return num;
    // if counts are same then return the smallest value
    } else if (ref[num] === ref[value]) {
      return num < value ? num : value;
    }
    // else return the previous value
    return value;
    // set initial value as 0(default)
  }, 0);
};

let findMode = b => {

  let ref = {
    '0': 0
  };

  return b.reduce((value, num) => {
    ref[num] = ref[num] || 0;
    ref[num]++;
    if (ref[num] > ref[value]) {
      return num;
    } else if (ref[num] === ref[value]) {
      return num < value ? num : value;
    }
    return value;
  }, 0);
};


[
  [2, 1, 1, 2, 1, 0],
  [1, 3, 2],
  [0, 0, 0, 1, 1, 2, 1, 1],
  [4, 4, 7, 4, 0, 7],
  [-4, -4, -1, 3, 5],
  [1, 1, 2, 3, 2],
  [10, 10, 10, 20, 20, 30]
].forEach(v => console.log(findMode(v)))

0
ответ дан Pranav C Balan 24 March 2019 в 23:12
поделиться
Другие вопросы по тегам:

Похожие вопросы: