The forum is deprecated and will become read-only.
Join our Discord or use GitHub Discussions.

Solutions Grouping

About

This site will make an attempt to group similar solutions together so that they may be voted on and discussed as a group. If you have any feedback on how this process can be improved, this is the place to talk about it.

Discuss:

  • Please sign in or sign up to leave a comment.
  • blindvigil Avatar

    It seems a strange design decision not to include the run-time in which a solution performed, ideally, corrected for server latency.

    It would make the most sense for the solutions that performed the best on the same data set to be grouped at the top of the list, would it not?

    Given the nature of algorithmic complexity, it is feasible for 10,000 lines of code running an O(n log n) algorithm to run blazingly faster than 10 lines of code written in O(n^2)

    Please consider posting the time in which a solution completes along with the solution itself. Surely this would be enormously popular, and also help people to determine which coding styles actually produce tangible results.

    Code to Joy

  • capcode Avatar

    Hello moderators, can you please delete my THIRD refactored solution (for kata "Upside-Down Numbers - Challenge Edition"), cause i accidentally submitted it and it doesn't nearly contain any changes. I know also that it wont be schown in public solutions, but it takes too much space in my own solutions tab.

    Thank you.

  • Evangelinetdy Avatar

    Hi, I complete this kata(https://www.codewars.com/kata/551dd1f424b7a4cdae0001f0). It showed both in my completed and unfinished kata list. Could it be removed from the unfinished list and stay on the completed one?

  • Sleepycatfuji Avatar

    Is there a way I edit the solution I submitted? It was not clean and I am a little embarrased.

  • Nikita31033 Avatar

    Hi! I have no idea. Help me to solve the recursion.

    We need to draw tree with recurcion. The tree class like:

    
    public class TreeNode {
      string nodeName;
      List children = new ArrayList<>();
      // Other code...
    }
    
    

    Input: (a, b, (c), d) Output:

      a
      |
    -----
    | | |
    b c d
    

    Input: (a, second, (abc, y, (x, 7), uuu, (8, 9, (10, 1)), abcddcdba) Output:

                  a 
                  | 
       ----------------------
       |          |         |
     second      abc     abcddcba 
                  | 
             ---------- 
             |  |  |  | 
             y  x uuu 8 
                   |  | 
                   - --- 
                   | | | 
                   7 9 10 
                       | 
                       - 
                       | 
                       1
    
  • bocacha Avatar

    Hey there! Can any1 give me a hand on this code?

    function highAndLow(numbers){ // ...

    numberList=numbers.split(' '); var result=""; var max=numberList[0]; var min=numberList[0];

    for(var i=0; i < numberList.length; i++){

      if(numberList[i]> max){
        max=numberList[i];
      }
      
      if(numberList[i]< min){
        min=numberList[i];
      }
      
    

    } result=max + " " + min; return result }

  • Gabr13dev Avatar

    I'm trying to solve this problem https://www.codewars.com/kata/563b662a59afc2b5120000c6/train/php in php and I arrived at a solution that passes the tests but at the time of sending it as an answer it does not accept:

    function nbYear($p0, $percent, $aug, $p) { $year = 0; do{ $upYear = ($p0 * ($percent/100)) + $aug; $p0 = $p0 + $upYear; $year++; } while($p0 <= $p); return $year; }

    I do not understand

  • OneEyedMwark Avatar

    umm.idk where im at and what is going on and what does KATA mean.someone help???

  • Medraut Avatar

    I hope that this is the correct place to ask. If not, I am sorry for the hassle. On the 8 Kyu kata "Sum of positive," you are to get an array of numbers and return the sum of all of the positive ones. I tried this:

    function positiveSum(arr) { return arr.filter(e => e > 0).reduce((a, b) => a + b); }

    It worked using node in VS Code, but in Codewars, I received a TypeError.

    Could someone please tell me what I have done wrong?

  • MMSS98 Avatar

    Hi, I have this code, and I have a problem in the output

    print("This program finds the intersection of two sets")
    
    sequenceOne = input("Please enter the space-separated elements of the first set: ")
    sequenceTwo = input("Please enter the space-separated elements of the second set: ")
    
    sequenceOne = sequenceOne.split()
    sequenceTwo = sequenceTwo.split()
    listOfIntersection = []
    
    for i in sequenceOne:
        for j in sequenceTwo:
            if (i==j):
                sequenceOne.remove(j)
                sequenceTwo.remove(i)
                listOfIntersection.append(i)
                if not sequenceOne or sequenceTwo:
                    pass
    

    it should print string or number intersection between the two sequences.

    sequence one : 12 k e 34 1.5 12 hi 12 0.2
    sequence two:  1.5 hi 12 0.1 54 12 hi hi hi
    
    intersection: {12, 1.5, 12, hi} #only one [hi] since it occurs once in sequence one
    

    but in my code it skips [hi], and i don't know why and only printing:

    {12,1.5,12}
    
  • Mohrezakhorasany Avatar

    How can i add my own class(Java) to the Kata?

  • SFin12 Avatar

    I'm currently trying to solf the TVRemote(wrap). I already solved it in python but i've been trying to solve it in JS. When I call the main function with the exact same test words that fail, it logs the correct answer but the test says it is logging a different answer. I'm still very new to JS and can't figure out what else I can do since all of my logs come back correct. Any help is appreciated. My code is below. I called the first function with the first test that fails so you can see difference in what is logged.

    // each string in the array is a row and each character in each string is a column.
    const rows = ['abcde123','fghij456','klmno789',
                 'pqrst.@0','uvwxyz_/','*#&&&&&&'];
    
    
    let current = [0,0];
    let new_l = [];
    
    // function that finds column and row of a given letter or character.
    const find_letter = letter => {
      let count = 0;
      for (i=0; i<rows.length; i++){
        
        // if the character isn't in the row, move to the next row.
        const column = rows[i].indexOf(letter);
          if(column === -1){
            continue;
            
            // if it is found, update row and column to the new letter.
          } else {
            new_l.push(i);
            new_l.push(column);
            
            //gives the distance to between current position and new character.
            let row = Math.abs(current[0]-new_l[0]);
            let col = Math.abs(current[1]-new_l[1]);
            
            // used to represent the wrapp arround ability
            if(row > 3) {
              row = 6-row;
            } if(col > 4) {
              col = 8-col;
            }
            
            // update count and new current position. The +1 is the "click" of the button.
            count += row + col +1;
            current = new_l;
            new_l = [];
            break;
          }
          } 
      
            // returns how many clicks it took from the previous character to press the current character.
            return count ;
        };
    
    
    const tvRemote = function(words) {
      // current total count that will be returned
      let count = 0;
      
      // represents current state of keyboard. False = lowercase, True = upercase.
      let shift = false;
      
      //check each character in word/words.
      [...words].forEach(l => {
        
        // if there is a space, the button to press is the space (#) key.
        if(l == " "){
          l = "#";
          
          // find_letter finds the row and column for that character and updates current position to that key.
          count += find_letter(l);
          
          // if the letter is uppercase, check how many clicks it takes to first press the shift key then the main key.
        } else if(l == l.toUpperCase()) {
            if(!shift) {
              count += find_letter('*');
              shift = true;
              count += find_letter(l.toLowerCase());
            // if the letters are alread capitalized, continue finding the character.
          } else {
            count += find_letter(l.toLowerCase());
          }
          
          // if the keyboard is uppercase and the character we are looing to press is letter, press shift key then find the letter.
        } else if(shift && l == l.match(/[a-z]/i)){
            count += find_letter('*');
            shift = false;
            count += find_letter(l);
          
          // find the letter if keypad is lowercase.
        } else if(!shift && l == l.match(/[a-z]/i)){
          count += find_letter(l);
          
          // if the character isn't a letter or a space, find how many clicks to press the character.
        } else {
          count += find_letter(l);
        }
      }); 
          return count;
    };
    
    console.log(tvRemote("your"))
    
  • ShaneDavison Avatar

    Hello internet friends,

    Any help with the following Python problem would be greatly apreciated. In my own IDE this seems to return the correct result but fails on the test. Thank you.

    This is the problem:

    Digital root is the recursive sum of all the digits in a number.

    Given n, take the sum of the digits of n. If that value has more than one digit, continue reducing in this way until a single-digit number is produced. The input will be a non-negative integer.

    Examples 16 --> 1 + 6 = 7 942 --> 9 + 4 + 2 = 15 --> 1 + 5 = 6 132189 --> 1 + 3 + 2 + 1 + 8 + 9 = 24 --> 2 + 4 = 6 493193 --> 4 + 9 + 3 + 1 + 9 + 3 = 29 --> 2 + 9 = 11 --> 1 + 1 = 2

    and here is my soloution :

    def digital_root(n):

    number = n
    sum_of_digits = 0
    for digit in str(number):
        sum_of_digits += int(digit)
    
    if sum_of_digits > 9:
        digital_root(sum_of_digits)
    if sum_of_digits < 9:
        return(sum_of_digits)
    
  • Blinky_32 Avatar

    Can somebody help me to solve this problem in Python or give a little hint, PLEASE! I have an idea how to do it but just not working... Thank you!

    In telecommunications we use information coding to detect and prevent errors while sending data.

    A parity bit is a bit added to a string of binary code that indicates whether the number of 1-bits in the string is even or odd. Parity bits are used as the simplest form of error detecting code, and can detect a 1 bit error.

    In this case we are using even parity: the parity bit is set to 0 if the number of 1-bits is even, and is set to 1 if odd.

    We are using them for the transfer of ASCII characters in binary (7-bit strings): the parity is added to the end of the 7-bit string, forming the 8th bit.

    You are to test for 1-bit errors and return a new string consisting of all of the correct ASCII characters in 7 bit format (removing the parity bit), or "error" in place of ASCII characters in which errors were detected.

    Examples

    Correct 7 bit string with an even parity bit as the 8th bit:

    "01011001" <-- The "1" on the right is the parity bit.

    In this example, there are three 1-bits. Three is an odd number, and the parity bit is set to 1. No errors are detected, so return "0101100" (7 bits).

    Example of a string of ASCII characters:

    "01011001 01101110 01100000 01010110 10001111 01100011"

    This should return:

    "0101100 error 0110000 0101011 error 0110001"

  • tanmay-sketch Avatar

    def digital_root(n):

    sum = 0
    temp = n #temparory variable to store n
    while temp > 9:
        for i in str(temp): #convert the integer to a string to iterate through
            sum += int(i)
        temp = sum
        #change the sum back to 0 for further iterations
        sum = 0
    
    return temp
    

    This was my solution to the digital root problem, this is not the most efficient solution. Can anyone post more efficient solutions to this problem?

  • tanmay-sketch Avatar

    def create_phone_number(n):

    if len(n) == 10:
        phone_number = ''.join(str(i) for i in n)
        newPhone = "(" + phone_number[0:3] + ")" + ' ' + phone_number[3:6] + '-' + phone_number[6:12]
    return newPhone
    

    This was a solution to the phone number problem, but I believe there are so many more efficient solutions, help me improvise this solution.

  • youbou12 Avatar

    Hello , Please some one help me to solve this problem :

    Les équipes d'acrobates font partie de la culture marocaine, elles jouaient dans les marchés traditionnels pour distraire les gens. Une des scènes les plus incroyables est quand ils se mettent debout les uns au dessus des autres pour former une sorte de pyramide.

    Une pyramide de hauteur L est formée de la manière suivante : Une personne au sommet se tient debout sur les épaules d'une autre personne, qui elle tient debout sur les épaules de deux autres personnes, puis 3 et ainsi de suite.

    On souhaite savoir quel est le nombre d'acrobates qu'il faut pour former une pyramide de hauteur L.

    Input : 2 6 3

    Output: 16 4

  • zsolt-szilagyi Avatar

    On topic:

    • Ignore all whitespaces
    • Ignore variable names, if feasable (e.g. in PHP ignore all that comes after the dollar sign)
    • Here is a big one: Upon completion, find the one that's closest to the new solution (e.g. smallest merge diff), and ASK the user if he want's his grouped with that one.
  • ankitlt Avatar

    Can anyone help me with the code of rotateArray(data,n) some of test cases seems to fail. Here is my code in Java:

    // Removed
    

    Thank you

  • krish77290 Avatar

    can anyone did the persistence program

  • TheCoder99 Avatar

    int findOdd(const std::vector<int>& numbers) {

    int arrayLength = numbers.size(); 
    for(int i = 0; i < (arrayLength - 1); i++) {
        int counter = 0;
        for(int j = 0; j <= arrayLength; j++) {
            if (numbers[i] == numbers[j]) {
                counter++;
            }
        }
        if(counter % 2) {
            return numbers[i];
        }
    }
    return numbers[arrayLength - 1];
    

    }

    When I test this code in Qt with sample arrays it returns the correct value, but when I execute it here it doesn't. Any ideas why.

  • m1ster-panda Avatar

    I am newbie in Python. can someone help me with the correct code of this?

    "Find films whose actor_3_name is Omar Sy and actor_1_name is the person from Armageddon."

    The dataset is found here: https://www.kaggle.com/carolzhangdc/imdb-5000-movie-dataset

    #my code:

    import pandas as pd data = pd.read_csv("movie_metadata.csv")

    data[data.movie_title.str.contains('Armageddon')] & data[data.actor_3_name.str.contains ('Omar Sy')]

    ...but I got an error.

  • mouhaka Avatar

    Please help me !!

    #include <stdbool.h> #include <stdio.h> #include <stdlib.h>

    bool xo (const char* str) {

    int count = 0;
    for (int i = 0; i < strlen(str); i++){
      if(str[i] == "x" || str[i] == "X"){
        count++;
      }
    }
    

    return count;

    int countY = 0;
      for (int j = 0; j < strlen(str); j++;){
      if(str[j] == "y" || str[j] == "Y" ){
        countY++;
        }
    }
    

    return countY;

    if (count == countY){ return true; } else {return false;} }

  • MalikDeveloper2077 Avatar

    Hi, guys! Is problem-solving improving your brain or thinking? What do you think?

  • mentayk Avatar

    Hello everyone. I am new to all this. Trying to learn JS. and i am stuck with a task: I need to find return an array of numbers [1, 2, 3, ..., n]. So my function fillArray(5) suppose to return [1, 2, 3, 4, 5]. Can someone help me please

  • Egor84 Avatar

    Hi! create function weekdays(date1 in date, date2 in date) return integer language plpgsql as $$ begin .... Why ERROR? function weekdays(date, date) does not exist ! Help me please!

  • user6680914 Avatar

    Valid Braces: I passed the tests but not the full test suite because of this: Failed asserting that false matches expected true. What the heck does that mean? I know my solution works but maybe I didn't provide something else that I'm not aware was needed. Please advise. I'm new here. Thanks.

  • dimarique Avatar

    Hello! I have posted 2 solutions by mistake. Now I can't find a way to remove one of them. Any help? Thank You!

  • ismodes Avatar

    Hello! I solved the 'Sums of Parts' question, but I cannot find my solution when filtering by 'My Solutions.' When I go to the 'Solutions' section of my profile, I see that solution, but unlike my other solutions, there is no 'Discuss' option to the right of the Refactor option. Additionally, when I go to the 'Stats' section of my profile it says that I only have 10 Total Completed Kata while in my solutions it says that I have 11. I do not understand why my last solution (Sums of Parts) has been accepted in some parts of the website and not in others. I would appreciate any help, thank you!

  • Nodbringer Avatar

    Hi, I have an issue with "Sum of Digits / Digital Root" question, I believe my code is correct, but it won't let me through (says "None should equal 6"), my prints are showing I'm reaching exactly that, would appriciate your input :) def digital_root(n): str_num_arr = split_num(str(n)) print(str_num_arr) sum = 0 for num in str_num_arr: sum = sum + int(num) print(f"sum is now {sum}") if len(str(sum)) == 1: print(f"len is now 1 for {sum}") return sum else: print(f"sum len is different than 1, sum is {sum}") digital_root(sum)

    def split_num(num): return [digit for digit in num]

  • mshein7 Avatar

    Convert string to camel case

    def to_camel_case(str)

    arr = str.gsub(/[_-]/," ").split(" ") final =[] arr.each_with_index do |char,i| if i==0
    final << char else final << char.capitalize! end end return final.join("") end p to_camel_case("the-stealth-warrior") p to_camel_case("The_stealth_warrior") Hi , in repl and vs code , my code produce the result but still fail in attempt at code wars , is it bug or something ,any suggestion from senior , i just started at codewars.Thanks.

  • OFG Avatar

    Hey I use the ClassicModels database. ClassicModels is a fictitious company I want to make basket of goods analysis: A common retail analytics task is to analyze each basket or order to learn what products are often purchased together. Report the names of products that appear in the same order ten or more times. I have no idea for sql qeury. Someone can help me?

  • Sora_ Avatar

    How to join a clan?:(

  • COder_ Avatar

    How to create a clan???

  • Globe Avatar

    [Honest Question here]

    Why are all the top kata solutions so 'hackery'? Like good job for getting it in one line, but who would ever want to read or debugg THAT code??

    Is hackery code a lower kyu thing? Is it a codewars thing? Or, and I really hope this isn't true, but is it maybe an industry-wide phenomenon?

    I'm a n00b, so if the above opinion is seriously wrong for some reason, by all means, please correct me. It's just that so far, every single resource I've used to study has hammered on the importance of readability, following the style guides, using proper, easy-to-understand names for things, etc.

    And as a learner especially, it'd be great if I could wrap my head around the top answers without having the decrypt the freaking variable names first.

  • Mikeswann21 Avatar

    Can anyone help me understand why I'm still seeing quotation marks around the entire sentence? If I remove the quotations from the last line it results in a syntax error. Thanks in advance!

    #Defining "quotable" as a function. def quotable(name, quote): return '{} said: "{}"'.format(name, quote)

    quotable('Michael', 'Practice makes perfect')

  • dr4w Avatar

    Hi!Two of my kata's have this problem "Execution Timed Out".I'm starting in programming and I want to get better on it. Guys , does anyone have any tip or place that can I learn about this? Pleeeeeeeeeeeeease somebody help me!! I start looking solutions , and one of my mistakes is using two "for" interation in very very big number's .So, any tip is welcome!

  • Orcinus orca Avatar

    I need faster algorithm. Problem - to leave only the last occurrences of each element in the sequence; the remaining elements must be removed from the sequence. Thank you. Given: 1 2 3 3 2 1 4 1 2 0 Answer:3 4 1 2 0

  • jamr Avatar

    i am very new to Codewars. Hope this question is appropriate for the forum. I ran the Attempt test cases for The Hunger Games – Foxes and Chickens using Java.

    For Random Test 1 Here is my result before/after (farm/farm2)
    followed by the Before/After from test case. //farm = C....C.C[..CCC..C.....C..CCCC.CC.CC....C.CCF..F.CCC..CCC.C.F...CC.C.....F..C.CCF..C....C..C..CCC.] //farm2= ........[..................................F..F............F............F......F.................] //Before:C....C.C[..CCC..C.....C..CCCC.CC.CC....C.CCF..F.CCC..CCC.C.F...CC.C.....F..C.CCF..C....C..C..CCC.] //After: C....C.C[..................................F..F............F............F......F.................] the After includes the "C"'s outside the brackets which to my understanding should be "."'s correct?

    For onlyChickens test case here is my before/after log followed by the test case results. farm =.C..[C.]..C....[C]..[C..] farm2=....[C.].......[C]..[C..] expected:<.[C..[C.]..C]....[C]..[C..]> but was:<.[...[C.]...]....[C]..[C..]> my result seems ok and the test case result has unmatched [ ]'s

    appreciate the help to clarify. Thanks

  • user7854114 Avatar

    Hello when I leave a problem I haven't finished is it gone forever or will I eventually recieve it again?

  • koala1st Avatar

    I have problems with the traning in python. Several times it says to me I m wrong when my code works at home and log show that I obtain the right results. For example for the "Who likes it" : Test Results: Basic tests Log 'no one likes this' None should equal 'no one likes this' Log 'Peter likes this' None should equal 'Peter likes this' Log 'Jacob and Alex like this' None should equal 'Jacob and Alex like this' Log 'Max, John and Mark like this' None should equal 'Max, John and Mark like this' Log 'Alex, Jacob and 2 others like this' None should equal 'Alex, Jacob and 2 others like this' Random tests Testing for Sylvie, Daley Wong, Quincy Rosenkreutz, Sylia Stingray, Nene Romanova, Brian J. Mason, Linna Yamazaki, Largo Log 'Sylvie, Daley Wong and 6 others like this' It should work for random inputs too: None should equal 'Sylvie, Daley Wong and 6 others like this'

    etc...

    Someone can explain to me where i do a mistake?

    thank in advance

  • fResult Avatar

    How to press Esc to normal mode in codewars ?

  • WestwardLand968 Avatar

    The speed of the solution should be added, because some clever solutions may not be quick, they are just using very obscure programming concepts - efficiency is very important with code.

    There should be another solution upvote category - readability. Some solutions are very hard to read. When writing code it is important to make sure that humans can easily understand what you are writing.

  • Nand Lal Avatar

    Hello, anyone can help me solve this task

    Google has offices in several locations. Currently we have an interviewee that is in the Google office on locationA and he has passed his first interview, so now for the second interview he needs to get to locationB. Find the fastest route to get there and return the number of steps. Input Method signature: int fastestRoute(int[] from, int[] to, int locationA, int locationB) • from - an array of integers. • to - an array of integers . The i-th pair (from[i], to[i]) means that there is a path from location from[i] to location to[i]. Constraints: • from and to will have between 0 and 50 integers, inclusive. • each integer in from and to will be between 0 and 50, inclusive. • Expected execution time is below 10 seconds. Output An integer giving the number to steps to get from location A to location B. If it is not possible return -1. Examples • fastestRoute([0, 0, 1], [1, 2, 3], 2, 3) returns 3 since to get from location 2 to location 3 the path is 2 -> 0 -> 1 -> 3, which is 3 steps. • fastestRoute([0, 1], [2, 3], 0, 1) returns -1 since it is there is no path from location 0 to location 1.

  • jorgemacias Avatar

    Hello, I am trying to solve the Kata is prime

    I keep getting this error "Your function shouldn't just consider any huge number as prime"

    My solution is:

    function is_prime(int $n): bool { $num=$n/6; $result = $n > 1 && (($n > 1 && $n <= 3) || ($num < round($num) ? (6 * (round($num)) - 1 == $n ? true : false) : (6 * (round($num)) + 1 == $n ? true : false))); return $result; }

    Please tell me what am i doing wrong

  • ForceQWE Avatar

    //

    Expected: "a\n b\nc" But Was: "a \n b \nc " So, i tried to delete this space by all ways i know, and nothing! Rest of tests are completed. How can i delete this spaces before i return a string?

  • Snim Avatar

    Hi, a question regarding the test cases: After you pass the sample tests, you see the tests results and the failed ones appear like: '4' should return '3', but I cannot see what the test case is, and when I click into the discussion of the kata I see comments like "I cannot pass the number 14 in test cases". And I'm like... how do they see that? Is it possible to know?

  • rnio Avatar

    Hard Sudoku Solver:

    Run into issue, where the kata says the offered sudoku puzzle is NOT solvable ... my code solves it ... and thus I can NOT pass?!

    I verified the puzzle and my solutions and can NOT find why it is rejected ... it only happens in 1 - 3 cases (RANDOM) per ATTEMPT.

    Any clues, suggestions?

    e.g:

    PUZZLE: [[3, 4, 7, 9, 0, 0, 0, 8, 0], [0, 1, 0, 8, 0, 0, 0, 5, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 5, 0, 0, 0, 0, 8], [0, 0, 0, 4, 0, 8, 0, 0, 0], [6, 0, 0, 0, 0, 3, 0, 0, 0], [0, 7, 0, 0, 0, 0, 0, 0, 0], [0, 8, 0, 0, 0, 5, 0, 3, 0], [0, 5, 0, 0, 0, 4, 2, 7, 9]] Solution: [[3, 4, 7, 9, 5, 1, 6, 8, 2], [2, 1, 9, 8, 3, 6, 7, 5, 4], [8, 6, 5, 2, 4, 7, 9, 1, 3], [7, 3, 4, 5, 6, 2, 1, 9, 8], [5, 9, 1, 4, 7, 8, 3, 2, 6], [6, 2, 8, 1, 9, 3, 5, 4, 7], [4, 7, 2, 3, 1, 9, 8, 6, 5], [9, 8, 6, 7, 2, 5, 4, 3, 1], [1, 5, 3, 6, 8, 4, 2, 7, 9]]

  • Brakusu Avatar

    Hi, I'm new here and do not know where do I write the solution for the kata. I see description of the task, but do not see any window where to enter my code. Anyone to help?

  • TraianMerfu Avatar

    Hello, I am trying to solve the Kata Sum String as Numbers. The problem I get is that the code I wrote as a solution works in Visual Studio but for some reason on the platform I get an error on the same code

    Can anyone please advise what could be the reason.Thanks!

  • uniqueyung91 Avatar

    I am trying to solve this Kata: Matrices II: Serious mathematics

    I tried to solve it in my IDE (intelliJ) and I tried to write some test cases in the main method and the code could pass all of them. So, I have thought the code is working, but when I have uploaded the code and submitted it it could not pass the tests. I am still a beginner in terms of programming. I hope someone can help me out and advices and tips are really appreciated since I am willing to learn.

    public class Matrix {

    // display method
    // method to print matrix
    // in vielen kleinen iterationen arbeiten
    // mini tests in main schreiben --> gute Vorgehensweise
    // tests schreiben & laufen lassen
    // schlägt test fehl
    // test-driven development
    private double[][] elements;
    
    // hier auch invalides array uebergeben werden
    public Matrix(double[][] elements) {
        // TODO: Write constructor
        // leeres array
        // array mit variablen spaltenzahl in jeder zeile
        if (elements.length == 0) {
            throw new IllegalArgumentException("elements must not be empty");
        }
        for (int i = 0; i < elements.length; i++) {
            if (elements[i].length == 0) {
                throw new IllegalArgumentException("elements must not be empty");
            }
        }
    
    
        int tmpLength = elements[0].length;
        for (int i = 0; i < elements.length; i++) {
            if (tmpLength != elements[i].length) {
                throw new IllegalArgumentException("Sub arrays must have same size");
            }
        }
    
    
        this.elements = elements;
    
    }
    
    // elements ist ein einfaches array
    public Matrix(int rows, int cols, double... elements) {
        // TODO: Write constructor
    
        if(elements.length == 0){
            throw new IllegalArgumentException("Elements should not be empty!");
        }
    
        if(elements.length != (rows*cols)){
            throw new IllegalArgumentException("Subarray should have same size!");
        }
    
        this.elements = new double[rows][cols];
        int counter = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (counter == elements.length)
                    break;
                this.elements[i][j] = elements[counter];
                counter++;
            }
        }
    
    
    }
    
    public double[][] toArray() {
        return this.elements;
    }
    
    public Matrix transpose() {
        // jetziges elements array benutzen
        // neues elements array erstellen --> transponiertes array
        // Konstruktor mit neuen elements --> zurueckgeben
    
        double[][] transposed = new double[elements[0].length][elements.length];
    
        for (int row = 0; row < elements.length; row++) {
            for (int column = 0; column < elements[row].length; column++) {
                double currentVal = elements[row][column];
                transposed[column][row] = currentVal;
            }
        }
    
        return new Matrix(transposed);
    }
    
    public void print() {
        for (int i = 0; i < elements.length; i++) {
            for (int j = 0; j < elements[i].length; j++) {
                System.out.print(elements[i][j] + " ");
            }
            System.out.println();
        }
    
    }
    
    // if matrices have different length --> invalid
    // add two matrices
    // row for row
    // returning new matrix with the sum of both
    public Matrix add(Matrix matrix) {
        double[][] sum = new double[elements.length][elements[0].length];
        if (elements.length != matrix.elements.length) {
            throw new IllegalArgumentException("Matrices have different length");
        }
        for (int i = 0; i < elements.length; i++) {
            for (int j = 0; j < elements[i].length; j++) {
                if (elements[i].length != matrix.elements[i].length) {
                    throw new IllegalArgumentException("Matrices have different length");
                }
            }
        }
    
        for (int i = 0; i < elements.length; i++) {
            for (int j = 0; j < elements[i].length; j++) {
                sum[i][j] = elements[i][j] + matrix.elements[i][j];
            }
        }
    
        return new Matrix(sum);
    }
    
    // scalar multiplication
    // every element of row multiply with number
    public Matrix multiply(double number) {
        double[][] scalarResult = new double[elements.length][elements[0].length];
    
        for (int i = 0; i < elements.length; i++) {
            for (int j = 0; j < elements[i].length; j++) {
                scalarResult[i][j] = (elements[i][j]) * number;
            }
        }
        return new Matrix(scalarResult);
    }
    
    public Matrix multiply(Matrix mulMatrix) {
        double[][] resultMatrix = new double[elements.length][mulMatrix.elements[0].length];
        // von elem gehe ich komplette Reihe durch
        // mulMatrix gehe komplette Spalte
    
        if (elements[0].length != mulMatrix.elements.length) {
            throw new IllegalArgumentException("Multiplication not possible");
        }
        for (int i = 0; i < elements.length; i++) {
            double sum = 0;
            int iter = 0;
            while (iter < mulMatrix.elements[i].length) {
                for (int j = 0; j < mulMatrix.elements[i].length; j++) {
                    sum += (elements[i][j]) * (mulMatrix.elements[j][iter]);
                }
                resultMatrix[i][iter] = sum;
                sum = 0;
                iter++;
            }
        }
    
    
        return new Matrix(resultMatrix);
    }
    
    public static void main(String[] args) {
    
        double[][] matrixElem = {{1, 2, 3, 4, 2},
                {1, 2, 3, 4, 3},
                {1, 2, 3, 4, 1},
                {1, 7, 3, 4, 9},
                {1, 2, 6, 4, 2}};
    
        Matrix matrix = new Matrix(matrixElem);
        matrix.print();
        System.out.println();
    
    
        Matrix newMatrix = matrix.transpose();
        //newMatrix.print();
    
        double[][] matrixElem2 = {{4, 3, 3, 4, 5},
                {4, 2, 2, 4, 7},
                {7, 4, 3, 2, 8},
                {5, 1, 3, 4, 5},
                {6, 2, 6, 3, 2}};
    
        Matrix matrix2 = new Matrix(matrixElem2);
        Matrix addMatrix = matrix.add(matrix2);
        addMatrix.print();
    
        System.out.println();
        matrix.multiply(3).print();
    
        Matrix result = matrix.multiply(matrix2);
        result.print();
    
        System.out.println("Anderer Konstruktor");
        Matrix matrixEx1 = new Matrix(4, 4, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,16);
        matrixEx1.print();
       // Matrix matrixEx2 = new Matrix(4,4);
        Matrix matrixEx3 = new Matrix(4, 4, 1, 2, 3, 4, 5, 6, 7, 8);
    
    }
    

    }

  • zgagato Avatar

    Hi guys

    Im trying to do the phone Directory kata in Swift. The problem is how should i use regex?

    the range method of strings works good in examples but i have syntax problems too. im stuck

  • Nikolaiko Avatar

    Is there any way to group some Kata's in list and suggest them to my friend?

  • LarisaOvchinnikova Avatar

    If I select a task I have already solved how can I see my solution?

  • mishrapradyumna Avatar

    unable to post solution . I have created my account and also received challenges but unable to identify where to post the solutions. anyone please help me.

  • rzasharp89 Avatar

    any tips to make site more mobile friendly

  • oybek Avatar

    Is there anyone who want to organize hackaton? If yes reply this comment. We will choose set of problems and solve them together via hangouts and discussion

  • zardoxnet Avatar

    Is there a way to delete one of your own solutions?

    What does the "link" button do? When i click it I see my solution but then what can I do?

  • meeramenon07 Avatar

    I passed in 3 of the tests here but failed in one, wonder how to fix it function isValidWalk(walk) { //insert brilliant code here var directions = ['n', 's', 'e', 'w']; var home = 0; var isValidWalk = 10; var walk = [0,0,0,0]; for ( var i = 0; i < walk.length; i++){ if (walk.length === 10 && walk.length >= isValidWalk){ return true; } else if (walk.length < 10 && walk.length < isValidWalk){ return false; } else if (walk.length === 0 || walk.length > 10 || walk.length < 0){ return false; }

    } return true;

    }

  • rkatic Avatar

    Not sure how (relatively new on this site), but it seams a my solution was somehow cloned, which was then grouped together in https://www.codewars.com/kata/reviews/5bcea1400b96aed875000523/groups/5c831842d611800001535265. Seems not fare, since it appears that both variations are identical (which is practically impossible if solved fairly!)

    How about to (atleast) show who did it first?

  • Aerros Avatar

    So far on my experience with codewars in the last 6 months and completing close to 200 challenges of varying difficulty, I've observed several instances where solutions are not grouped together when they virtually identical in structuring and functionality. To visually represent what I'm referring to, I'll use two fictional examples for a simple problem: count number of even ints in array (using Python).

    #Example 1:
    def countEvents(intArray):
      count = 0
      for i in intArray:
        if i % 2 == 0
          count++
      return count
      
    #Example 2:
    def countEvens(ints): #different argument var name
      total = 0 #different var name
      for x in intArray: #different temp var name
        if x % 2 == 0:
          total += 1 #var++ and var+= 1 are equivalent
      return total
    

    In my opinion, examples 1 and 2 should definitely be grouped together. However, in most examples that I've seen, they would potentially be treated as entirely separate from one another. There is no functional difference between "++" and "+=", and changing the names of variables does not change how the solution works. Usually, the solution grouping system seems to be good at grouping together solutions with different spacing, or different variable names within a method/function, but argument variable changes and functionally identical ways to reach the same result are often treated as different. I believe I've also seen whitespace or even comments make my own solutions not group with other virtually identical ones.

    I would propose at the least improving the system to treat any variable (including argument variable changes) as irrelevant when it comes to grouping, and categorizing similar operations or methods that function identically as being the same. The second part would take significantly more effort to implement, but I believe it would be possible by measuring the execution time of the code, and grouping them if they are identical (creating some flexibility to account for server delays). The execution time would not group them alone, but would contribute to some form of "similarity score". If that similarity score was high enough, they would be grouped together.

    Something similar to my proposal may already be in place, but it just seems like virtually identical solutions are rather frequently not grouped together. For myself at least, a lot of the enjoyment from lower level katas come from creating "best practices" or "clever" solutions, so it can be disappointing when a situation similar to the demonstrated one occurs.

  • akashsingh59 Avatar

    i have to find an integer which appears an odd number of times in an array. what am i doing wrong.help!

    public class FindOdd { public static int findIt(int[] a) { int odd,b; for(int i=0;i<a.length;i++) { odd=1; b=a[i]; for(int j=i+1;j<a.length;j++) { if(b==a[j]) { odd++; } } if(odd%2!=0) break; else continue; } return b; } }

  • kalichmu Avatar

    I have passed 28 tests but failed 4 tests for - "Playing with digits" kata. I don't find the correct solution anywhere on the site. Wanted to check if the correct solution is available after attempting a kata or no?

  • amirsaeed671 Avatar

    i have passed 26 tests but 6 tests are failing plz tell me what am i doing wrong

    this is my code of "Split an array" kata...

    function split(arr, prop) {

    //ceate an array

    let returnArray = [[],[]];

    //iterate through all the object in the array

    for(let i = 0; i < arr.length; i ++){ //compare the prop

    if(arr[i][prop] && arr[i][prop] !== false && arr[i][prop] !== 0 && arr[i][prop] != "" && arr[i][prop] != null && arr[i][prop] !== undefined && arr[i][prop] != NaN){
    
      //if it is true than first object of the array is the given object 
    
      returnArray[0].push(arr[i]);
    
    } 
    
    if((arr[i][prop] === null && arr[i][prop] !== true && arr[i][prop] == "" && arr[i][prop] === undefined && arr[i][prop] == NaN) || !arr[i][prop] || arr[i][prop] === 0){
    
      //if it is false than second object of the array is the given object
    
      returnArray[1].push(arr[i]);
    
    }
        
    }
    
    //return the array    
    return returnArray;
    

    }

  • aloneal Avatar

    I can't find kata's discussion... (And not only I)

    In kata "Are they the "same"?" I dond't understand:

    [2, 2, 3] [4, 9, 9]

    True should equal False

    why False? 4^0.5=2, 9^0.5=3

  • MicheleN Avatar

    Hi, My name is Michele and I want to improve my coding skills. I do feel like an idiot because I cannot find the right solution for the challenge, Unwanted dollars, and I have been busy with it for a while now. My sample tests passed 10 and failed 0 but yet it is not approved. Woud you please direct me?

    Thanks in advance

  • sojib-bd Avatar

    My programme work on sample test but in the Attemp my programme work on 93 cases and failed in 28 cases but I wanted to know what are those cases. Is there any access to see what are those cases where my programme is not working? I wanted to see those arguments.

  • sanlihakan Avatar

    Hello guys! I am working on C. I have a problem. How can I sort array's elements with even indexes in increasing order and the elements with odd indexes in decreasing order. For example: If the array is { 10 , 5, 2, 7, 3,9,11 , 6, 8, 13} then after sorting it should be {2, 13,3,9, 8, 7,10,6,11,5} . The result of printing should be as: 13 9 7 6 5 2 3 8 10 11

  • tomahawkgirl92 Avatar

    hey guys! i'm a relatively new Python programmer (and just a new programmer in general) and I'm new to codewars. I was trying to solve the Centuries kata and used this as my answer but it keeps saying that it won't work and that "n" was referenced before it was defined. I don't see why this code wouldn't work. Can anyone help me out? Thanks! -tomahawkgirl

    Edit: i used the correct indentations but they won't show up in this comment

    def century(year): year = str(year) if len(year) == 4: if year[2:4] == str(0) + str(0): n = int(year[0:2]) else: n = int(year[0:2]) + 1 if len(year) == 3: if year[1:3] == str(0) + str(0): n = int(year[0]) else: n = int(year[0]) + 1 return str(n)

  • Asier Arin Benito Avatar

    cat + one potatoes = cat fat

  • Asier Arin Benito Avatar

    I have potatoes and one cat

  • pcsteak92 Avatar

    Hi, I am trying to complete https://www.codewars.com/kata/counting-sheep-dot-dot-dot/train/csharp

    I keep getting a syntax error. Any help would be great as I am pretty new to c#.

    My solution:

    using System;

    public static class Kata { public static int CountSheeps(bool[] sheeps) { //TODO int sheepCount = 0;

    int sh = sheeps[].length;
    
    for(int i = -1; i < sh; i++){
      if(sheeps[i] == true){
        
        sheepCount++;
      }
      else{
      sheepCount = sheepCount;
      }
    }
      
    return sheepCount;
    

    } }

  • natela Avatar

    The equivalent solutions in upper case and lower case in SQL are not grouped together but should be.

  • chrissy_a Avatar

    I'm trying to do https://www.codewars.com/kata/string-repeat/train/java

    I'm having some problems that the string just keeps repeating and never stops. I added the "i" into the print to see what's going on and it keeps resetting to 0 when it reaches the repeat number

    public class Solution { public static String repeatStr(final int repeat, final String string) { int i = 0; while (i<repeat) { System.out.print(string + " " + i); i++; }

       return repeatStr(repeat,string);
    

    } }

    4 a output is: a 0a 1a 2a 3a 0a 1a 2a 3a 0a 1a 2a 3a 0a 1a 2a 3a 0a 1a 2a 3

  • hatef_8 Avatar

    everything is confusing in this site. just signed up I could not change a picture profile!! codes not clear how to contribute is not clear everything is flying here

  • Slushy Avatar

    Im new to code wars. Ive recently successfully attempted some kata challenges. For one i submitted it and realised i didnt clean up my code and i tried to refactor the solution but it made a copy. I now have three solutions to the same kata. How do i remove a solution? Thanks in advance

  • devbuilt Avatar

    I got this Algo during a tech screening can anyone eleborate on how to solve!

    //input let array = [ { skill: 'css', user: 'Bill' }, { skill: 'javascript', user: 'Chad' }, { skill: 'javascript', user: 'Bill' }, { skill: 'css', user: 'Sue' }, { skill: 'javascript', user: 'Sue' }, { skill: 'html', user: 'Sue' } ];

    Expected Output

    var newArray = [ { skill: 'css', users: ['Bill', 'Sue'], count: 2 }, { skill: 'javascript', users: ['Chad', 'Bill', 'Sue'], count: 3 }, { skill: 'html', users: ['Sue'], count: 1 } ]

  • ri8ika Avatar

    Hi!

    I was trying to solve a kata but not able to understand how the following result is coming in?

    https://www.codewars.com/kata/56a5d994ac971f1ac500003e/train/javascript

    testing(longestConsec(["wlwsasphmxx","owiaxujylentrklctozmymu","wpgozvxxiu"], 2), "wlwsasphmxxowiaxujylentrklctozmymu")

    As far as I understand the kata, it should result "owiaxujylentrklctozmymuwpgozvxxiu"

    Can anyone please explain? Thanks.

  • a.2.c.4 Avatar

    I was grouped with code that is worse than mine. Not that it broke my heart, but it is sad.

    Here: https://www.codewars.com/kata/5715eaedb436cf5606000381/solutions/java/

  • Marcos Turing Avatar

    Write a program that receives a number and then a comma-separated circular list (without repeats) and responds as quickly as possible to whether a number belongs to the list.

    Example:

    Input: 5 2,3,4,0,1 Output: no

    Input: 4 2,3,4,0,1 Output: yes

    Input: 3 4,6,11, -1,1,2,3 Output: yes

  • bayoumymac Avatar

    Hello everyone, was wondering about magic rectangles specifically constructing their elements; if possible would love some elaboration on this topic or some helpful resources

  • Judini Avatar

    i can't find the Unlock Solution button?

  • Lisenndre Avatar

    Good afternoon, I am a new guy here. Tryin to improve my sql progress, so my first kata is

    "to create a SELECT statement, this SELECT statement will use an IN to check whether a department has had a sale with a price over 98.00 dollars"

    ...

  • yatinovate Avatar

    You are going to be given an array of integers. Your job is to take that array and find an index N where the sum of the integers to the left of N is equal to the sum of the integers to the right of N. If there is no index that would make this happen, return -1

  • BohdanShuliaka Avatar

    Hey guys, i need help with Game of Go kata, have the same task in my js course, i have spent few days and still my progress is miserable, maybe somebody can get any similar solutions?

  • user5929647 Avatar

    Is it frowned upon to refactor your code with other people's ideas?

  • user5789726 Avatar

    Hello, My name is Danyshman. And i am superman!

  • harrysingghh Avatar

    i participated in a kata. And when i finish the i got this error

    "Process exited prematurely with a SIGFPE signal"

    What does it mean

  • Chrono79 Avatar

    Please, read what this topic should be about:

    Solutions Grouping

    About

    This site will make an attempt to group similar solutions together so that they may be voted on and discussed as a group. If you have any feedback on how this process can be improved, this is the place to talk about it.

    If you want to discuss some kata in particular, there is a Discourse section for each one.

  • mrc-rius Avatar

    I trying the duplicate_encode kata for Python.

    Despite all test are ok, when trying the final attemp it gives me an error in the last test, it returns:

     '))(()())())' should equal '()(((())())'
    

    My code is:

     def duplicate_encode(word):
       nword=''
       for c in word.lower():nword+='(' if word.count(c)==1 else ')' 
       return nword
    

    I do not have feedback of the input that gives error. Can someone help me please?

    Thanks.

  • naaga_n Avatar

    ERROR for problem https://www.codewars.com/kata/coordinates-validator/train/python

    it passes sample tests but fails at attempt .gives the following Error some please help me finish the problem

    Test Results: Example Test Cases should return true for valid coordinates (7 of 7 Assertions) STDERR: Traceback: in in is_valid_coordinates ValueError: could not convert string to float: '- 23.4234'

    |||| MY CODE |||||||

    code:

    def is_valid_coordinates(coordinates):

    c=coordinates
    symb=[',','-','.',' ']
    nums='0123456789'
    for x in c:
        if x in symb:j=0
        elif x in nums:j=1
        else:return False
    s=c.find(',')
    x=float(c[:s].strip())
    y=float(c[s+1:].strip())
    if x<=90 and x>=-90 and y<=180 and y>=-180:
        return True
    else:return False
    
     
    
  • Sorryuken Avatar

    Hi, I'm doing Shakespearean Tug of War (https://www.codewars.com/kata/shakespearean-tug-of-war) and my program works for 6 fixed tests but the 7th one fails and then some random tests too. The team is correct but the number not. Any hint on what I might be doing wrong?

  • 张琪灵 Avatar

    Hello everyone i just begin improve my js coding skill ,can anyone join me.We can teach each other

  • augustom0422 Avatar

    Você recebe uma matriz (que terá um comprimento de pelo menos 3, mas pode ser muito grande) contendo números inteiros. A matriz é inteiramente composta de inteiros estranhos ou inteiramente composta de inteiros pares, exceto por um inteiro inteiro N. Escreva um método que leva a matriz como um argumento e retorna esse "outlier" N, nao conseguir resolver

  • theoegui Avatar

    Hello everyone. I just started this problem.I have no idea where to start. Codeacademy.com did not help.

  • aploteo Avatar

    Hi, I've a solution to a problem and I'm new at this website. Would you please tell how do I submit this solution? Thanks luca

  • tomo.dev Avatar

    I have a problem with my code. It is my first assignment so maybe I'm doing something wrong with the return value. I really don't know. The program is written in C.

    ASSIGNMENT: If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

    Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.

    Note: If the number is a multiple of both 3 and 5, only count it once.

    CODE:

    int solution(int number) { // code here int k; scanf("%d", &k); int a = 0; int b = 0; int c = 0; int d = 0; int i = 0; int j = 0; int sum = 0; if(k % 3 != 0 && k % 5 == 0){ a = k / 3; b = k / 5; for(i=1; i<=a; i++){ c += 3 * i; //printf("c u koracima = %d\n", c); } for(j=0; j<b; j++){ d += 5 * j; //printf("d u koracima = %d\n", d); } sum = c + d; } else if(k % 3 != 0 && k % 5 != 0){ a = k / 3; b = k / 5; for(i=1; i<=a; i++){ c += 3 * i; //printf("c u koracima = %d\n", c); } for(j=0; j<=b; j++){ d += 5 * j; //printf("d u koracima = %d\n", d); } sum = c + d; } else if(k % 3 == 0 && k % 5 == 0){ a = k / 3; b = k / 5; for(i=0; i<a; i++){ c += 3 * i; //printf("c u koracima = %d\n", c); } for(j=0; j<b; j++){ d += 5 * j; //printf("d u koracima = %d\n", d); } sum = c + d; } else{ a = k / 3; b = k / 5; for(i=0; i<a; i++){ c += 3 * i; //printf("c u koracima = %d\n", c); } for(j=1; j<=b; j++){ d += 5 * j; //printf("d u koracima = %d\n", d); } sum = c + d; } //printf("a = %d\n", a); //printf("b = %d\n", b); //printf("c = %d\n", c); //printf("d = %d\n", d); //printf("sum = %d\n", sum); return sum;
    }

    Would you be so kind and review my code? What am I doing wrong?

  • zhangyang11c Avatar

    Hi, I have a question about finding the length of the longest substring in the given string s that is the same in reverse. As an example, if the input was “I like racecars that go fast”, the substring (racecar) length would be 7. My code is follow and I don't know where is wrong, How do I do this?

    def longest_palindrome (s): for i in range(len(s)): for j in range(len(s),i,-1): n = s[i:j] if n == n[::-1]: return len(n)

  • rol173 Avatar

    Hi, I have an array containing a number of values of different types. The task is to move all of the zeros to the end. The problem is that I can't distinquish a zero value '0' from a boolean value 'False' when comparing them in a cycle. So actually this is my question. How do I do this?

  • 4knort Avatar

    kata: https://www.codewars.com/kata/55c6126177c9441a570000cc/train/javascript

    condition: When two numbers have the same "weight", let us class them as if they were strings and not numbers: 100 is before 180 because its "weight" (1) is less than the one of 180 (9) and 180 is before 90 since, having the same "weight" (9) it comes before as a string.

    Test.assertEquals(orderWeight("2000 10003 1234000 44444444 9999 11 11 22 123"), "11 11 2000 10003 22 123 1234000 44444444 9999")

    why do we expect that the order will be 11 11 2000 if 2000 is before 11 in argument and why 10003 is before 22? can't solve this kata cause of the strange instructions

  • Chrono79 Avatar

    Try not to post whole code solutions here, there is no way of flag them as spoilers and are shown on the Home's Discussion block. Discussion about a particular kata solution belongs on that challenge solutions tab (they're only visible to people that already solved that kata). Thanks.

  • user63032 Avatar

    def spin_words(sentence): # Your code goes here word = "" sen = "" for i in sentence: if i != " ": word = word + i if len(word) >= 5: r1 = word[::-1] sen = sen + r1 else: sen = sen + word

    return sen
    
  • user63032 Avatar

    def spin_words(sentence): # Your code goes here word = "" sen = "" for i in sentence: if i != " ": word = word + i if len(word) >= 5: r1 = word[::-1] sen = sen + r1 else: sen = sen + word

    return sen
    
  • dtarvin Avatar

    Hi, I did the Valid Parentheses challenge, where you're supposed to write a function that tells whether a bunch of parentheses are grouped together correctly. () should be true, )( should be false, ()) should be false, etc. I solved the challenge, but I like to look at other peoples' answers to see how I could've done better. I don't understand how the top answer works successfully. Here is the code: function validParentheses(parens){ var indent = 0;

    for (var i = 0 ; i < parens.length && indent >= 0; i++) { indent += (parens[i] == '(') ? 1 : -1;
    }

    return (indent == 0); } When I try to think through it, it seems like the code would return )()( as true, even though it's false. However, when I ran the code it correctly returned it as false. Can someone explain to me how the code works so that the proper result is returned in this case?

  • Kuribo Avatar

    I am doing the XO Kata and I dont know why this doesnt return true for the string xoxo I understand why it wont work for capital letters, I havent implemented that yet:

    public static boolean getXO (String str) {
     
      boolean state=false;
      int countx = 0;
      int county = 0;
     if(!str.contains("x") & !str.contains("o") ){
        state = true;
      
      }   
    
      for(int i=0;i<str.length();i++){
        if(str.charAt(i)=='x' ){
        countx +=1;
        
        }
        else if(str.charAt(i)=='y'){
        county +=1;
        }
      }
      if(countx==county){
      System.out.println(countx);
      state=true;
        
      }
      
     return state;
    }
    
  • adam080 Avatar

    I'm doing the Bingo Card kata. I did use Random class. However, it says "The same number appeared on more than 30 of the 100 cards on the same spot, are the cards random? Expected: False But was: True"

    Having each square 15 posibilities and 5 places to be, it doesn't seem weird to get the case of sharing the same spot when you test with 100 different ones.

    If I did random the numbers, how can I fix this problem? Thanks!

  • phatace Avatar

    Hello to all CodeWarriors I wrote code for Gap in primes (in Python). It passes all sample tests but unfortunately I can't submit the solution because of server time restrictions for code execution. It works pretty fast on my slow computer and sample tests take about 100ms. Could you help me to find solution? Is it codewarior's bug or I need fixes in my code

    def gap(g, m, n):
        def isPrime(num):
            for i in range(2, num - 1):
                if(num % i == 0):
                    return False
            return True
    
        def primeInRange(n1, n2):
            for y in range(n1 + 1, n2):
                if(isPrime(y)):
                    return False
            return True
    
        for z in range(m, n):
            if(isPrime(z) and z + g < n and isPrime(z + g) and primeInRange(z, z+g)):
                return[z, z+g]
                break
    
  • cjislegit Avatar

    Hey All,

    I am hoping to get some feed back on my code for the Sum of Digits Kata, my code only passes 2 of the tests and fails the other four and I am not sure why.

    My code

    function digital_root(n) { var all = 0; var m = n.toString(); var t = 0; for(var i = 0; i < m.length; i++){ all = m.charAt(i); t += +all; } return(t); };

    Test Results: Test Passed: Value == 7 Expected: 6, instead got: 15 Expected: 2, instead got: 20 Expected: 9, instead got: 108 Expected: 9, instead got: 27 Test Passed: Value == 0

    Thanks!

  • ReferenceOfAnObject Avatar

    Not understanding hamsterme. Got all test cases but having issues with random input. Not sure what the question expects. Solution expectation explaination missing large chunk of well... explaination.

  • calluna Avatar

    Hi,

    I'm working on "Its all backwards" and in my console it gives the correct output, but when I validate it in the Codewars console it does not pass the tests and it is giving different answers than I see in my console.

    What gives?

  • iamsdhar Avatar

    Is there a way to view your previously solved Katas? Thanks!!

  • richardk70 Avatar

    Digital root strangeness. My code is returning an undefined even though the console.log(n) call shows the proper value in the variable. Not sure what the problem is. Thanks for any and all pointers.

    // add the digits of the numbers together, return the final sum function digital_root(n) { console.log(n); if (n <= 9) return n; else{ // use recursion! var numString = n.toString(); var stringArr = numString.split(''); var toNums = stringArr.map((e)=> parseInt(e)); var sumNums = toNums.reduce((acc, curr) => acc + curr ); digital_root(sumNums); } }

    console.log(digital_root(16));

  • hyip8000 Avatar

    Hi! I'm trying to code a simply javascript reverse/ mirror function and it's my very first practice for Javascript so I'm a little lost.. I'm not sure how to read the sample tests and I'm sure my code is working fine. Can someone help?

    const mirror = str => {

    var temp = "";

    for (var i= str.length - 1; i>= 0; i--){

    temp += str.charAt(i);

    }

    return temp;

    };

    Sample Test:

    const assert = require('chai').assert; const style = style="display: inline-block; transform: scale(-1, 1)"; const log = m => console.log(m, ' ', <span ${style}>${m}</span>);

    // Tests describe('mirror', () => { it('basic', () => { const expected = { abc: 'cba', arara: 'arara', }; const actual = mirror({ abc: undefined, arara: undefined, });

    console.log('Expected');
    Object.keys(expected).forEach(k => log(k));
    
    assert.deepEqual(actual, expected);
    

    }); });

  • vguzev Avatar

    Hello, codewarriors!

    I've started collection "Learning TypeScript": https://www.codewars.com/collections/learning-typescript

    Generally, I'm trying to create katas for this handbook: https://www.typescriptlang.org/docs/handbook/basic-types.html

    Need help with testing/writing katas :)

  • letfly Avatar

    The system can't ATTEMPT!!

  • Ali3noid Avatar

    Hi i have problem with "Alphabetic Anagrams" Kata (http://www.codewars.com/kata/53e57dada0cb0400ba000688). I passed all tests and made some other cases. I passed them as well. Problem is i can't get through final attempt. I just get error 24. This error dont tell me so much. What am I doing wrong? My code:

    class Anagrams { private static BigInteger[] bigFactorials = { new BigInteger("51090942171709440000"), new BigInteger("1124000727777607680000"), new BigInteger("25852016738884976640000"), new BigInteger("620448401733239439360000"), new BigInteger("15511210043330985984000000")};

    private static Long[] smallFactorials = {1L, 1L, 2L, 6L, 24L, 120L, 720L, 5040L, 40320L,               362880L, 3628800L, 39916800L, 479001600L, 6227020800L, 87178291200L, 1307674368000L,                 2092278988800L, 355687428096000L, 6402373705728000L, 121645100408832000L, 2432902008176640000L};
    
    BigInteger listPosition(String word) {
        List<Character> initialList = new ArrayList<>();
        List<Character> sortedList = new LinkedList<>();
    
        for (char letter : word.toCharArray()) {
            initialList.add(letter);
            sortedList.add(letter);
        }
    
        Map<Character, Long> counts =
            initialList
                .stream()
                .collect(Collectors.groupingBy(e -> e, Collectors.counting()));
    
        Collections.sort(sortedList);
        return getSortedPosition(BigInteger.ZERO, initialList, sortedList, counts);
    
    }
    
    private BigInteger getSortedPosition(BigInteger sum, List<Character> initialList, List<Character> sortedList, Map<Character, Long> counts) {
        int size = initialList.size();
    
        Long repetitions = 1L;
    
        for (Map.Entry<Character, Long> entry : counts.entrySet()) {
            Long value = entry.getValue();
            repetitions = getFactorial(BigInteger.valueOf(value)).multiply(BigInteger.valueOf(repetitions)).longValue();
        }
    
        if (size == 1) {
            return sum.add(BigInteger.ONE);
        } else {
            Character firstLetter = initialList.get(0);
            int index = sortedList.indexOf(firstLetter);
            Character removedChar = sortedList.remove(index);
            counts.put(removedChar, counts.get(removedChar) - 1);
            BigInteger tempSum = getFactorial(BigInteger.valueOf(size - 1)).multiply(BigInteger.valueOf(index)).divide(BigInteger.valueOf(repetitions)).add(sum);
            return getSortedPosition(tempSum, initialList.subList(1, size), sortedList, counts);
        }
    }
    
    private BigInteger getFactorial(BigInteger n) {
        int nInt = n.intValue();
        if (nInt <= 20) {
            return BigInteger.valueOf(smallFactorials[nInt]);
        } else {
            return bigFactorials[nInt];
        }
    }
    

    }

  • czartu66 Avatar

    Hi all, i've started with Python recently and I have a problem with "Stop gninnipS My sdroW!" exercise. Description: "Write a function that takes in a string of one or more words, and returns the same string, but with all five or more letter words reversed (Just like the name of this Kata). Strings passed in will consist of only letters and spaces. Spaces will be included only when more than one word is present."

    My code looks like that:

      # Your code goes here
      new_sen = sentence.split(" ")
      new_sen2 = ""
      n = 0
      for i in range(len(new_sen)):
        
          if (len(new_sen[i]) >= 5):
              new_sen[n] = reversed(new_sen[n])
              new_sen2 = new_sen2.join(new_sen[n])
              n = n + 1
          else:
              new_sen2 = new_sen2.join(new_sen[n])
             
          return new_sen2
        
    

    ...output shows that single word is ok, but still shows an error with multiple words "'Hey' should equal 'Hey wollef sroirraw'". Could you help me with this problem?

  • Lexiqw Avatar

    Hey guys my name is Lexi and I am a first year student at UCT. I have been given a project in java and I don't really know how to do it. If there is anyone who is understands java and is willing to help please email me at lexiwellsqw@gmail.com . I will really appreciate it if someone could try to help it would contribute tremendously to my career as a programmer.

  • ginnk Avatar

    Hi all, I am new to javascript and am having trouble with the Split Camelcase kata.

    Description:

    Split a camelcase string into individual words, the return value must be a single string of words seporated by one whitespace.

    The strings are to be split on the capital letters like so:

    'StringStringString' => 'String String String'

    **I completed this with no problem, but what it doesn't mention in the instructions is that if two or more capital letters are next to each other, you only add a space before the first capital letter. So "TTThisIsAnExample" would become "TTThis Is An Example" and not "T T This Is An Example" ... if that makes sense. So this is the suuper inefficient code I wrote to try to satisfy those tests, but apparently it is an infinite loop and I have no idea why:

    function splitter(str){ let array = str.split(''); for (let i=0; i<array.length; i++) { if(array[i] === array[i].toLowerCase() && array[i + 1] === array[i + 1].toUpperCase()) { array.splice(array.indexOf(array[i + 1]), 0, " "); } else if(array[i] === array[i].toUpperCase() || array[i] === " ") { continue; } } return array; }

    I would appreciate any help people could offer on this code. Thanks!

  • RapidR3D Avatar

    I don't understand why this is giving me an error when it works fine in my interpreter...The Kata:

    In this kata you will create a function that takes a list of non-negative integers and strings and returns a new list with the strings filtered out.

    Example

    filter_list([1,2,'a','b']) == [1,2] filter_list([1,'a','b',0,15]) == [1,0,15] filter_list([1,2,'aasf','1','123',123]) == [1,2,123]

    My CODE:

    def filter_list(l): numbers = [int(l) for l in str.split(l) if l.isdigit()] print(numbers) string = ' '.join(str(e) for e in numbers) return string #return a new list with the strings filtered out

    The ERROR:

    Traceback: in in filter_list TypeError: descriptor 'split' requires a 'str' object but received a 'list'

    Any help would be greatly appreciated. Thanks in advance.

  • Ignatiusflo Avatar

    My first code. It's the convert two numbers added together to a binary string one. This is my code.

    def add_binary(a,b): return a + b c = 5 d = 3 sum = (add_binary(c ,d)) solution = bin(sum) print(solution)

    It works but it doesn't pass the second test example. Any ideas?

  • ginnk Avatar

    Hi all, not sure if I am asking this question in the right topic section - but I completed a kata asking to remove all the strings from a mixed array. I was accidentally logged out when I submitted my solution and once I logged in I could no longer find that kata. I would like to submit my solution! If anyone knows the name for the kata could you let me know please? You need to create a filter function that removes all the strings from a mixed array and returns a new array with only the numbers. Thanks.

  • MomoSong Avatar

    When if i can. i want to help translate. but where is translate section? i mean english -> korean translate.

  • rado9408 Avatar

    Write a C++ function int div(double &nominator, double denominator) that computes the integer part of double division. It takes as its arguments double &nominator by reference and double denominator by value and returns the integer part of the division. Before returning the result, it assigns the remainder to the nominator. For example, if nominator is 3.7 and denominator is 1.4, the function returns 2 with nominator assigned a new value 0.9, since 3.7 - 2 * 1.4 = 0.9.

    who can help friends??????? I need help....

    : Write a C++ program that creates two 3-element arrays double price[3] and int items[3]. These arrays represent prices and amount of three different products respectively. The program inputs the element values of double price[3] array and double money – the total available money. It assigns values to the elements of int items[3] array as follows: the first element is the maximal amount of items of the first product that can be bought by the initial money, the second one – the maximal amount of items of the second product that can be bought by the remaining money, and the third one – the maximal amount of items of the third product that can be bought by the last remaining money

    and third .....

    : Chess is played on an 8-by-8 board. The columns (files) are enumerated with letters from ‘a’ to ‘h’, and the rows (ranks) – with numbers from 1 to 8. Write a C++ function int ddist(string cell1, string cell2) that takes as its argument two two-character strings string cell1 and string cell2 representing the column and row of two cells and returns the distance between them in a diagonal direction. If the cells are not lying on the same diagonal, the function returns -1.

  • MomoSong Avatar

    Hey. people. my solution always too long and inefficient. how can i learn clever solution idea? is it about natural talent thing? if i don't have sense of clever code.. is it still okay?

  • arssonist Avatar

    I'm having a problem with countPositivesSumNegatives(). I'm a newbie but can't figure out why I'm getting and error. Not fail, but error.

    The error is long, but gist is "TypeError: Cannot read property 'length' of null at countPositivesSumNegatives". I have obviously taken steps to solve the obvious things this error suggests. All other tests pass, and none fail.

    Can I get help here? Not sure where the offcial help forum is.

  • Kudinov Avatar

    Your task is to construct a building which will be a pile of n cubes. The cube at the bottom will have a volume of n^3, the cube above will have volume of (n-1)^3 and so on until the top which will have a volume of 1^3.

    You are given the total volume m of the building. Being given m can you find the number n of cubes you will have to build?

    #include class ASum { public: static long long findNb(long long m); };

    long long ASum::findNb(long long m) { if(m<0) return -1; double descr = 1+8*sqrt(m); double n1=(-1+sqrt(descr))/2; if(n1==floor(n1)) return n1; return -1; }

    this code does not go through one test only, don't understand whatis the problem, help me plz

  • PHPSQLLOVE Avatar

    SELECT c.customer_id,c.email,COUNT(c.customer_id) AS payments_count,SUM(c.customer_id ) AS total_amount FROM customer c JOIN payment p ON (c.customer_id = p.customer_id) ORDER BY c.customer_id limit 10;

    I have done this for the SQL Basics: Top 10 customers by total payments amount question but it still does not work it also wants to return a float number as well for the total amount

    Overview

    For this kata we will be using the DVD Rental database.

    Your are working for a company that wants to reward its top 10 customers with a free gift. You have been asked to generate a simple report that returns the top 10 customers by total amount spent. Total number of payments has also been requested.

    The query should output the following columns:

    customer_id [int4] email [varchar] payments_count [int] total_amount [float] and has the following requirements:

    only returns the 10 top customers, ordered by total amount spent

  • doca94 Avatar

    Hi everyone! Can someone help me with KATA Count of positives / sum of negatives Here is my code and there is one wrong value when I attempt to pass. Please, can anyone help me to find mistake? Thanks a lot. function countPositivesSumNegatives(input) { var positive=0; var negative=0; var array1=[]; if(input == 'undefined' || input == null){ return array1;} else{ for(var i=0; i<input.length; i++){ if(input[i]>0){ positive+=1; }else{negative+=input[i];}

    }
    

    var array=[positive, negative]; return array; } }

  • KissOf Avatar

    Hello,

    I have three identical solutions on a KATA. I wanted to delete two of them (cause they are identical) but couldn't do it.

    So I decided to REFACTOR one of them by making the code better. After succeeding refactoring it, I couldn't REFACTOR it but only SUBMIT it. And as a result, didn't REFACTOR the solution I wanted to.

    Does anyone have an idea on how to rewrite the solutions to avoid similar one?

  • hindujesus Avatar

    I dont even think I'm answering any of the katas correctly. I dont know how to input anything, i think.

  • Arbane Avatar

    Is this a place where I can ask about the kata?

  • serralath Avatar

    Hello! Is it possible to publish two solutions for one kata? I ask because I made a second try and the second solution-code isn't showed in the solutions-overview. Did I do something wrong?

  • omriShneor Avatar

    Kata:Are they the "same"?(C++ learning the language) I seem to be failing only test 8. the result of the test is "true". anyone knows what that test test's? am i not checking some exreme cases?

  • zruF Avatar

    Suggestion: What about adding more solution sort possibilities like "number of characters" or "runtime"? Is that possible?

  • perfectcoder Avatar

    Kata: SQL Basics: Group By Day

    I have one failure during its execution. Here is test-case message: " should should return the expected results ✘ expected true to respond to true? or perhaps you meant be true or be_truthy "

    Does it connected with my code?

  • ravi_shankar Avatar

    https://www.codewars.com/kata/tribonacci-sequence/train/python

    I HAVE SOLVE THIS BUT GETTING ERROR WHILE FINAL SUBMISSION

    HERE IS MY CODE

    def tribonacci(signature,n): if n == 0: return [] if n < 4: return signature[:n] for i in range(2, n - 1): new = signature[i] + signature[i-1] + signature[i-2] signature.append(new) return signature

  • SamaR3 Avatar

    #issue @twinbird24 The kata Average Scores works fine on VS2015 on my laptop, but doesn't work here. The second basic test returns a value of 94, but here, it's returning 78. please help.

  • bhavya9107 Avatar

    #how to implement difference function #what is problem with my code def array_diff(a, b): for i in range(len('a')): if (a[i] in b): a.remove(a[i]); break;

  • user404642 Avatar

    Hi! How to submit my solution? I'm now 8 kyu and I've solved the task from the 7 kyu, but I can't submit it. Why???

  • sharpenyourskillz Avatar

    Hi, I just joined and solved my first kata -- which when I view my profile I see as a completed kata. However, I wanted to peruse my solution again, just mainly for curiosity, but when I try to view solutions to this "solved" kata the system says I can't view them since I haven't yet solved the kata. Am I doing something wrong, or is this a bug? Thanks, and cool site.

    UPDATE: Maybe I was doing something wrong - if I click on the kata and then solutions, it says that I can't see them as I haven't solved (though I have); but if I click on my profile, then 'solutions' from my profile, I do see my submitted solution. Maybe that's just the way things work, though it was a bit confusing. Perhaps working as designed?

  • AppAttacker Avatar

    i solved the training module called "mumbling" my answer is identical to the solution but its saying its wrong... what do i need to do

    import sys def accum(s): # your code i = 0 j = 1 while i < len(s): a = s[i] * j sys.stdout.write(a.title()) sys.stdout.write("-") i += 1 j += 1

  • smp Avatar

    Hello, is it possible to delete a solution? I submitted two that were almost identical (didn't know you could refactor) and now I'd like to remove one. Thanks!

  • reese Avatar

    Is it possible to add the solution's runtime to each submitted solution listed? Learning the cool features and extensions to a language is neat, but example runtimes of the various solutions could be very useful.

  • Tiagovsky Avatar

    Is it possible to view all the solutions of a user?

  • aliens9889 Avatar

    Hi everyone!! Does anyone has an example of how to getcenter from multiple markers (coordinates). I want to from the same example the google gives here https://developers.google.com/maps/documentation/javascript/examples/layer-heatmap?hl=es And try to get the middle of all GetPoints. By The Way, Thanks for the Help. :+1

  • TanYiXun Avatar

    i dont know why although my output matches the same as the test cases result i still got error.. E.g. Error ,expected:0, actual:0

  • pucefloyd Avatar

    I don't understand why I can't see the solution of the kata while I am working on it...

  • user3484633 Avatar

    Hi, I have succefully solved my first kata, at least I run the tests and it says it's all good, but when I submit it it says "1 solved, 1 failed" and tells me to try again,when I run the tests it says "1 solved, 0 failed", why is this happening?

  • panghal18 Avatar

    How can i see the solution to any problem?

  • L_L Avatar

    This web so helpful for me :))

  • coolhydro Avatar

    Please help me to solve "Don't rely on luck" problem. Please I'm stuck.

  • Jacob Avatar

    Hello! Suddenly someone is from Ukraine or Russia Knock on Skype will work together skype: mister-djim!

  • JasmineYuan Avatar

    How can I use library like underscore.js in my code?

  • renzhentaxi Avatar

    I thought it would be really cool if you could save the amount of time a solution took in your database and use this information to rank the solutions. Since the one that took the least amount of time is probably the most efficient one.

  • Anu003 Avatar

    Hi, I am new to code wars, could anyone please guide me where to write a solution?

  • vilnytskyi Avatar

    Is there any way to remove first published solution? I have lucky completed one based on random tests and suddenly published it. Later I have solved it correctly but now there are two of mine solutions in the list.

  • draconar Avatar

    How may I see the katas that I started but haven't finished yet?

  • oson Avatar

    Grouping through community set flags

    I suggest a grouping mode based on tags that users give to a solution. Many solutions can be discerned by very obvious criteria a user (human being) is able to grasp very quickly, but tools cannot). For Java for example there are many java 8 solutions using streams/lambdas. Flagging these would be a good group. Then you have "Optimised", "Vanilla Java", "Java with Guava and oher libraries", "Clean Code/Refactored", maybe things like "With issues", "Obvious cheating/circumventing acceptance tests" etc.

    The flagging system should allow introducing new flags on the fly, but also give a list of all the flags already in use. So you can flag with some clicks, or by entering a new name. Very similar to the system currently used for tagging (new) katas!

    Advantage of tags that people can define is that people can decide about the interesting features of a solution or time ("Zeitgeist"). Grouping would benefit from the current trends directly mirrored in the flags given from a user, so to say.

    Personally I do not fancy a machine based grouping that much. I don't care what some algorithm tells me is "like my solution", in 99% of all cases, it isn't anyway. Mostly I would be interested in those solutions that are not like my solution... but which algorithm could possibly know that...

    So, more power to the users/community! Less power to tools. And actually, less power to the honor points as well (but this is another topic).

  • jnordwick Avatar

    There are tools out there that universities use for cheat detection that will normalize code (variable names, whitespace, partial evaluation) and then computer a modified edit-distance-like score of similarity. They used to use it at Cal. Can't something like one of those be hacked up?

  • bkaes Avatar

    User driven solution grouping

    The problem

    We all know that grouping solutions isn't easy. People use other variable names, import libraries in another order, indent their code not the same way others do. Some of those things can be handled, for example with clang-format-diff or similar tools. However, take the following three snippets:

    module Codewars.Kata.HelloWorld
    import Prelude (String)
    
    helloWorld :: String
    helloWorld = "Hello World"
    
    module Codewars.Kata.HelloWorld
    
    helloWorld :: String
    helloWorld = "Hello World"
    
    module Codewars.Kata.HelloWorld
    
    helloWorld = "Hello World"
    

    They're all doing the same, their behaviour doesn't differ at all. However, the current grouping mechanism doesn't recognize those solutions as "the same". A really different solution would be something along

    module Codewars.Kata.HelloWorld
    
    createHelloWorld :: a -> String
    createHelloWorld _ = "Hello World"
    
    helloWorld = 
      createHelloWorld undefined
    

    So, how can we group those things better?

    Lets get some Levenshteinian help

    Disclaimer: I'm not an expert in comparing strings, so the following could be a load of bull****. There are probably better algorithms.

    If we take the Levenshtein distance of the four code fragments above, we end up with the following (symmetrical) table:


              |  Import   | No import |  Minimal  |  Create
    ~--------------------------------------------------------
    Import    |  0 (1.00) | 23 (0.94) | 43 (0.86) | 61 (0.87)
    No import | 23 (0.94) |  0 (1.00) | 20 (0.93) | 60 (0.86)
    Minimal   | 43 (0.86) | 20 (0.93) |  0 (1.00) | 79 (0.79)
    Create    | 61 (0.87) | 60 (0.86) | 79 (0.79) |  0 (1.00)
    

    The number in parentheses is 1 - levenshtein(str1,str2)/(length(str1) + length(str2) / 2), the other the actual Levenshtein distance. Lets call the number in parentheses the Levenshteinian likelihood, or LL. We can see that the LL of our last snippet Create to the other snippets is less than 0.9, whereas Import <-> No import are above 0.9, as well as No import <-> Minimal. If we would automatically group solutions that have a LL of 0.9 or higher, we would group Import <-> No import <-> Minimal, since grouping should be transitive.

    However, that's not good enough. There are too many false positives and false negatives that can happen, although a LL of .98 strongly suggests that both solution are the same. So what's this fuzz about? It's meant for an initial grouping score.

    Involve the author

    Whenever the user solves a kata, he's usually presented with other solutions. They're ordered by best practices, clever, or whatever the user chose the last time he browsed those snippets. However, when a user solves kata, he shouldn't be presented with those things, at least not initially. When the user has solved a kata he should be presented with something along this:

    Good job!

    Great job solving this kata. We found some solutions similar to yours, please take a moment to check whether you and other warriors do the same:

    • Max' solution
    • Jenny's/Sarah's solution (already grouped)
    • Tom's/Susanne's solution (already grouped)
    • None

    The suggestions are based on the LL: if any LL of a solution in a group is more than .90, we suggest the solution/group for grouping. In order to keep the calculations on the server side to a minimum, the LL should computed if the solutions' lengths don't differ too much and don't exceed a certain treshhold.

    If the user things that none of the other solutions are similar, he can simply click on "None". Then, the scoring mechanism I mentioned takes effect.

    Involve the users

    Take the initial LL, multiply it by 10, and take 5: ll(str1,str2) * 10 - 5. You'll end up with something in [-5,5]. Users can now vote for likeness. Each vote is weighted the same way a usual vote is weighted, so warriors with +500 honor change the score more than those with 20. As long as the score is between [-10,10] (excluding the ends), the potentional pair is up to review. If the score reaches -10, the pair is declaired unsimilar and removed from review, if it reaches 10, it's also removed from review, but the solutions get grouped.

    Afterwards, the LL of other items in the review queue must be adapted, but I'm not sure how to do that.

    If a user gets 1 honor (or 1 group honor, a new point currency) per reviewed solution/solution or solution/group pair, it should be rather fast. You could also provide a "group solutions queue" or something similar.


    Questions and Answers

    What if the author groups the question incorrectly?

    Well, that could be handled with flags, see my feature request.

    What if I don't have a LL between two solutions, since they exceeded the threshold?

    Have users suggest a pair, which will start with a score of -5.

    Should the votes really be weighted? After all, it's a review process!

    Well, that's up to discussion. If codewars introduced "group honor", the weighting should be based on that instead of the usual honor.

    One honor per vote? That's insane!

    You want to motivate people to participate. Gamification is usually a pretty good way. That being said, one could change this a little bit. For example, the user gets 1 "grouping honor" and additional "grouping honor", if other users agreed with his vote, e.g. if he votes + and it reaches 10.

    Agreed with his vote? Well, then I'll just vote for the majority.

    Which is why the current score should be hidden. Abuse and stuff.


    Last words

    So, this has been yet another rather long text/feature request/idea for something. I hope it has been enjoyable to read, as I just wrote this down in a jiffy as the ideas came along, and I really hope that I haven't messed up formatting. (Edit: yep. Headings aren't really there :/)


    TL;DR

    Have users handle the grouping instead of fully automated mechanisms. Lure them with points, score the grouping.

  • paragonHex Avatar

    Is there any way to tell us how runtime-optimized a solution is? I see the "Process took ... ms to complete" message after solving a JS kata, and I wonder..

    If that kind of data is solid and comparable, can you attach it to the solutions, to let us notice how methods we use compare to each other in runtime.

    Just a number there, and I think I would learn a lot from it.

  • Katzen_gott Avatar

    Not sure it would work for other languages, but for python it doesn't matter if you write 'some string' or "some string", except for need to escape quotations marks accordingly (if you use 'some string' you can leave doubled quotation marks but need to escape single ones and vice versa). So in most katas it doesn't matter which quotes to use, therefore it would be great to group such things.

  • user3482173 Avatar

    Not really the right place to left that tought but...

    I don't feel like it is easy to refactor your own code. (I just discovered this otpion in my personnal page -> kata solutions -> completed -> refactor). I feel like it would be good to have a "refactor" button on your solution in the solution section of a kata. I often want to edit my solution a bit after seeing other solutions. Plus a "delete" button when you have multiple solution. For the moment even after refactoring i feel like the old solution appears first in the solutions when the refactored should be first.

  • Katzen_gott Avatar

    Some more thoughts about grouping. Solutions like def summ(a,b): return a+b and def summ(a,b): return b+a are counted as different. Not sure if it's possible to detect such things, but it would be good I think. Also for Python functions range() and xrange() are counted as different, though usually Python2 users use xrange() as it had some advantages, and Python3 users use range() cause in Python3 it behaves same way as xrange() in Pyton2, while latter is deprecated. So difference between such soutions is just preferred version of language.

    Thinking about it, I assume that you could still consider these two things as different, but add some 2-leveled grouping. So that first you group things like now (really-really same solutions, different only in comments, spacing and var names). And then you count kind of index-of-difference, and group closest groups in upper-groups.

    To illustrate: solutions using range() vs xrange() or a+b vs b+a will be in different inner-groups, but in same outer-group.

    I know it must be a big thing, so it's more like "an idea you could consider to implement in some distant future", not an actual feature-request like "I do really want it" :)

  • Katzen_gott Avatar

    Hi. Python solution grouping is also not perfect.

    There are solutions, that are not grouped because of comments, what if all comments are cleaed for grouping?

    Other thing is that two solutions with different variables' names are not grouped. Is it possible to group them?

  • kvanberendonck Avatar

    The Haskell solutions grouping is kind of poor.

    Two solutions like (f (g x)) and (f $ g x) come up as different solutions, causing most of the first page to just be the same solution with alternating sets of $'s and ( )'s everywhere.

    The other thing I've noticed a lot of is that some users (inc. myself) put a linebreak after module ... where before they start the import list, whereas others do not. These are counting as two different solutions ...

    Perhaps desugaring (attempting to inline $) the Haskell and removing all whitespace would be a good way to test equivalence.

  • constablebrew Avatar

    I posted a long discussion on this yesterday: http://www.codewars.com/topics/feature-requests#52604d92594da0c37c0009ba

    I think the grouping should be as aggressive as possible. Tools to minify or, at the very least, format the code should be used where available. For languages that don't have any such tools would just be grouped as best as possible.

    The additional metrics available for complexity and lines of code have tools available for most languages. I doubt very many languages have tools that implement the maintainability index that I promote, so Code Wars would have to cobble together different code bases to produce that metric.

    Just googling around a bit, I found a couple open source options that could handle a number of options:

    http://cloc.sourceforge.net/#Languages

    http://saikuro.rubyforge.org/

    http://thegarywilson.com/blog/2006/cyclomatic-complexity-for-python-code/

    http://www.locmetrics.com/alternatives.html

  • vas3a Avatar

    I hope it's the right place to post this. Can you show more solutions on the kata's solution page? It's kind of annoying to not be able to see the latest solutions. I want to post simple and elegant solutions (after spending time on refactoring the older ones), but I am not able to do this, because my solution will never be visible to anyone.

    Maybe a quick fix is to remove all the invalid kata solutions. For example, on this page http://www.codewars.com/dojo/katas/51675d17e0c1bed195000001/javascript half of them are invald solutions.

  • JoshBrodieNZ Avatar

    Kind of belongs here, kind of about upvoting. I'm wondering what user participation is like in situations where solutions diverge so greatly as to fill the page? I try to vote for the solutions I like but at a certain point the length becomes prohibitive and what might be very nice solutions go unobserved.

    I would love for some automatic pre-arrangement to be taking place, probably by performance because I imagine it the easiest test to automate, while style, elegance and clarity are better suited to judgement by vote.

  • constablebrew Avatar

    Each language is so different and the potential tools available to group solutions are so different from one language to the next, that I don't think it really would be possible to have a one-size-fits-all-languages solution. Probably the best we could do is to define the different ways in which code could be grouped:

    Clarity: How readily the code is understood
    Performance: How quickly the code performs the intended task. (Would probably require benchmarking or some way to generate the big O notation.)
    Innovation/Elegance: How inspirational the design is, making use of language features in graceful ways where naive solutions look more like a hammer was used to solve everything.

  • jhoffner Avatar

    There has been some talk about using minification which would work for js and coffeescript. I'm unaware of any kind of ruby minification library (why would there be one after all). I would prefer to find a solution that works across all languages, including those we intend to support (such as Python, Scala, Clojure, Java, C#, Objective C, etc). If we diverge too much in how solutions get grouped then it could fragment the experience. For example, maybe one solution is better than another even though they are essentially the same, because one user used bad naming conventions and the other didn't.

    Thoughts?