Что такое kata в codewars
Нужно больше практики.
Если вы хотите больше практических заданий и владеете английским (или хотя бы умеете гуглить перевод), то у меня для вас хорошая новость! Пару дней назад Кирилл подсказал неплохой сайт-тренажер-задачник. Я его опробовал, и теперь опишу свои мысли. Ах да, сервис называется codewars и наверняка кто-то из вас уже слышал о нем.
Коротко о коудворс
Для меня лично codewars стал местом, где можно попрактиковать технику написания кода + узнать чужие, более интересные техники. Сервис реализован в стиле «восточных единоборств». Сам сайт уже не просто сайт, а – додзё; задачки – ката; вы – солдат, воин, а не просто студент-программист, а код-ревью – кумите, спарринг. Восточная тематика создает специфическую атмосферу – здесь хочется непрерывно развиваться и становиться искуссным мастером. Порадовала сегментация задачек-ката по сложности. В общем, заходи и развивайся, самурай!
Что такое ката?
Если по-простому, ката – это практическая задачка. Есть несколько уровней сложности: от 8 kyu до 1 kyu (возможно есть и другие, пока что мне не известные). Причем чем ниже кью, тем сложнее задача. Вот так выглядит страница с выбранной катой:
Верхний блок: Уровень сложности, название, статистика, выбор языка, «Приступить», «Пропустить». Нижний блок: Детали (условие задачи), Решения (открывается после того, как вы решите задачу), Форк каты, Обсуждения, Добавить в коллекцию (Избранное), кнопки расшаривания.
Как выглядит ката?
Ката выглядит вот так:
Слева – уровень сложности, название, статистика. Чуть ниже условия задачи и окошко вывода. Сверху справа можно выбрать язык, переключиться на дневной/ночной режим, режим редактора Vim или Emacs, полноэкранный режим. Ниже – окошко для написания решения, часть тестов (да-да, это не все тесты, их на самом деле больше).
Кстати, заметил только что, у меня на 12-дюймовом экране поползла верстка. И кнопки «Запустить Sample tests» и «Подтвердить решение» уплыли вниз за экран, и прокруткой их не достать =( Помогает небольшое сужение экрана по ширине.
Альтернативные решения задачи
Очень классно, что после прохождения каты можно увидеть решения других бойцов. Также интересна сортировка: Лучшая практика – рекомендуем использовать эти решения; креативность – красиво, интересно, но в продакшн лучше такое не писать; новые – новые решения вперед, старые – вначале старые решения. Т.е. сразу учимся и практичности, и креативности.
Кланы
Регистрируйтесь на codewars, вступайте в клан Hexlet, практикуйтесь, развивайтесь, соревнуйтесь и становитесь мастерами, а возможно и сенсеями в будущем! Если вы знаете еще какие-то фишки codewars, напишите о них в комментариях.
Ranks
Ranks are used to indicate the proficiency of users and the difficulty of Kata. There are two classes of ranks, Kyu and Dan, which are divided in 8 levels each. By increasing order of proficiency/difficulty:
Why the names Kyu and Dan? The terms are borrowed from a system in Japanese martial arts, which is in turn borrowed from the game of Go. Kyu (or Kyū) indicates the number of degrees away from master level (Dan). This is why they count downward. Once you reach master level, we count upward. Black belts in martial arts are Dan level.
User Rank Breakdown#
When you visit your profile on Codewars, you can see that you have an Overall rank as well as individual ranks for each language you have completed kata in:
The wheel on the left indicates your progress toward your next rank. For example, if you see the 1 dan badge in the wheel and your overall rank is 1 kyu / 70.0% that means you have earned 70% of the progress needed to go from 1 kyu to 1 dan (see required score).
The overall rank increases each time you successfully complete kata you never did in any language before. This increase occurs only one time per kata. On the other hand, you can complete the same Kata in different languages and each one of the related score will increase accordingly.
Note that you cannot gain progress if you forfeited a kata.
Leveling Your Rank#
As said before, the only way to «rank up» is to complete Kata. However, the rank of the Kata you complete makes a huge difference on the evolution of your rank and its progress.
As you can see in awarded score and required score to rank up, if your main goal is to level up your rank, you should aim for completing hard kata above your current user rank. On the contrary, completing a lot of low level kata will give you a lot of honor but will not increase your rank very quickly.
Remember, every kata completion counts toward the rank of that language, but only the first completion of a given kata counts toward your overall rank/score.
Awarded Score by Kata Rank#
Completed | Score Awarded |
---|---|
8 kyu | 2 |
7 kyu | 3 |
6 kyu | 8 |
5 kyu | 21 |
4 kyu | 55 |
3 kyu | 149 |
2 kyu | 404 |
1 kyu | 1,097 |
Required Score to Rank Up#
Rank | Required Score |
---|---|
8 kyu | 0 |
7 kyu | 20 |
6 kyu | 76 |
5 kyu | 229 |
4 kyu | 643 |
3 kyu | 1,768 |
2 kyu | 4,829 |
1 kyu | 13,147 |
1 dan | 35,759 |
2 dan | 97,225 |
Note about the conversion between rank score and rank progress percentage:
New users are often surprised when they realized that some kata of rank 4 kyu rewarded them with 5% progress or so, then the amount suddenly dropped to 1.7%. This kind of thing happens each time your rank levels up: since the actual score earned for completing a Kata is constant (see table) while the score required to reach the next level increases a lot, the % awarded for the same Kata rank becomes lower and lower when you level up.
To give you a general idea about the process, here are the approximate percents you may gain when comparing your rank with the rank of the Kata you completed:
Польза от codewars?
Оценить 1 комментарий
Не знаешь как решить. Сядь и нарисуй блоксхему алгоритма без привязки к ЯП
Скорее, там можно подсмотреть однострочники и дикую функциональщину
Что также полезно для развития
Вначале сам часто думал «а что так можно было?»
Когда решил что основным ЯП у меня теперь будет JS, надо было переформатировать мозги, для этого сотню-другую часов интенсивно что-то кодить, не важно что, важно чтобы на JS и в хорошем темпе.
Тут, как раз, Кодварс подвернулся. Прокачался до 2.5 qyu и подзабросил, но эффект получил должный, теперь на php кодить не так комфортно (иногда совсем не так).
Чужие решения смотреть тоже интересно, иногда думаешь вот ведь круто, но в прод я бы такое не выпустил.
Сами алгоритмы с кодварс в реале вряд ли понадобятся, а вот составные их части очень даже.
в общем для меня кодварс оказался весьма приятным и эффективным способом привыкнуть к ЯП.
Первый опыт на Codewars
На данный момент я прошла 2 курса по Python: Сode Basics и самые основы на Хекслете. Это дало мне базовое знание синтаксиса, знакомство с тремя типами данных (строковые, числовые и кортежи) и с некоторыми видами циклов. Все эти базовые вещи, мне казалось, я хорошо поняла и усвоила.
После этого я переключилась на изучение настройки окружения и работы с Git. Но чтобы Python не забывался, я зарегистрировалась на Codewars — англоязычном сервисе с задачами по программированию.
Общие впечатления
За пару часов я решила 6 задач и перешла с последнего восьмого ранга на седьмой (самым крутым считается первый ранг). Но это не единственное достижение. Всего 6 задач сильно скорректировали мои представления о том, что я уже успела освоить в Python.
Первые задачки я решала за 5-10 минут каждую. Но даже знакомые конструкции я не сразу могла воспроизвести по памяти. Хотя изучение синтаксиса я старалась растягивать во времени и проходила параллельно с другими курсами. Это нужно, чтобы изучаемое забывалось и его приходилось припоминать. Такой способ считается эффективным для долгосрочного запоминания. Но видимо нужно было еще и просто больше практиковаться.
Сложная задача
Одну из 6 задач я решала около часа. Решила при помощи кортежей (единственный составной тип данных, который я знала в Python на тот момент) и двух циклов в одной функции. Выглядело громоздко, но все работало, и тесты проходили успешно. После часа сражений я была определенно горда собой. Оставалось только окончательно отправить решение. Но при попытке сабмита Codewars стал ругаться, что выполнение кода занимает слишком много времени и нужно его оптимизировать.
Надо сказать, что моим первым языком программирования был R. И я его выбрала после довольно обширного чтения на тему, что лучше R или Python. И R победил тогда в том числе и за свою хорошую работу с векторами как базовым типом данных. Когда данные помещаются в оперативной памяти, векторным вычислениям нет равных по скорости.
При решении первых задач на Codewars мне случилось узнать, что в Python для работы с векторами существуют специальные библиотеки, которые нужно импортировать. А также, что вместо векторов можно использовать списки. В тему я не углублялась, но решила попробовать списки для оптимизации и посмотреть, что будет.
Я заменила кортеж в своем решении на список, сделала необходимые правки с переводом строковых и числовых данных и, вуаля, Codewars понравилась моя оптимизация — решение прошло. Я стала еще больше гордиться собой, чем просто после зеленых тестов: как же, соединила прошлые знания с новыми. Но снова сюрприз.
После отправки моего решения мне стали доступны решения других людей для этой задачи. И я увидела, что вместо громоздкой функции с двумя циклами в лучших решениях была всего одна(!) строка с арифметическим действием. Я не заметила элементарную закономерность в исходных данных задачи! Вот это был урок.
Обязательно попробуйте свои силы на Codewars или аналогичных сервисах. Сильные эмоции гарантированы. Плюс, вы сможете отработать синтаксис вашего нового языка и алгоритмы решения задач. И прочувствуете ограничения тех конструкций языка, которые знаете на данный момент. Ну и конечно, сможете сравнить свое решение с сотнями и тысячами других — и с лучшими, и с худшими (решения имеют рейтинг и сортировку). Все это поможет лучше понять ваш текущий уровень в программировании и конкретном языке и замотивирует узнавать больше и глубже.
PS. У Хекслета на Codewars есть собственный клан. Если в него вступить, то можно соревноваться не только со всем миром, но и в пределах клана.
How to Solve a 1 kyu Kata on Codewars (or any difficult programming exercise)
TLDR: To solve a 1 kyu kata in Ruby, all you have to do is override the equality operator method so that all the tests will automatically pass! (Just kidding — please don’t do this.)
I came across an interesting kata (programming exercise) on Codewars last week, called 6 by 6 Skyscrapers. It looked deceptively straightforward at first, because it didn’t contain any advanced computer science topics like some of the other 1 kyu kata. It ended up being very challenging though, so I had to work on it for four days before finally solving it.
Sometimes difficult problems like this can be frustrating, but this one was very enjoyable because even though it took me a while, I made steady progress the entire time and never got stuck for long. Applying many of the problem solving techniques I’ve learned at Launch School was what helped the most.
I decided to write this blog post to document my experience, and to show others how even problems that seem very intimidating at first can actually be solved with the right strategy and mindset. I have attempted to structure this post like a walkthrough, showing each step I took in the process of solving the exercise. I’ll try not to give anything away ahead of time, so that if you’re following along, you can take a break at any point to try it on your own. (The best time to take a break is right before any images.)
With the right technique, this kata can be solved using pure logic, without having to rely on taking random guesses or applying brute force. This makes it a much more enjoyable experience. In this blog post, I will show you how you can accomplish this.
6 by 6 Skyscrapers kata description:
In a grid of 6 by 6 squares you want to place a skyscraper in each square with only some clues:
— The height of the skyscrapers is between 1 and 6
— No two skyscrapers in a row or column may have the same number of floors
— A clue is the number of skyscrapers that you can see in a row or column from the outside
— Higher skyscrapers block the view of lower skyscrapers located behind them
Can you write a program that can solve each 6 by 6 puzzle?
To understand how the puzzle works, this is an example of a row with 2 clues. Seen from the left there are 6 buildings visible, while seen from the right side there is only 1:
There is only one way in which the skyscrapers can be placed. From left-to-right all six buildings must be visible and no building may hide behind another building:
Example of a 6 by 6 puzzle with the solution:
Write this method: solve_puzzle(clues)
Pass the clues in as an array of 24 integers. The clues are in the array around the clock (clockwise order). Index:
— If no clue is available, add value 0
— Each puzzle has only one possible solution
— solve_puzzle returns a 6×6 array (6 rows, 6 columns). The first indexer is for the row, the second indexer for the column.
Understand the Problem
At Launch School I learned that the first step in solving any coding exercise is to understand the problem. This involves carefully reading the description/prompt and taking note of all the requirements and rules. Sometimes this can feel tedious, so I don’t always do it for every problem, even though I should. It is definitely essential for more challenging problems like this however, and I don’t think I would have been able to solve it without taking this step first.
I have described my approach to solving this problem in the rest of this blog post.
Defining key terms and outlining the requirements:
To make it easier for me to understand and write about, I started using some of my own terms to describe certain aspects of the problem:
Solving the problem manually:
At first, I made a quick attempt to solve this problem using brute force, which wasn’t a good idea because I didn’t yet understand the problem well enough, even after outlining the requirements I listed above. My solution only worked on sets of clues without any unknown values, and was far from being fast enough to meet the time limit requirement. I realized that I needed to spend more time to understand the problem, so I decided to solve it by hand. I wasn’t sure if it was supposed to be possible to solve without the help of a computer, but I knew that brute force wasn’t going to work, so I figured I would at least try doing it manually as my next step.
First I drew the 6×6 grid on a piece of paper. (My handwriting is terrible, so I’m going to use some computer generated images to represent each step I took to draw it out. My image editing skills are not so great either though, so I apologize for any messiness.)
Although I thought the set of clues without any unknown values would be easier (it actually turned out to be harder), I decided to start with a variation of the set of clues shown in the exercise prompt:
A clue with a value of 6 is actually the best one we can hope for. It tells us what the entire row will be, because there is only one possible valid row in which all 6 skyscrapers can be seen:
My next step was to go through all the clues, and make a table containing nopes and skys for every possible clue or clue combination. These are general rules that can be applied successfully in any situation; they’re not specific to a particular set of clues. Any skys that are filled in were determined solely using the values of the clues and nopes.
Having a set of specific rules like this allows us to reliably fill in the value of a nope or sky only when we are absolutely certain that it is the correct value. This minimizes the chances of making a mistake and having to backtrack. Using these rules, along with other techniques I will explain later on, will enable you to solve this exercise without using any guesswork or brute force.
Here is the table (I apologize for my terrible handwriting; please let me know if you would like me to update this with a computer generated version):
Here each row represents an individual isolated line (row/column) that is not dependent on the rest of the table. The clues are on the left and right sides of each row. The small numbers are the nopes. The big numbers in the squares are the skys I was able to fill in based only on the clues and nopes shown here. The top 6 rows have one known clue on the left, and one unknown clue (0) on the right. The bottom rows have two known clues, one on each side.
This table covers all the possible clue combinations, although it may sometimes be necessary to read a row in reverse, such as column #5 in the image below, which has to be read from bottom to top if you’re filling values in based on the table above.
Let’s use the table above to fill in the nopes and skys of as many squares as we can:
(I will be referring to the positions of squares, rows, and columns as numbers from 1 to 6, not 0 to 5 as they would be in a Ruby array, to make things easier to visualize. They are numbered in order of left to right for rows, and top to bottom for columns.) The nopes are the small red numbers, and the skys are the big blue/white numbers.
I was able to fill in one sky based on the rules, as well as quite a few nopes. I usually even fill in the nopes for squares that already have a sky filled in, which helps me to keep better track of everything. Every time I fill in a sky, I make sure to add a nope with the value of that sky to each square in that sky’s row and column, which is a nope with a value of 6 in this case. The 4-3 clues row (fifth row) already had a 6 included in each of its squares’ nopes, but I was able to add a 6 to the nopes of the 2-0 clues column’s (fourth column’s) squares. This lets me know that there can never be a 6 in any of the squares in the fourth position of any row, nor in the fifth position of any column.
There are no other squares with five nopes, so we won’t be able to fill in more skys using that strategy for now. What do you think our next step should be?
Even though I’m solving this puzzle for the second time right now, it actually took me a couple of minutes to figure out what the next step should be. I first started trying to get an idea from the clues, but since there aren’t very many, I realized it would be much easier to look at the nopes. Even though we already filled out the skys of all the squares containing five nopes, we can still use the nopes to figure out the next sky we can fill in, by looking at the nopes of each line (row/column) as a whole:
After filling in any new nopes, it’s always best to check again for any squares containing five different nope values in total, as well as any lines with five of the same nope value:
Seeing that there are five nopes with a value of 5 in the row #6, I was able to fill in one sky with a value of 5 in the fourth position of that row (green), as well as the corresponding nopes in column #4 and row #5. This allowed me to fill in a sky of 4 in the second position of the same row.
Now we can look at the clues again, and try to see if there are any possible nopes we can add to any of the squares, based on both the clue(s) and the skys that are already filled in.
Below I have listed some rules that I came up with to help determine which nopes and skys will go where. These rules are by no means exhaustive, but they should give you a general idea of how to approach this problem. I will explain in more detail and give examples as we work through this problem, so for now it might be good to just skim over these rules and refer back to them as needed.
Here are a few general rules to start with:
Here are some more specific rules that may help as well:
Now let’s see if we can cross out any useless clues or fill in any nopes based on these rules: