Skip to content

CodeWars, Class assignment, Severe polymorphism and inheritance hierarchy, Calculating a person's age #21

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

Open
wants to merge 12 commits into
base: Pyzhov_Viktor
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
25 changes: 25 additions & 0 deletions codewars/Adding Big Numbers/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
function add(a, b) {
let result = "";
let carry = 0;
let i = a.length - 1;
let j = b.length - 1;
while (i >= 0 || j >= 0 || carry > 0) {
const digit1 = i >= 0 ? Number(a[i]) : 0;
const digit2 = j >= 0 ? Number(b[j]) : 0;
const sum = digit1 + digit2 + carry;
const digitSum = sum % 10;
carry = Math.floor(sum / 10);
result = digitSum.toString() + result;
i--; j--;
}
return result;
}

console.log(add("123", "321"))
console.log(add("11", "99"))
console.log(add("1", "1"), "2")
console.log(add("123", "456"), "579")
console.log(add("888", "222"), "1110")
console.log(add("1372", "69"), "1441")
console.log(add("12", "456"), "468")
console.log(add('63829983432984289347293874', '90938498237058927340892374089') == "91002328220491911630239667963")
42 changes: 42 additions & 0 deletions codewars/Anagram difference/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
function anagramDifference(w1, w2) {
// Подсчитайте частоту употребления каждой буквы в обоих словах
const frequency1 = countLetterFrequency(w1.split(''));
const frequency2 = countLetterFrequency(w2.split(''));

let count = 0;

// Посчитать разницу в частоте букв
for (let letter in frequency1) {
if (frequency1.hasOwnProperty(letter)) {
const diff = Math.abs(frequency1[letter] - (frequency2[letter] || 0));
count += diff;
}
}

// Добавьте лишние буквы во второе слово
for (let letter in frequency2) {
if (frequency2.hasOwnProperty(letter) && !frequency1.hasOwnProperty(letter)) {
count += frequency2[letter];
}
}

return count;
}

function countLetterFrequency(word) {
// Посчитать как часто встречается буква в слове
const frequency = {};

for (let i = 0; i < word.length; i++) {
const letter = word[i];
frequency[letter] = frequency[letter] ? frequency[letter] + 1 : 1;
}

return frequency;
}


console.log(anagramDifference("", ""), 0)
console.log(anagramDifference("a", ""), 1)
console.log(anagramDifference("", "a"), 1)
console.log(anagramDifference("ab", "a"), 1)
13 changes: 13 additions & 0 deletions codewars/Array Deep Count/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
function deepCount(a) {
let count = a.length;
for (let i of a) { if (Array.isArray(i)) { count += deepCount(i) } }
return count;
}


console.log(deepCount([]))
console.log(deepCount([1, 2, 3]))
console.log(deepCount(["x", "y", ["z"]]))
console.log(deepCount([1, 2, [3, 4, [5]]]))
console.log(deepCount([[[[]]]]))
// console.log([[[[[[[[[]]]]]]]]])
18 changes: 18 additions & 0 deletions codewars/Build Tower/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.towerBuilder = void 0;
var towerBuilder = function (nFloors) {
var tower = [];
var lastFloor = (nFloors - 1) * 2 + 1;
var space = 0;
for (var i = 0; i < nFloors; i++) {
var floor = " ".repeat(space) + "*".repeat(lastFloor) + " ".repeat(space);
tower.push(floor);
space++;
lastFloor -= 2;
}
return tower.reverse();
};
exports.towerBuilder = towerBuilder;
console.log((0, exports.towerBuilder)(3));
console.log((0, exports.towerBuilder)(6));
16 changes: 16 additions & 0 deletions codewars/Build Tower/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export const towerBuilder = (nFloors: number): string[] => {
let tower = [];
let lastFloor = (nFloors - 1) * 2 + 1;
let space = 0;
for (let i = 0; i < nFloors; i++) {
let floor = " ".repeat(space) + "*".repeat(lastFloor) + " ".repeat(space)
tower.push(floor)
space++
lastFloor -= 2
}

return tower.reverse();
}

