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
Code
Diff
  • f=numMinusSeven
    
        =(__,_=___)=>
    
           _?f(--__,--_):__
    • const numMinusSeven = num => num - 7;
    • f=numMinusSeven
    • =(__,_=___)=>
    • _?f(--__,--_):__

public async Task CreateUser(User userInput)
{
var validUserTypes = new string[] { "regular", "premium", "trial" };

if (!validUserTypes.Contains(userInput.UserType))
{
    throw new ArgumentOutOfRangeException(
        nameof(userInput.UserType),
        "Invalid user type. Must be one of: " + string.Join(", ", validUserTypes)
    );
}

User user = userInput.UserType switch
{
    "regular" => new User(userInput.Username),
    "premium" => new User(userInput.Username, new List<Permission>
    {
        "PremiumFeature.Read",
        "PremiumFeature.Create"
    })
    {
        IsPremium = true
    },
    "trial" => new User(userInput.Username) { IsOnTrial = true },
    _ => throw new ArgumentOutOfRangeException(
        nameof(userInput.UserType),
        "Invalid user type. Must be one of: " + string.Join(", ", validUserTypes)
    )
};

return await repository.CreateAsync(user);

}

Code
Diff
  • public async Task<bool> CreateUser(User userInput)
    {
        var validUserTypes = new string[] { "regular", "premium", "trial" };
    
        if (!validUserTypes.Contains(userInput.UserType))
        {
            throw new ArgumentOutOfRangeException(
                nameof(userInput.UserType),
                "Invalid user type. Must be one of: " + string.Join(", ", validUserTypes)
            );
        }
    
        User user = userInput.UserType switch
        {
            "regular" => new User(userInput.Username),
            "premium" => new User(userInput.Username, new List<Permission>
            {
                "PremiumFeature.Read",
                "PremiumFeature.Create"
            })
            {
                IsPremium = true
            },
            "trial" => new User(userInput.Username) { IsOnTrial = true },
            _ => throw new ArgumentOutOfRangeException(
                nameof(userInput.UserType),
                "Invalid user type. Must be one of: " + string.Join(", ", validUserTypes)
            )
        };
    
        return await repository.CreateAsync(user);
    }
    
    • public async Task<bool> CreateUser(User userInput) {
    • var validUserTypes = new string[] {"regular", "premium", "trial"} ;
    • var user = userInput.UserType switch {
    • "regular" => new User(userInput.Username),
    • "premium" => new User(userInput.Username,
    • new List<Permission> {
    • "PremiumFeature.Read",
    • "PremiumFeature.Create",
    • }){IsPremium = true},
    • "trial" => new User(input.Username) {
    • IsOnTrial = true
    • },
    • _ => new ArgumentOutOfRangeException(
    • "Invalid user type. Must be on of the following {string.Join(" ")"
    • nameof(input.usertype))
    • };
    • public async Task<bool> CreateUser(User userInput)
    • {
    • var validUserTypes = new string[] { "regular", "premium", "trial" };
    • if (!validUserTypes.Contains(userInput.UserType))
    • {
    • throw new ArgumentOutOfRangeException(
    • nameof(userInput.UserType),
    • "Invalid user type. Must be one of: " + string.Join(", ", validUserTypes)
    • );
    • }
    • User user = userInput.UserType switch
    • {
    • "regular" => new User(userInput.Username),
    • "premium" => new User(userInput.Username, new List<Permission>
    • {
    • "PremiumFeature.Read",
    • "PremiumFeature.Create"
    • })
    • {
    • IsPremium = true
    • },
    • "trial" => new User(userInput.Username) { IsOnTrial = true },
    • _ => throw new ArgumentOutOfRangeException(
    • nameof(userInput.UserType),
    • "Invalid user type. Must be one of: " + string.Join(", ", validUserTypes)
    • )
    • };
    • return await repository.CreateAsync(user);
Strings
Cryptography
Code
Diff
  • eval(compile((_:=__import__("ast")).fix_missing_locations(_.Module(body=[_.Import(names=[_.alias(name='string')]), _.Assign(targets=[_.Name(id='ceasar', ctx=_.Store())], value=_.Lambda(args=_.arguments(posonlyargs=[], args=[_.arg(arg='s'), _.arg(arg='n')], kwonlyargs=[], kw_defaults=[], defaults=[]), body=_.Call(func=_.Attribute(value=_.Constant(value=''), attr='join', ctx=_.Load()), args=[_.ListComp(elt=_.Name(id='c', ctx=_.Load()), generators=[_.comprehension(target=_.Name(id='c', ctx=_.Store()), iter=_.Call(func=_.Name(id='map', ctx=_.Load()), args=[_.Lambda(args=_.arguments(posonlyargs=[], args=[_.arg(arg='c')], kwonlyargs=[], kw_defaults=[], defaults=[]), body=_.IfExp(test=_.BoolOp(op=_.Or(), values=[_.Compare(left=_.Name(id='c', ctx=_.Load()), ops=[_.In()], comparators=[_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load()))]), _.BoolOp(op=_.And(), values=[_.Compare(left=_.Name(id='c', ctx=_.Load()), ops=[_.In()], comparators=[_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load()))]), _.Call(func=_.Attribute(value=_.Name(id='c', ctx=_.Load()), attr='islower', ctx=_.Load()), args=[], keywords=[])])]), body=_.Subscript(value=_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load())), slice=_.BinOp(left=_.Call(func=_.Name(id='ord', ctx=_.Load()), args=[_.Name(id='c', ctx=_.Load())], keywords=[]), op=_.Sub(), right=_.Constant(value=97)), ctx=_.Load()), orelse=_.IfExp(test=_.BoolOp(op=_.Or(), values=[_.Compare(left=_.Name(id='c', ctx=_.Load()), ops=[_.In()], comparators=[_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load()))]), _.BoolOp(op=_.And(), values=[_.Compare(left=_.Name(id='c', ctx=_.Load()), ops=[_.In()], comparators=[_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load()))]), _.Call(func=_.Attribute(value=_.Name(id='c', ctx=_.Load()), attr='isupper', ctx=_.Load()), args=[], keywords=[])])]), body=_.Subscript(value=_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load())), slice=_.BinOp(left=_.Call(func=_.Name(id='ord', ctx=_.Load()), args=[_.Name(id='c', ctx=_.Load())], keywords=[]), op=_.Sub(), right=_.Constant(value=65)), ctx=_.Load()), orelse=_.Name(id='c', ctx=_.Load())))), _.Name(id='s', ctx=_.Load())], keywords=[]), ifs=[], is_async=0)])], keywords=[])))], type_ignores=[])), "", "exec"))
    
    • def ceasar(string, pos):
    • bet = 'abcdefghijklmnopqrstuvwxyz'
    • new = bet[pos:] + bet[:pos]
    • word = ''
    • for char in string:
    • if char.lower() in bet: word += new[bet.index(char.lower())].upper() if char.isupper() else new[bet.index(char)]
    • else: word += char
    • return word
    • eval(compile((_:=__import__("ast")).fix_missing_locations(_.Module(body=[_.Import(names=[_.alias(name='string')]), _.Assign(targets=[_.Name(id='ceasar', ctx=_.Store())], value=_.Lambda(args=_.arguments(posonlyargs=[], args=[_.arg(arg='s'), _.arg(arg='n')], kwonlyargs=[], kw_defaults=[], defaults=[]), body=_.Call(func=_.Attribute(value=_.Constant(value=''), attr='join', ctx=_.Load()), args=[_.ListComp(elt=_.Name(id='c', ctx=_.Load()), generators=[_.comprehension(target=_.Name(id='c', ctx=_.Store()), iter=_.Call(func=_.Name(id='map', ctx=_.Load()), args=[_.Lambda(args=_.arguments(posonlyargs=[], args=[_.arg(arg='c')], kwonlyargs=[], kw_defaults=[], defaults=[]), body=_.IfExp(test=_.BoolOp(op=_.Or(), values=[_.Compare(left=_.Name(id='c', ctx=_.Load()), ops=[_.In()], comparators=[_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load()))]), _.BoolOp(op=_.And(), values=[_.Compare(left=_.Name(id='c', ctx=_.Load()), ops=[_.In()], comparators=[_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load()))]), _.Call(func=_.Attribute(value=_.Name(id='c', ctx=_.Load()), attr='islower', ctx=_.Load()), args=[], keywords=[])])]), body=_.Subscript(value=_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load())), slice=_.BinOp(left=_.Call(func=_.Name(id='ord', ctx=_.Load()), args=[_.Name(id='c', ctx=_.Load())], keywords=[]), op=_.Sub(), right=_.Constant(value=97)), ctx=_.Load()), orelse=_.IfExp(test=_.BoolOp(op=_.Or(), values=[_.Compare(left=_.Name(id='c', ctx=_.Load()), ops=[_.In()], comparators=[_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_lowercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load()))]), _.BoolOp(op=_.And(), values=[_.Compare(left=_.Name(id='c', ctx=_.Load()), ops=[_.In()], comparators=[_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load()))]), _.Call(func=_.Attribute(value=_.Name(id='c', ctx=_.Load()), attr='isupper', ctx=_.Load()), args=[], keywords=[])])]), body=_.Subscript(value=_.BinOp(left=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(lower=_.Name(id='n', ctx=_.Load())), ctx=_.Load()), op=_.Add(), right=_.Subscript(value=_.Attribute(value=_.Name(id='string', ctx=_.Load()), attr='ascii_uppercase', ctx=_.Load()), slice=_.Slice(upper=_.Name(id='n', ctx=_.Load())), ctx=_.Load())), slice=_.BinOp(left=_.Call(func=_.Name(id='ord', ctx=_.Load()), args=[_.Name(id='c', ctx=_.Load())], keywords=[]), op=_.Sub(), right=_.Constant(value=65)), ctx=_.Load()), orelse=_.Name(id='c', ctx=_.Load())))), _.Name(id='s', ctx=_.Load())], keywords=[]), ifs=[], is_async=0)])], keywords=[])))], type_ignores=[])), "", "exec"))
