Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Домашнее задание из 5 занятия #193

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
194 changes: 183 additions & 11 deletions koans/AboutApplyingWhatWeHaveLearnt.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,19 @@ describe("About Applying What We Have Learnt", function() {
}
}

expect(productsICanEat.length).toBe(FILL_ME_IN);
expect(productsICanEat.length).toBe(1);
});

it("given I'm allergic to nuts and hate mushrooms, it should find a pizza I can eat (functional)", function () {

var productsICanEat = [];

/* solve using filter() & all() / any() */
productsICanEat = products
.filter((product) => product.containsNuts === false)
.filter((product) => !product.ingredients.includes("mushrooms"));

expect(productsICanEat.length).toBe(FILL_ME_IN);
expect(productsICanEat.length).toBe(1);
});

/*********************************************************************************/
Expand All @@ -55,14 +58,16 @@ describe("About Applying What We Have Learnt", function() {
}
}

expect(sum).toBe(FILL_ME_IN);
expect(sum).toBe(233168);
});

it("should add all the natural numbers below 1000 that are multiples of 3 or 5 (functional)", function () {
/* try chaining range() and reduce() */
var sum = _.range(1000)
.filter((i) => i % 3 === 0 || i % 5 === 0)
.reduce(function (sum, x) { return sum + x});

var sum = FILL_ME_IN; /* try chaining range() and reduce() */

expect(233168).toBe(FILL_ME_IN);
expect(233168).toBe(sum);
});

/*********************************************************************************/
Expand All @@ -75,39 +80,206 @@ describe("About Applying What We Have Learnt", function() {
}
}

expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN);
expect(ingredientCount['mushrooms']).toBe(2);
});

it("should count the ingredient occurrence (functional)", function () {
var ingredientCount = { "{ingredient name}": 0 };

/* chain() together map(), flatten() and reduce() */

expect(ingredientCount['mushrooms']).toBe(FILL_ME_IN);
_(products)
.chain()
.map(product => product.ingredients)
.flatten()
.reduce((allNames, name) => {
const currCount = allNames[name] || 0;
allNames[name] = currCount + 1;
return allNames;
}, ingredientCount)
.value();

expect(ingredientCount['mushrooms']).toBe(2);
});

/*********************************************************************************/
/* UNCOMMENT FOR EXTRA CREDIT */
/*

it("should find the largest prime factor of a composite number", function () {

function getLargestPrimeFactor(inputNumber) {
for(let i = inputNumber - 1; i > 1; i--) {
if (inputNumber % i === 0 && isSimpleNumber(i)) {
return i;
}
}
return `${inputNumber} is simple number`;
}

function isSimpleNumber(num) {
for(let i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}

expect(getLargestPrimeFactor(323)).toBe(19);
});

it("should find the largest palindrome made from the product of two 3 digit numbers", function () {
function getMaxPalindrome() {
let max = 0;
for(let i = 999; i >= 100; i--) {
for(let j = 999; j >= 100; j--) {
let result = i*j;
if (result > max && isPalindrome(result)) {
max = result;
}
}
}
return max;
}

function isPalindrome(number) {
let str = number.toString();
let countStr = str.length;

if (countStr === 0 || countStr === 1) {
return true;
}

let index = 0;

while (index <= countStr / 2) {
if (str[index] !== str[countStr - index - 1]) {
return false;
}
index++;
}

return true;
}

expect(getMaxPalindrome()).toBe(906609);
});

it("should find the smallest number divisible by each of the numbers 1 to 20", function () {

function getSmallestNumber1to20() {
let mapResult = new Map();
for(let i = 1; i <= 20; i++) {
for (const [key, value] of getPrimeFactorsWithNumberOfOccurrences(i).entries()) {
if (!mapResult.has(key) || mapResult.get(key) < value) {
mapResult.set(key, value);
}
}
}

let result = 1;
for (const [key, value] of mapResult.entries()) {
result = result * Math.pow(key,value);
}

return result;
}

// Определяем простое ли число
function isSimpleNumber(num) {
if (num === 1) {
return false;
}
for(let i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}

// Получаем степень вхождения делителя в числе (пример, у числа '8' делитель '2' входит 3 раза = 2*2*2)
function getNumberOfOccurrences(value, divisor) {
if (value === 0 || divisor === 0) {
return 0;
}
if (value === divisor) {
return 1;
}
if (divisor === 1) {
return value;
}
let result = 0;
while (value % divisor === 0) {
value = value / divisor;
result++;
}

return result;
}

// Получаем мапу всех простых делителей числа с количеством вхождений (6 = {3 => 1, 2 => 1} 8 = {2 => 3})
function getPrimeFactorsWithNumberOfOccurrences(inputNumber) {
let mapDivisor = new Map();
for(let i = inputNumber; i > 0; i--) {
if ((inputNumber % i === 0 || inputNumber === i) && isSimpleNumber(i)) {
mapDivisor.set(i, 1);
}
}

for (const [key, value] of mapDivisor.entries()) {
mapDivisor.set(key, getNumberOfOccurrences(inputNumber, key));
}

return mapDivisor;
}


expect(getSmallestNumber1to20()).toBe(232792560); // 3724680960(если просто перемножить от 1 до 20)
});

it("should find the difference between the sum of the squares and the square of the sums", function () {
function between(...nums) {
let sumSquares = nums.reduce(function (sumSquares, x) { return sumSquares + x*x});
console.log('sumSquares = ' + sumSquares);

let squaresSum = nums.reduce(function (squaresSum, x) { return squaresSum + x});
squaresSum = squaresSum * squaresSum;
console.log('squaresSum = ' + squaresSum);

return sumSquares - squaresSum;
}

expect(between(1,2,3)).toBe(-22);
});

it("should find the 10001st prime", function () {
function getPrime(simpleIndex) {
let i = 1;
let iteration = 0;
while (true) {
iteration++;
if (isSimpleNumber(iteration)) {
if (i === simpleIndex) {
return iteration;
}
i++;
}
}
}

// Определяем простое ли число
function isSimpleNumber(num) {
if (num === 1) {
return false;
}
for(let i = 2; i < num; i++) {
if (num % i === 0) {
return false;
}
}
return true;
}

expect(getPrime(10001)).toBe(104743);
});
*/
});
60 changes: 30 additions & 30 deletions koans/AboutArrays.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,16 @@ describe("About Arrays", function() {
//We shall contemplate truth by testing reality, via spec expectations.
it("should create arrays", function() {
var emptyArray = [];
expect(typeof(emptyArray)).toBe(FILL_ME_IN); //A mistake? - http://javascript.crockford.com/remedial.html
expect(emptyArray.length).toBe(FILL_ME_IN);
expect(typeof(emptyArray)).toBe('object'); //A mistake? - http://javascript.crockford.com/remedial.html
expect(emptyArray.length).toBe(0);

var multiTypeArray = [0, 1, "two", function () { return 3; }, {value1: 4, value2: 5}, [6, 7]];
expect(multiTypeArray[0]).toBe(FILL_ME_IN);
expect(multiTypeArray[2]).toBe(FILL_ME_IN);
expect(multiTypeArray[3]()).toBe(FILL_ME_IN);
expect(multiTypeArray[4].value1).toBe(FILL_ME_IN);
expect(multiTypeArray[4]["value2"]).toBe(FILL_ME_IN);
expect(multiTypeArray[5][0]).toBe(FILL_ME_IN);
expect(multiTypeArray[0]).toBe(0);
expect(multiTypeArray[2]).toBe("two");
expect(multiTypeArray[3]()).toBe(3);
expect(multiTypeArray[4].value1).toBe(4);
expect(multiTypeArray[4]["value2"]).toBe(5);
expect(multiTypeArray[5][0]).toBe(6);
});

it("should understand array literals", function () {
Expand All @@ -23,36 +23,36 @@ describe("About Arrays", function() {
expect(array).toEqual([1]);

array[1] = 2;
expect(array).toEqual([1, FILL_ME_IN]);
expect(array).toEqual([1, 2]);

array.push(3);
expect(array).toEqual(FILL_ME_IN);
expect(array).toEqual([1,2,3]);
});

it("should understand array length", function () {
var fourNumberArray = [1, 2, 3, 4];

expect(fourNumberArray.length).toBe(FILL_ME_IN);
expect(fourNumberArray.length).toBe(4);
fourNumberArray.push(5, 6);
expect(fourNumberArray.length).toBe(FILL_ME_IN);
expect(fourNumberArray.length).toBe(6);

var tenEmptyElementArray = new Array(10);
expect(tenEmptyElementArray.length).toBe(FILL_ME_IN);
expect(tenEmptyElementArray.length).toBe(10);

tenEmptyElementArray.length = 5;
expect(tenEmptyElementArray.length).toBe(FILL_ME_IN);
expect(tenEmptyElementArray.length).toBe(5);
});

it("should slice arrays", function () {
var array = ["peanut", "butter", "and", "jelly"];

expect(array.slice(0, 1)).toEqual(FILL_ME_IN);
expect(array.slice(0, 2)).toEqual(FILL_ME_IN);
expect(array.slice(2, 2)).toEqual(FILL_ME_IN);
expect(array.slice(2, 20)).toEqual(FILL_ME_IN);
expect(array.slice(3, 0)).toEqual(FILL_ME_IN);
expect(array.slice(3, 100)).toEqual(FILL_ME_IN);
expect(array.slice(5, 1)).toEqual(FILL_ME_IN);
expect(array.slice(0, 1)).toEqual(["peanut"]);
expect(array.slice(0, 2)).toEqual(["peanut", "butter"]);
expect(array.slice(2, 2)).toEqual([]);
expect(array.slice(2, 20)).toEqual(["and", "jelly"]);
expect(array.slice(3, 0)).toEqual([]);
expect(array.slice(3, 100)).toEqual(["jelly"]);
expect(array.slice(5, 1)).toEqual([]);
});

it("should know array references", function () {
Expand All @@ -62,36 +62,36 @@ describe("About Arrays", function() {
refArray[1] = "changed in function";
}
passedByReference(array);
expect(array[1]).toBe(FILL_ME_IN);
expect(array[1]).toBe("changed in function");

var assignedArray = array;
assignedArray[5] = "changed in assignedArray";
expect(array[5]).toBe(FILL_ME_IN);
expect(array[5]).toBe("changed in assignedArray");

var copyOfArray = array.slice();
copyOfArray[3] = "changed in copyOfArray";
expect(array[3]).toBe(FILL_ME_IN);
expect(array[3]).toBe("three");
});

it("should push and pop", function () {
var array = [1, 2];
array.push(3);

expect(array).toEqual(FILL_ME_IN);
expect(array).toEqual([1, 2, 3]);

var poppedValue = array.pop();
expect(poppedValue).toBe(FILL_ME_IN);
expect(array).toEqual(FILL_ME_IN);
expect(poppedValue).toBe(3);
expect(array).toEqual([1, 2]);
});

it("should know about shifting arrays", function () {
var array = [1, 2];

array.unshift(3);
expect(array).toEqual(FILL_ME_IN);
expect(array).toEqual([3, 1, 2]);

var shiftedValue = array.shift();
expect(shiftedValue).toEqual(FILL_ME_IN);
expect(array).toEqual(FILL_ME_IN);
expect(shiftedValue).toEqual(3);
expect(array).toEqual([1, 2]);
});
});
Loading