Files
freeCodeCamp/curriculum/challenges/russian/08-coding-interview-prep/rosetta-code/averages-mode.russian.md
2020-02-13 11:55:03 +04:00

2.2 KiB

title, id, challengeType, forumTopicId, localeTitle
title id challengeType forumTopicId localeTitle
Averages/Mode 594d8d0ab97724821379b1e6 5 302226 Сред-Mode

Description

Напишите программу , чтобы найти режим значение коллекции.

Случай, когда коллекция пуста, может быть проигнорирован. Необходимо следить за тем, чтобы режим не был уникальным.

Если это не подходит или возможно поддерживает общую коллекцию, используйте вектор (массив), если это возможно. Если это не подходит или возможно поддерживает неопределенный тип значения, используйте целые числа.

Instructions

Tests

tests:
  - text: <code>mode</code> is a function.
    testString: assert(typeof mode === 'function');
  - text: <code>mode([1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17])</code> should equal <code>[6]</code>
    testString: assert.deepEqual(mode(arr1), [6]);
  - text: <code>mode([1, 2, 4, 4, 1])</code> should equal <code>[1, 4]</code>.
    testString: assert.deepEqual(mode(arr2).sort(), [1, 4]);

Challenge Seed

function mode(arr) {
  // Good luck!
  return true;
}

After Tests

const arr1 = [1, 3, 6, 6, 6, 6, 7, 7, 12, 12, 17];
const arr2 = [1, 2, 4, 4, 1];

Solution

function mode(arr) {
  const counter = {};
  let result = [];
  let max = 0;
  // for (const i in arr) {
  arr.forEach(el => {
    if (!(el in counter)) {
      counter[el] = 0;
    }
    counter[el]++;

    if (counter[el] === max) {
      result.push(el);
    }
    else if (counter[el] > max) {
      max = counter[el];
      result = [el];
    }
  });
  return result;
}