console.log(towerBuilder(3))
console.log(towerBuilder(6))
10 changes: 10 additions & 0 deletions codewars/Convert string to camel case/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
function toCamelCase(str) {
str = str.split(/[-_]+/)
let arr = [str[0]]
for (i of str.slice(1)) { arr.push(i[0].toUpperCase() + i.slice(1)) }
return arr.join("")
}

console.log(toCamelCase("the_stealth_warrior"))
console.log(toCamelCase("The-Stealth-Warrior"))
console.log(toCamelCase("The_Stealth-Warrior"))
25 changes: 25 additions & 0 deletions codewars/Duplicate Encoder/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
function duplicateEncode(word) {
// const не изменяемая переменная, let изменяемая переменная
const charCount = {};

// toLowerCase() возвращает значение строки, преобразованное в нижний регистр
word = word.toLowerCase()

// Оператор for...of выполняет цикл обхода итерируемых объектов (включая Array, Map, Set, объект аргументов и подобных),
// вызывая на каждом шаге итерации операторы для каждого значения из различных свойств объекта.
for (const i of word) {
charCount[i] = (charCount[i] || 0) + 1
}

// Метод split() разбивает строку на массив
return word.split('').map(i => { // "=>" стрелочная функция, представляет собой более короткую форму функции
return charCount[i] === 1 ? '(' : ')'
}).join(''); // Метод join() объединяет все элементы массива (или массивоподобного объекта) в строку
}


// Тесты
console.log(duplicateEncode("din") == "(((");
console.log(duplicateEncode("recede") == "()()()");
console.log(duplicateEncode("Success") == ")())())");
console.log(duplicateEncode("(( @") == "))((");
19 changes: 19 additions & 0 deletions codewars/Duplicate Encoder/main2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.duplicateEncode = void 0;
function duplicateEncode(word) {
var charCount = {};
word = word.toLowerCase();
for (var _i = 0, word_1 = word; _i < word_1.length; _i++) {
var i = word_1[_i];
charCount[i] = (charCount[i] || 0) + 1;
}
return word.split('').map(function (i) {
return charCount[i] === 1 ? '(' : ')';
}).join('');
}
exports.duplicateEncode = duplicateEncode;
console.log(duplicateEncode("din") == "(((");
console.log(duplicateEncode("recede") == "()()()");
console.log(duplicateEncode("Success") == ")())())");
console.log(duplicateEncode("(( @") == "))((");
18 changes: 18 additions & 0 deletions codewars/Duplicate Encoder/main2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
export function duplicateEncode(word: string) {
const charCount: { [key: string]: number } = {};

word = word.toLowerCase();

for (const i of word) {
charCount[i] = (charCount[i] || 0) + 1;
}

return word.split('').map((i: string) => {
return charCount[i] === 1 ? '(' : ')';
}).join('');
}

console.log(duplicateEncode("din") == "(((");
console.log(duplicateEncode("recede") == "()()()");
console.log(duplicateEncode("Success") == ")())())");
console.log(duplicateEncode("(( @") == "))((");
14 changes: 14 additions & 0 deletions codewars/Find the missing letter/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.findMissingLetter = void 0;
function findMissingLetter(array) {
for (var i = array[0].charCodeAt(0); i < array[array.length - 1].charCodeAt(0); i++) {
if (array.indexOf(String.fromCharCode(i)) == -1) {
return String.fromCharCode(i);
}
}
return "";
}
exports.findMissingLetter = findMissingLetter;
console.log(findMissingLetter(['a', 'b', 'c', 'd', 'f']));
console.log(findMissingLetter(['O', 'Q', 'R', 'S']));
11 changes: 11 additions & 0 deletions codewars/Find the missing letter/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
export function findMissingLetter(array: string[]): string {
for (let i = array[0].charCodeAt(0); i < array[array.length - 1].charCodeAt(0); i++) {
if (array.indexOf(String.fromCharCode(i)) == -1) {
return String.fromCharCode(i);
}
}
return "";
}

console.log(findMissingLetter(['a', 'b', 'c', 'd', 'f']));
console.log(findMissingLetter(['O', 'Q', 'R', 'S']));
38 changes: 38 additions & 0 deletions codewars/Flatten a Nested Map/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
function flattenMap(map, prefix = '', result = {}) {
for (let i in map) {
const value = map[i];
let newKey
if (prefix) {
newKey = prefix + '/' + i
} else {
newKey = i
}

if (value && typeof value === 'object' && !Array.isArray(value)) {
flattenMap(value, newKey, result);
} else {
result[newKey] = value;
}
}
return result;
}

console.log(flattenMap({
'a': {
'b': {
'c': 12,
'd': 'Hello World'
},
'e': [1, 2, 3],
'v': true,
'r': null,
'n': [],
'A': {
'h': {
'OOOO': {
'lol': false
}
}
}
}
}))
21 changes: 21 additions & 0 deletions codewars/Fun with tree - max sum/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
function maxSum(root) {
if (!root) { return 0; }

let max = Number.MIN_SAFE_INTEGER;

function dfs(node, sum) {
if (!node) { return; }

sum += node.value;

// Достигнут конечный узел, при необходимости обновите максимальную сумму.
if (!node.left && !node.right) { max = Math.max(max, sum); }

dfs(node.left, sum);
dfs(node.right, sum);
};

dfs(root, 0);

return max;
}
30 changes: 30 additions & 0 deletions codewars/Linked Lists - Sorted Insert/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
function Node(data) {
this.data = data;
this.next = null;
}

function sortedInsert(head, data) {
const newNode = new Node(data);
if (!head || data < head.data) {
newNode.next = head;
return newNode;
}
let curr = head;
while (curr.next && data >= curr.next.data) { curr = curr.next; }
newNode.next = curr.next;
curr.next = newNode;
return head;
}

// Лучшее решение
// function Node(data, nxt) {
// this.data = data;
// this.next = nxt;
// }
// function sortedInsert(head, data) {
// if (!head || data < head.data) return new Node(data, head);
// else {
// head.next = sortedInsert(head.next, data);
// return head;
// }
// }
13 changes: 13 additions & 0 deletions codewars/Merge two arrays/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
function mergeArrays(a, b) {
const result = [];
const maxLen = Math.max(a.length, b.length);
for (let i = 0; i < maxLen; i++) {
if (i < a.length) { result.push(a[i]); }
if (i < b.length) { result.push(b[i]); }
}
return result;
}


console.log(mergeArrays(['a', 'b', 'c', 'd', 'e'], [1, 2, 3, 4, 5]))
console.log(mergeArrays([2, 5, 8, 23, 67, 6], ['b', 'r', 'a', 'u', 'r', 's']))
15 changes: 15 additions & 0 deletions codewars/Moving Zeros To The End/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
function moveZeros(arr) {
let zeros = 0;
let newarr = [];
for (i in arr) {
if (arr[i] !== 0) {
newarr.push(arr[i]);
} else {
zeros++;
}
}
for (let i = 0; i < zeros; i++) { newarr.push(0) }
return newarr;
}

console.log(moveZeros([false, 1, 0, 1, 2, 0, 1, 3, "a"]));
31 changes: 31 additions & 0 deletions codewars/Permutations/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
function permutations(array) {
array = array.split("")
const result = new Set();

const indices = Array(array.length).fill(0);

result.add([...array].join(""));

let i = 0;
while (i < array.length) {
if (indices[i] < i) {
if (i % 2 === 0) {
[array[0], array[i]] = [array[i], array[0]];
} else {
[array[indices[i]], array[i]] = [array[i], array[indices[i]]];
}

result.add([...array].join(""));

indices[i]++;
i = 0;
} else {
indices[i] = 0;
i++;
}
}

return Array.from(result);
}

console.log(permutations("aabb"))
Loading