Skip to content

Instantly share code, notes, and snippets.

@tuscen
Last active May 12, 2020 21:50
Show Gist options
  • Select an option

  • Save tuscen/51a5bafa0394561cfb92 to your computer and use it in GitHub Desktop.

Select an option

Save tuscen/51a5bafa0394561cfb92 to your computer and use it in GitHub Desktop.
// Задание:
// 1) генерируем последовательность натуральных чисел до ста
// 2) оставляем только нечетные
// 3) складываем их попарно
// 4) оставляем только те, у которых в бинарном представлении
// количество единиц и нулей одинаковое
// 5) возвращаем общее количество единиц
'use strict'
function partition(array, size) {
if (array.length === 0) return result;
const part = array.slice(0, size);
return [part].concat(partition(array.slice(part.length), size);
}
const count = (string, predicate) => string.split('').filter(predicate).length;
const toBinary = decNum => parseInt(decNum, 10).toString(2);
const equals = comp => char => char === comp;
const isOdd = number => number & 1 === 1;
function isEqualZeroAndOneCount(binary) {
const zeros = count(binary, equals('0'));
const ones = count(binary, equals('1'));
return zeros === ones;
}
function solution(size) {
const naturalNumber = Array.apply(null, {length: size})
.map(Number.call, Number)
.map(n => n + 1);
const oddNumbers = naturalNumber.filter(isOdd);
return partition(oddNumbers, 2)
.map(pair => pair.reduce((fst, snd) => fst + snd))
.map(toBinary)
.filter(isEqualZeroAndOneCount)
.map(bin => count(bin, equals('1')))
.reduce((ones, n) => ones + n, 0)
}
console.log(solution(100)); // => 20
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment