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

Codewars + задание на классы #14

Open
wants to merge 4 commits into
base: Midjaeva_Evgenija_Gennadevna
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
13 changes: 13 additions & 0 deletions codewars/Adding Big Numbers/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
function add(a, b) {

a = Array.from(a).reverse()
b = Array.from(b).reverse()

for (let count = 0; count < b.length; count++) {
if ((a[count] = ~~a[count] + ~~b[count]) > 9) {
b[count+1] = ~~b[count+1] + 1
a[count] -= 10
}
}
return a.reverse().join("")
}
13 changes: 13 additions & 0 deletions codewars/Anagram difference/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
function anagramDifference(w1,w2){

let len = w1.length + w2.length
let num = 0;
for (count = 0; count < w2.length;){
if (w1.includes(w2[count])) {
w1 = w1.replace(w2[count], "")
w2 = w2.replace(w2[count], "")
num += 2
} else count++
}
return len - num
}
12 changes: 12 additions & 0 deletions codewars/Array Deep Count/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
function deepCount(a){

let arrays = 0;
const Counts = (array) => {
arrays += array.length;
for ( let count of array ) {
if ( Array.isArray(count) ) Counts(count);
}
}
Counts(a);
return arrays;
}
10 changes: 10 additions & 0 deletions codewars/Build Tower/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
function towerBuilder(nFloors) {

let array = []
for (count = 0; count < nFloors; count++){
let repeat = nFloors - count - 1
array.push(" ".repeat(repeat) + "*".repeat(1 + 2 * count) + " ".repeat(repeat))
}
return array;
}
console.log(towerBuilder(6));
10 changes: 10 additions & 0 deletions codewars/Convert string to camel case/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
function toCamelCase(str){
let word = Array.from(str)
word.forEach((element, item) =>{
if (element == "_" || element == "-"){
word.splice(item, 1)
word[item] = word[item].toUpperCase()
}
})
return word.join("")
}
24 changes: 24 additions & 0 deletions codewars/Duplicate Encoder/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
function duplicateEncode(word){

let map = new Map()
word = word.toLowerCase()
result = ""

for (let count = 0; count < word.length; count++) {
if (map.get(word[count]) == undefined){
map.set(word[count], 1)
} else {
map.set(word[count], map.get(word[count]) + 1)
}
}

for (let index = 0; index < word.length; index++) {
if (map.get(word[index]) > 1 ){
result += ")"
} else {
result += "("
}

}
return result;
}
28 changes: 28 additions & 0 deletions codewars/Find the missing letter/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
function findMissingLetter(array) {

let alphabet = "abcdefghijklmnopqrstuvwxyz".split("");
let uppercase = false;
result = "";

if (array[0] == array[0].toUpperCase()){
uppercase = true;
}

for (count = 0; count < alphabet.length; count++){
if(array[0] == alphabet[count] || array[0] == alphabet[count].toUpperCase()){
alphabet = alphabet.splice(count, array.length);
break;
}
}

for (i = 0; i < array.length; i++){
if (!uppercase && array[i] != alphabet[i]){
result = alphabet[i];
break;
} else if (uppercase && array[i] != alphabet[i].toUpperCase()){
result = alphabet[i].toUpperCase();
break;
}
}
return result;
}
13 changes: 13 additions & 0 deletions codewars/Flatten a Nested Map/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
function flattenMap(map) {
return result(map, "", {})
}
function result(object, current, response) {
if (Object.prototype.toString.call(object)!=="[object Object]") {
response[current.substring(1)]=object
return
}
for (let count of Object.keys(object)) {
result(object[count], current+"/"+count, response)
}
return response
}
5 changes: 5 additions & 0 deletions codewars/Fun with tree - max sum/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
function maxSum(root) {

if (!root) return 0
return root.value + Math.max(maxSum(root.left),maxSum(root.right))
}
24 changes: 24 additions & 0 deletions codewars/Linked Lists - Sorted Insert/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
function Node(data) {
this.data = data;
this.next = null;
}