Strings
Big Integers
Code
Diff
  • /*
    
      __uint128_t solution(char *str1, char *str2) {
        return *(uint64_t *)str1 | ( (__uint128_t) *(uint64_t *)str2 << 64 );
      }
    
      48 8b 07  mov rax, [rdi]
      48 8b 16  mov rdx, [rsi]
      c3        ret
    
    */
    
    const long solution = 54912407923297096;
    
    • __uint128_t solution(char* str1, char* str2) {
    • __uint128_t result = 0;
    • for (unsigned long i = 0; i < 7; ++i) {
    • result +=
    • (((__uint128_t) str1[i]) << (8*(i + 0))) +
    • (((__uint128_t) str2[i]) << (8*(i + 8)));
    • /*
    • __uint128_t solution(char *str1, char *str2) {
    • return *(uint64_t *)str1 | ( (__uint128_t) *(uint64_t *)str2 << 64 );
    • }
    • return result;
    • }
    • 48 8b 07 mov rax, [rdi]
    • 48 8b 16 mov rdx, [rsi]
    • c3 ret
    • */
    • const long solution = 54912407923297096;
Strings

Goal

Get dice roll results from multiple dice of the same type.

Dice notation

Dice are entered as strings such as "2d6" where the first number indicates the quantity of dice thrown and the last number indicates the number of sides on the dice. Assume input is "XdN" where 1 <= X <= 250 and <= N <= 5000

e.g. "2d6" means 2 dice are thrown. Each dice is a 6 sided dice with values 1-6.
2d6 should have results such as [2,5] or [1,6] or [3,3]

e.g. 3d500 (after setting random.seed(444) should result in [159,148,7]

Fork 1

Solved the problem, and added random testing. Currently the random tests will use any dice noted here and then each multiple of 50 above that.Calculating which number

Code
Diff
  • import random
    def roll_dice(dice):
        return [random.randint(1, int(dice[dice.index('d') + 1:])) for _ in range(int(dice[:dice.index('d')]))]
    
    • import random
    • def roll_dice(dice_text:str):
    • #this returns the correct value for roll_dice("2d1000")
    • return [random.randint(1,1000), random.randint(1,1000)]
    • def roll_dice(dice):
    • return [random.randint(1, int(dice[dice.index('d') + 1:])) for _ in range(int(dice[:dice.index('d')]))]

Goal

write a function that will return the integer of a string evaluation. Your function should catch any errors related to this process. If it does catch and error, it should return a string: "Invalid Input"

Fork 1

Added testing, and error checking. I think random tests should cover all realistic inputs that don't try to intentionally break the function. For example, KeyError would be pretty easy to create here, but why would you put something as complicated as a dictionary into this function without already knowing the keys?

Code
Diff
  • def calc(string):
        try: return int(eval(string))
        except (NameError, SyntaxError, TypeError, ValueError, ZeroDivisionError) as e:
            print(e)
            return 'Invalid Input'
    
    • def calc(string):
    • return int(eval(string))
    • try: return int(eval(string))
    • except (NameError, SyntaxError, TypeError, ValueError, ZeroDivisionError) as e:
    • print(e)
    • return 'Invalid Input'
Puzzles

Story

The pandemic has spread to all countries of the world, and Berland is no exception. Even at the All-Berland Olympiad in Computer Science, antiviral measures were introduced. In total, n people participate in the Olympiad, and in order to comply with all the instructions of the management, the Olympiad jury decided to invite participants to the tour one at a time with an interval of x minutes. Thus, the first participant will start the tour at time 0, the second participant will start the tour at time x, the third — at time 2x and so on.
Despite the different start times, the duration of the tour for each participant is exactly t minutes. Because of this, some participants finish writing the tour before the rest. When a participant finishes writing a tour, the amount of dissatisfaction with the organization of the Olympiad for this participant is equal to the number of other participants who are currently still writing or just starting to write a tour, but have not finished it yet.

Goal

Help the organizers of the Olympiad to find out what the total dissatisfaction of all participants of the Olympiad is equal to.

Input:

A single integer n is entered in the first line 1<=n<=2 * 10^9 — the number of participants of the Olympiad.
A single integer x is entered in the second line 1<=x<=2 * 10^9 — the interval in minutes between the start times of the tour for participants.
In the third line, a single integer t is entered 1<=t<=2 * 10^9 — duration of the tour.

Output:

In a single line, return one number — the total dissatisfaction of all participants of the Olympiad.

Examples

def satisfaction(4, 2, 5)  -->  5

def satisfaction(3, 1, 2)  -->  3

def satisfaction(3, 3, 10)  -->  3

  • In the first example , the first participant will start writing the tour at time 0 and finish at time 5. By this time, the second and third participants will already start writing the tour, so the dissatisfaction of the first participant will be equal to 2. The second participant will start writing at time 2 and finish at time 7. By this point, the third and fourth participants will already start writing the tour, so the dissatisfaction of the second will be equal to 2. The third participant will start writing the tour at time 4 and finish at time 9. By this time, the fourth participant will already start writing the tour, so the dissatisfaction of the third will be equal to 1. The fourth participant will start writing the tour at time 6 and finish at time 11. At time 9 no one will write a tour anymore, so the dissatisfaction of the fourth will be equal to 0. Thus, the total dissatisfaction of all participants will be equal to 2+2+1+0=5.

  • In the second example , the first participant will start writing the tour at time 0 and finish at time 2. By this point, the second participant will already be writing the tour, and the third participant will just start at time 2. Therefore , the dissatisfaction of the first participant will be equal to 2. The second participant will start at time 1and finish at time 3. By this point, only the third participant will still be writing the tour. Thus, the total dissatisfaction of all participants will be equal to 2+1=3.

Fork 1

I think I met the bid here. I wrote some edge cases that you should check to make sure that they follow the rules as well, but I've been treating all comparisons as <= since you said:

currently still writing or just starting to write a tour, but have not finished it yet.

Either way, really fun challenge! If this is looking good for you, just add some random tests and this will be ready for a kata IMO. This was a really fun puzzle to figure out because it's not just math that helps you get to the right solution, but clever coding logic as well. This would be a really fun kata when you're satisfied... get it?

Code
Diff
  • def satisfaction(n, x, t):
        start_times = [i * x for i in range(n)]
        finish_times = [(i * x) + t for i in range(n)]
        upset_factor = 0
        
        for i, writer in enumerate(finish_times):
            for j, others in enumerate(start_times):
                if others <= writer and i < j:
                    upset_factor += 1
        print(start_times, finish_times)
        return upset_factor
    
    • def qwerty(n, x, t):
    • time_finish_before_start = t + x * (n - 1)
    • time_start_before_finish = t + x * (n - 2)
    • dissatisfaction_finish_before_start = min(n - 1, time_finish_before_start // x)
    • dissatisfaction_start_before_finish = max(0, n - 2 - dissatisfaction_finish_before_start)
    • total_dissatisfaction = dissatisfaction_finish_before_start * dissatisfaction_start_before_finish
    • return total_dissatisfaction
    • def satisfaction(n, x, t):
    • start_times = [i * x for i in range(n)]
    • finish_times = [(i * x) + t for i in range(n)]
    • upset_factor = 0
    • for i, writer in enumerate(finish_times):
    • for j, others in enumerate(start_times):
    • if others <= writer and i < j:
    • upset_factor += 1
    • print(start_times, finish_times)
    • return upset_factor