Олимпиада для котов - мой варик

function getYears(start,end,num){
var year = [];
while(start <= end){
arr = String(start).split(’’).reduce((accumulator, currentValue) => {
accumulator = Number(currentValue) + Number(accumulator);
return accumulator
}
)
if(arr === num){
year.push(start)
}
start++
}
return year
}

console.log(getYears(2000,2020,4))

1 лайк

var getYears = function (start, finish, sum) {
var olymp = [];
for(var i = (finish - start); i >= 0; i–) {
if (start <= finish) {
var str = String(start);
var sym = Number(str[0]) + Number(str[1]) + Number(str[2]) + Number(str[3]);
if(sym == sum) {
olymp.push(start);
}
start++;
}
}
return olymp;
}

var getYears = function (beginYear, endYear, sumYear) {
var arrayYear = [];
var z = 0;
for (let i = beginYear; i <= endYear; i++) {
var sum = 0;
for (let j = 0; j < 4; j++) {
sum = sum + Math.trunc((i % (Math.pow(10, j + 1))) / (Math.pow(10, j)));
}
if (sum === sumYear) {
arrayYear[z] = i;
z++;
}
}
return(arrayYear);
}

С reduce

const reducer = (acc, value) => Number(acc) + Number(value);

const culcSumYear = year => {
 const numbers = String(year).split('');

 return numbers.reduce(reducer);
}

let getYears = function (yearStart, endYear, sum) {
  const years = [];
  for (let i = yearStart; i <= endYear; i++) {
    const sumYear = culcSumYear(i);

    if (sumYear === sum) {
      years.push(i);
    }
  }

  return years;
}

Только с тем, что проходили Ж

let arraySum = function(array) {
  let arrSum = 0;
  for (item of array) {
    arrSum += Number(item);
  };
  return arrSum;
};

let getYears = function(startYear, finishYear, sumYear) {
  
  let years = [];
  
  for (let i = startYear; i <= finishYear; i++) {
    let year = String(i);
    let yearStringArray = [];
    
    for(let j = 0; j < year.length; j++) {
      yearStringArray.push(year[j]);
    };
    
    if (arraySum(yearStringArray) === sumYear) {
      years.push(i);console.log(year.length);
    };
    
  };
  return years;
};