Start a new Kumite
AllAgda (Beta)BF (Beta)CCFML (Beta)ClojureCOBOL (Beta)CoffeeScriptCommonLisp (Beta)CoqC++CrystalC#D (Beta)DartElixirElm (Beta)Erlang (Beta)Factor (Beta)Forth (Beta)Fortran (Beta)F#GoGroovyHaskellHaxe (Beta)Idris (Beta)JavaJavaScriptJulia (Beta)Kotlinλ Calculus (Beta)LeanLuaNASMNim (Beta)Objective-C (Beta)OCaml (Beta)Pascal (Beta)Perl (Beta)PHPPowerShell (Beta)Prolog (Beta)PureScript (Beta)PythonR (Beta)RacketRaku (Beta)Reason (Beta)RISC-V (Beta)RubyRustScalaShellSolidity (Beta)SQLSwiftTypeScriptVB (Beta)
Show only mine

Kumite (ko͞omiˌtā) is the practice of taking techniques learned from Kata and applying them through the act of freestyle sparring.

You can create a new kumite by providing some initial code and optionally some test cases. From there other warriors can spar with you, by enhancing, refactoring and translating your code. There is no limit to how many warriors you can spar with.

A great use for kumite is to begin an idea for a kata as one. You can collaborate with other code warriors until you have it right, then you can convert it to a kata.

Ad
Ad
p4songervs.EPiphFailed Tests

Bonk

Probability
Statistics

Goal

Not really sure. But it looks like we're calculating the actual probability of a ruleset and comparing it to the calculated probability.

Fork 1

I changed the testing to use assert_approx_equals instead of assert_equals since the implementation was the same, and it makes testing more consistent. Added a zero to the range we're using to increase the odds we will match expected probability, and made a minor optimization to use a comprehension since we're iterating 100,000 times.

I also refactored the funtion to take our alternate ruleset, and run those rules if true. Can't get it to pass the tests though. It's something though.

Code
Diff
  • from random import randint
    
    
    playing_board = [0] * 100 # board is 100 positions long
    position = 0 # player starts at position 0 on the board
    while position < 100: # end when position moves off board
        playing_board[position] = 1 # player was here
        position += randint(1, 6) # throw a die and move
    
    # what's the probability that playing_board[n] == 1?
    # there is a prize if you land on position n
    # but a cost for playing the game
    # let's run N times
    
    def probability(other_rule=False):
        successes = [0] * 100
        if not other_rule:
            for n in range(100000): # maybe this isn't big enough # maybe it is now?
                playing_board = [0] * 100
                position = 0
                while position < 100:
                    successes[position] += 1
                    position += randint(1, 6)
            return [s / n for s in successes]
        
        # what if we add a rule
        # if the player lands on square 99, they teleport back to 0
        for n in range(100000):
            playing_board = [0] * 100 # board is 100 positions long
            position = 0 # player starts at position 0 on the board
            while position < 100: # end when position moves off board
                successes[position] += 1 # player was here
                position += randint(1, 6) # throw a die and move
                if position == 99: position = 0 # snakey snake
        return [s / n for s in successes]
        
    
    
    
    # can you calculate the probability of the prize now?
    • from random import randint
    • playing_board = [0] * 100 # board is 100 positions long
    • position = 0 # player starts at position 0 on the board
    • while position < 100: # end when position moves off board
    • playing_board[position] = 1 # player was here
    • position += randint(1, 6) # throw a die and move
    • # what's the probability that playing_board[n] == 1?
    • # there is a prize if you land on position n
    • # but a cost for playing the game
    • # let's run N times
    • def probability():
    • N = 10000 # maybe this isn't big enough
    • def probability(other_rule=False):
    • successes = [0] * 100
    • for _ in range(N):
    • playing_board = [0] * 100
    • position = 0
    • while position < 100:
    • successes[position] += 1
    • position += randint(1, 6)
    • ret = []
    • for s in successes:
    • ret.append(s / N)
    • return ret
    • if not other_rule:
    • for n in range(100000): # maybe this isn't big enough # maybe it is now?
    • playing_board = [0] * 100
    • position = 0
    • while position < 100:
    • successes[position] += 1
    • position += randint(1, 6)
    • return [s / n for s in successes]
    • # what if we add a rule
    • # if the player lands on square 99, they teleport back to 0
    • for n in range(100000):
    • playing_board = [0] * 100 # board is 100 positions long
    • position = 0 # player starts at position 0 on the board
    • while position < 100: # end when position moves off board
    • successes[position] += 1 # player was here
    • position += randint(1, 6) # throw a die and move
    • if position == 99: position = 0 # snakey snake
    • return [s / n for s in successes]
    • # what if we add a rule
    • # if the player lands on square 99, they teleport back to 0
    • playing_board = [0] * 100 # board is 100 positions long
    • position = 0 # player starts at position 0 on the board
    • while position < 100: # end when position moves off board
    • playing_board[position] = 1 # player was here
    • position += randint(1, 6) # throw a die and move
    • if position == 99: position = 0 # snakey snake
    • # can you calculate the probability of the prize now?
Fundamentals
Strings

The goal of this kumite is to separate each adjacient pair of characters in the original string by an additional space (' ') character.

Original

Used std::accumulate to achieve this

Fork 1

  • if the string is empty, return empty string (next steps require the string to be nonempty)
  • preallocate a buffer of size 2*string.length()-1 filled with space characters
  • map each each character of original string from position i to position 2*i in the buffer
Code
Diff
  • #include <string>
    
    std::string digest(const std::string& str) {
      if(str.empty()) 
        return "";
      std::string buff (str.size()*2-1, ' ');
      for(std::size_t i = 0; i < str.size(); ++i)
        buff[2*i] = str[i];
      return buff;
    }
    • #include <string>
    • #include <numeric>
    • std::string digest(const std::string& param) {
    • return param.empty()?
    • param
    • : std::accumulate(std::next(param.cbegin()),param.cend(),
    • std::string(1,param[0]),
    • [](auto &s, auto c) {return s.append(" ").append(1,c);});
    • std::string digest(const std::string& str) {
    • if(str.empty())
    • return "";
    • std::string buff (str.size()*2-1, ' ');
    • for(std::size_t i = 0; i < str.size(); ++i)
    • buff[2*i] = str[i];
    • return buff;
    • }
Matrix

Goal

Write a function matrix() that takes a 2D array, an operation, a target location, and an optional write_data as an input.

def matrix(matrice=[[1,2,3],
                    [4,5,6],
                    [7,8,9]], operation="write", location=(0, 1), write_data=7)

Your function should catch any IndexError that occers. Return values should be:

  • if write: The new matrix, after adding write_data in the location given.
  • if read: The existing data at the requested location.
  • if neither: raise an AttributeError with any message.

Fork 1

Cleaned up some of the error checking to use best practices. Added testing for the error checking. Added random testing with basic matricies from numpy.

The random tests are honestly scuffed beyond belief. I've never worked with numpy before, and this is probably a bad first experience. I would love to see someone fix the mess that I've made lol... sorry in advance. I decided to cap the size of random tests at 100 since this isn't really meant to be a preformance type kumite. Ran a couple times and seems like a good upper limit imo.

Code
Diff
  • def matrix(matrice=list, operation=str, location=tuple, write_data=None):
        if operation == "read":
            try: 
                return matrice[location[0]][location[1]]
            except IndexError as e:
                print(e)
                return 0
        elif operation == "write":
            try:
                matrice[location[0]][location[1]] = write_data
                return matrice
            except IndexError as e:
                print(e)
                return 0
        else:
            raise AttributeError("That is not a valid operation for this system.")
    • def matrix(matrice=list, operation=str, location=tuple, writedata=None):
    • def matrix(matrice=list, operation=str, location=tuple, write_data=None):
    • if operation == "read":
    • try:
    • try:
    • return matrice[location[0]][location[1]]
    • except Exception as e:
    • except IndexError as e:
    • print(e)
    • return 0
    • elif operation == "write":
    • try:
    • matrice[location[0]][location[1]] = writedata
    • matrice[location[0]][location[1]] = write_data
    • return matrice
    • except Exception as e:
    • except IndexError as e:
    • print(e)
    • return 0
    • else:
    • raise OperationError("That is not a valid operation for this system.")
    • raise AttributeError("That is not a valid operation for this system.")

Goal

You are collecting data that fits a wave signal. Your must determine witch mathematical expression fits the signal. You will receive an array of numbers into your function called find_signal()

All numbers in the array will obey one of these expressions:
y = sin x,
y = cos x,
y = sin x + cos x

The given y values will always correspond to x input values of 0, 1, 2, ... n where n is the length of the array - 1. Your function will identify which signal is coming in and return string: 'sin x', 'cos x' or 'sin x + cos x'. Otherwise, None

All inputs will have at least 2 numbers to indicate a clear answer.

Fork 1

Removed duplicate tests. Added more precise floating point values instead of rounded numbers. (I think its best practice to avoid rounding where it is not absolutely necessary? Either way, it makes the random tests easier to build, and the actual code more accurate). Added random tests

In addition to what's above, I refactored pretty much the whole code to accept more than just 4 numbers. The random tests will give an array of size 2 <= n <= 1000. We start at 2 to avoid edge cases between cos, and sin + cos. I'm sure someone smarter than I could find a way to include those as well, but I think this is good enough for a pretty simple problem like this.

Code
Diff
  • import math as m
    def find_signal(wave): 
        sinx = ('sin x', [i for i in range(len(wave)) if wave[i] == m.sin(i)])
        cosx = ('cos x', [i for i in range(len(wave)) if wave[i] == m.cos(i)])
        cossin = ('sin x + cos x', [i for i in range(len(wave)) if wave[i] == m.cos(i) + m.sin(i)])
        final = max([sinx, cosx, cossin], key=lambda x : sum(x[1]))
        return final[0] if sum(final[1]) == sum([i for i in range(len(wave))]) else None
    
            
    • import math as m
    • def find_signal(s):
    • k=0; k1=0; k2=0
    • for i in range(4):
    • if s[i]==round(m.sin(i),2):
    • k=k+1
    • if k==4:
    • return('sin x')
    • if s[i]==round(m.cos(i),2):
    • k1=k1+1
    • if k1==4:
    • return('cos x')
    • if s[i]==round(m.cos(i)+m.sin(i),2):
    • k2=k2+1
    • if k2==4:
    • return('sin x + cos x')
    • def find_signal(wave):
    • sinx = ('sin x', [i for i in range(len(wave)) if wave[i] == m.sin(i)])
    • cosx = ('cos x', [i for i in range(len(wave)) if wave[i] == m.cos(i)])
    • cossin = ('sin x + cos x', [i for i in range(len(wave)) if wave[i] == m.cos(i) + m.sin(i)])
    • final = max([sinx, cosx, cossin], key=lambda x : sum(x[1]))
    • return final[0] if sum(final[1]) == sum([i for i in range(len(wave))]) else None
Code
Diff
  • const reverseStr = str => [...str].reverse().join('');
    • const reverseStr = str => str.split('').reverse().join('');
    • const reverseStr = str => [...str].reverse().join('');
Code
Diff
  • using System;
    
    namespace Solution
    {
      public class BlockBuilder
      {
        public static int[][] BuildATower(int[] bag)
        {
          return new int[][] {new int[] {1}}; // Code goes here ...
        }
      }
    }
    • using System;
    • namespace Solution
    • {
    • public class BlockBuilder
    • {
    • public static int[,] BuildATower(int[] bag)
    • public static int[][] BuildATower(int[] bag)
    • {
    • return new int[,] { { 1 } }; // Code goes here ...
    • return new int[][] {new int[] {1}}; // Code goes here ...
    • }
    • }
    • }

Compact, can't be taking up too much storage space!

Code
Diff
  • class Greeting:
        def __init__(self, name, rank=None, formal=False):
            self.name = name
            self.rank = rank
            self.formal = formal
            
        def __call__(self):
            return f'He{["y","llo"][self.formal]}, {[str(self.rank)+" ",""][self.rank is None or not self.formal]}{self.name}{chr(33+self.formal*13)}'
    • class Greeting:
    • def __init__(self, name, rank=None, formal=False):
    • self.name = name
    • self.rank = rank
    • self.formal = formal
    • def __call__(self):
    • if self.formal: return f'Hello,{" " + self.rank if self.rank is not None else ""} {self.name}.'
    • else: return f'Hey, {self.name}!'
    • return f'He{["y","llo"][self.formal]}, {[str(self.rank)+" ",""][self.rank is None or not self.formal]}{self.name}{chr(33+self.formal*13)}'

It will be faster, if you use bit operation

Code
Diff
  • class Calculator {
      
      public boolean isEven(int number) {
        return (number & 1) == 0;
      }
      
    }
    • class Calculator {
    • public boolean isEven(int number) {
    • return (number % 2) == 0;
    • return (number & 1) == 0;
    • }
    • }