function sortedInsert(head, data) {

if (head === null) return new Node(data);

if (data < head.data) {
let new_head = new Node(data);
new_head.next = head;
return new_head;
}

let current_node = head;
while (current_node.next !== null && current_node.next.data < data) {
current_node = current_node.next;
}
let insert = new Node(data);
insert.next = current_node.next;
current_node.next = insert;
return head;
}
12 changes: 12 additions & 0 deletions codewars/Merge two arrays/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
function mergeArrays(a, b) {

let array = [];
let maxLen = a.length > b.length? a.length: b.length;

for (count = 0; count < maxLen; count++){
if (a[count] === undefined) array.push(b[count])
else if (b[count] === undefined) array.push(a[count])
else array.push(a[count], b[count])
}
return array
}
9 changes: 9 additions & 0 deletions codewars/Moving Zeros To The End/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
function moveZeros (arr) {
for (let count = arr.length - 1; count >= 0; count--) {
if (arr[count] === 0) {
arr.splice(count, 1);
arr.push(0);
}
}
return arr;
}
18 changes: 18 additions & 0 deletions codewars/Permutations/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
function permutations(string) {

let result = [];
if (string.length < 2) return [string];

const noRepeat = (array) => {
let set = new Set(array);
return [...set];
}

for (let count = 0; count < string.length; count++){
let path = string.slice(0, count) + string.slice (count+1, string.length)
for(let item of permutations(path)){
result.push([string[count], item].join(""))
}
}
return noRepeat(result)
}
13 changes: 13 additions & 0 deletions codewars/Simple Pig Latin/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
function pigIt(str){

let arr = str.split(" ")
let result = ""

arr.forEach((element) => {
if (element.toLowerCase() != element.toUpperCase()){
element = element.substring(1)+element[0] + "ay"
}
result += element + " "
})
return result.slice(0, result.length-1)
}
3 changes: 3 additions & 0 deletions codewars/Sum of Digits - Digital Root/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
function digitalRoot(n) {
return (n-1) % 9 + 1
}
9 changes: 9 additions & 0 deletions codewars/Sum of pairs/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
function sumPairs (ints, s){

const set = new Set();

for (const element of ints) {
if (set.has(s - element)) return [s - element, element];
set.add(element);
}
};
16 changes: 16 additions & 0 deletions codewars/Tic-Tac-Toe Checker/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
function isSolved(board) {

let array = [...board[0], ...board[1], ...board[2]]
if (board[1][1] != 0){
if (board[0][0] === board[1][1] && board[0][0] === board[2][2]) return board[1][1]
else if (board[0][2] === board[1][1] === board[2][0]) return board[1][1]
}
for (count = 0; count < board.length; count++){
let boards = board[count]
let arr = [board[0][count], board[1][count], board[2][count]]
if (boards.every( elem => elem === boards[0] && boards[count] != 0)) return boards[0]
else if (arr.every( elem => elem === arr[0]) && arr[count] != 0) return arr[0]
else if (!array.includes(0)) return 0
}
return -1
}
16 changes: 16 additions & 0 deletions codewars/Valid Parentheses/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
function validParentheses(parens) {

let arr = [];
if (parens.length % 2 == 1) return false

for (count = 0; count < parens.length; count++){
if (parens[count] == "("){
arr.push(parens[count])
} else if (parens[count] == ")" && arr.length == 0){
arr.shift()
}
}
if (arr.length != 0){
return false
} else return true
}
17 changes: 17 additions & 0 deletions codewars/Where my anagrams at/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
function sortAlpha(letter) {
return [...letter].sort((a,b)=>a.localeCompare(b)).join("")
}

function anagrams(word, words) {

word = sortAlpha(word)
let result = [];

words.forEach(element => {
let elements = sortAlpha(element);
if (elements == word){
result.push(element)
}
});
return result
}
42 changes: 42 additions & 0 deletions rpgsaga/saga/src/gun.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
export class Gun {
readonly serialNumber: string = 's00001';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

присваиваете значение в конструкторе - для счетчика можно завести приватную статическую переменную и исходя из нее увеличивать счетчик и устанавливать соответствующий серийный номер

private aMagazine: number;
model: string;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

protected


shotCount = 0;

constructor(modelName: string, magazine: number, public bullets?: number) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
constructor(modelName: string, magazine: number, public bullets?: number) {
constructor(modelName: string, magazine: number, protected bullets?: number) {

this.model = modelName;
this.magazine = magazine;
this.bullets = this.bullets < this.magazine && this.bullets >= 0 ? this.bullets : this.magazine;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

если я передам отрицательное или слишком большое число - то стоит бросать исключение - exception

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

для установки лучше бы создать приватный метод и просто его из конструктора вызвать

}
// инфо :)
info() {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

давайте переименуем в toString() : string <- указывайте тип возвращаемого значения

return `You're create gun model: "${this.model}". He has a magazine for ${this.magazine} bullets and ${this.bullets} bullets.`;
}

// выстрел
shot(): string {
if (this.bullets > 0) {
this.shotCount += 1;
this.bullets -= 1;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

создайте get для protected поля bullets

return `The gun ${this.model} fired ${this.shotCount} times`;
} else {
return 'You are out of ammo. Recharge';
}
}

// перезарядка
recharge(): string {
this.bullets = this.magazine;
return 'The magazine is being recharged';
}

// проверка магазина
set magazine(magazine: number) {
this.aMagazine = magazine >= 0 && magazine < 21 ? magazine : this.aMagazine ?? 20;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

если указано неверное число патрон - бросайте exception

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

trow new Exception(wrong amount of bullets)

}
get magazine() {
return this.aMagazine;
}
}
18 changes: 4 additions & 14 deletions rpgsaga/saga/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,6 @@
import { Phone } from './phone';
import { Gun } from './gun';

const first = new Phone('+7900-000 000 (123)', 1990, 'Телефон 1');
first.year = 1998;
const gun: Gun = new Gun('p-250', 21, 5);

first.year = -1998;
first.call('12345');
first.endCall();

const second = new Phone('+799900000', -5);
// second.name = 'Телефон 2';
console.log(second.year);
second.call('12345');
second.endCall();

console.log(first, second, Phone.phoneCount);
console.log(gun);
console.log(gun.shot());
2 changes: 1 addition & 1 deletion rpgsaga/saga/src/phone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@ export class Phone {
get year(): number {
return this.aYear;
}
}
}
Loading
Loading