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
Fundamentals
Games

Implement function for Rock Paper Scissors game, players submits his/her shape and cpu gets random draw between the 3 shapes, the two data are compared and winner is decided.

I'm in learning fundamental JavaScript phase, tried to challenge my self to comeup with the code from syntax I know up till now, this is why its probably so long, tried the switch statement, i also did it in if/else statement, but liked this switch way cause i could include the shapes of players in the alert msg.

I checked the code and it works, but somehow cant figure out how to setup 'Test Cases'section for it on this website, appreciate if you guys could let me know how to set test cases for it or any other suggestions about my long & probably stupid code.

let player;
let cpu;

const rpsGame = function (player, cpu) {
  player = prompt(`Rock Paper Scissors Game, which shape you go with:`);
  cpu = Math.trunc(Math.random() * 3 + 1);
  switch (player) {
    case 'Rock':
      if (cpu === 2)
        return alert(`CPU's Paper covers your ${player}: YOU LOOSE!!!`);
      if (cpu === 3)
        return alert(`Your ${player} crushes CPU's Scissors: YOU WIN!!`);
      if (cpu === 1)
        return alert(`Both players choose ${player}: ITS A TIE...!`);
      break;
    case 'Paper':
      if (cpu === 1)
        return alert(`Your ${player} covers CPU's Rock: YOU WIN!!`);
      if (cpu === 2)
        return alert(`Both players choose ${player}: ITS A TIE...!`);
      if (cpu === 3)
        return alert(`CPU's Scissors cuts your ${player}: YOU LOOSE!!!`);
      break;
    case 'Scissors':
      if (cpu === 1)
        return alert(`CPU's Rock crushes your ${player}: YOU LOOSE!!!`);
      if (cpu === 2)
        return alert(`Your ${player} cuts CPU's Paper: YOU WIN...!!`);
      if (cpu === 3)
        return alert(`Both players choose ${player}: ITS A TIE...!`);
      break;
    default:
      return alert(`Wrong! Please choose from Rock, Paper or Scissors`);
      break;
  }
};
Parsing
Algorithms
Logic
Strings
Data Types

Given an expression as a string, calculate its value. For example, given the string "1+2+3", return 6.

Order of operations should be respected: multiplication happens before addition.

Possible avenues for future exploration:

  • Adding support for subtraction and division
  • Stripping whitespace
  • Adding support for brackets
using System;
using System.Linq;

public class ArtihmeticParser
{
  public static int Evaluate(string input)
  {
    return input.Split("+").Select(EvaluateProduct).Aggregate(0,(a,b) => a+b);
  }
  
  private static int EvaluateProduct(string input)
  {
    return input.Split("*").Select(EvaluateInteger).Aggregate(1,(a,b) => a*b);
  }
  
  private static int EvaluateInteger(string input)
  {
    return int.Parse(input);
  }
}
#just woke up from a random dream where I had a student explained to me this very simple algorythm. 
#Seems pretty usless to me unless anybody can think of an actually use??
#crazy simple but the dream was so vivid I just had to put it down hahahaha
def power_rooter(num):
    total = 1
    while num > 1 and num//2 == num/2:
        num = num / 2
        total *= num
    return total
unit module Foo;
error-here

To Upper First

write a function that capitalize only the first letter of a string.

for example:
toUpperFirst "" == ""
toUpperFirst "finn the human" == "Finn the human"
toUpperFirst "alice" == "Alice"

module ToupperFirst where
    import Data.Char
    
    toUpperFirst ""    = ""
    toUpperFirst xs    = [toUpper (x) | x <- xs, x == head (xs)] ++ tail (xs)

This is the start of a linear series of kata for learning Python. In this kata, you have to print "Hello World" to the screen.

Hint: Use the return keyword!

Rate 8 kyu!

def hello_world():
    return "Hello World"
Dates/Time
Data Types

You have a starting time and duration of some activity and you have to find out if it fits in a given timeslot.

package com.codewars;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Optional;
import java.util.function.Predicate;

public class TimeSlotFinder {
  
  public boolean isSuitable(TimeSlot slot, String startTimeString, long durationInSecodns) {
		LocalDateTime startTime = LocalDateTime.parse(startTimeString);
		return Optional.of(slot)
				.filter(startsBefore(startTime))
				.filter(hasEnoughTimeLeftInSlot(startTime, durationInSecodns))
				.isPresent();
	}

	public Predicate<TimeSlot> startsBefore(LocalDateTime startTime) {
		return slot -> slot.startTime.isBefore(startTime) || slot.startTime.isEqual(startTime);
	}

	public Predicate<TimeSlot> hasEnoughTimeLeftInSlot(LocalDateTime startTime, long durationInSecodns) {
		return slot -> ChronoUnit.SECONDS.between(startTime, slot.endTime) >= durationInSecodns;
	}



  public static class TimeSlot {
		public final LocalDateTime startTime;
		public final LocalDateTime endTime;
		public final long durationInSeconds;

		public TimeSlot(String dateTimeString, long durationInSeconds) {
			this.startTime = LocalDateTime.parse(dateTimeString);
			this.endTime = startTime.plus(durationInSeconds, ChronoUnit.SECONDS);
			this.durationInSeconds = durationInSeconds;
		}
  }
}
Dates/Time
Data Types

You are given an array of dates. Your task is group the dates into seperate weeks. The week starts on Monday, and ends on Sunday.

example input

[
3/24/2021,
3/25/2021,
3/1/2021,
3/6/2021,
3/10/2021
]

expected output

[
[3/1/2021, 3/6/2021],
[3/10/2021],
[3/24/2021, 3/25/2021],
]

function groupByWeek(days) {
  var dates = days.map(a => new Date(a)).sort((a, b) => b - a);
  
  console.log(dates.map(a => (a.getMonth()+1) + "/" + a.getDate() + "/" + a.getFullYear()))

  var currentMonday = new Date();
  currentMonday.setDate(dates[0].getDate() - dates[0].getDay())
  
  var currentSunday = new Date()
  currentSunday.setDate(currentMonday.getDate() + 6);
  
  //console.log(firstMonday.getDay())
  //console.log(firstSunday.getDay())
  
  var weeks = []
  var currentWeek = []
  for(var date of dates) {
    if(date >= currentMonday && date <= currentSunday) {
      currentWeek.push((date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear())
    } else {
      if(currentWeek.length > 0) {
        weeks.push(currentWeek)
      }
      currentWeek = [(date.getMonth()+1) + "/" + date.getDate() + "/" + date.getFullYear()]
      currentMonday.setDate(date.getDate() - date.getDay())
      currentSunday.setDate(currentMonday.getDate() + 6);
    }
    
  }
  if(currentWeek.length > 0) {
    weeks.push(currentWeek)
  }
  
  return weeks
  
}

I wrote a basic polynomial class in C++ as a little exercise in user-defined literals.
I only inluded failing test cases because I think std::cout is the best way to show what is happening.

#include <map>
#include <sstream>
#include <cstdint>
#include <string>

                          // ( 1_x2 4_x1 4_x0 )
#define ALTERNATE_DISPLAY // ( 1x^2 4x^1 4x^0 )

class polynomial;
std::ostream &operator <<(std::ostream &lhs, polynomial rhs);

class polynomial
{
public:
    std::map<unsigned long long, double> coefficients;
    polynomial operator +(int rhs)
    {
        polynomial result(*this);
        int result_x0 = result.coefficients[0] += rhs;
        if (!result_x0)
        {
            result.coefficients.erase(0);
        }
        return result;
    }
    polynomial operator -(int rhs)
    {
        polynomial result(*this);
        int result_x0 = result.coefficients[0] -= rhs;
        if (!result_x0)
        {
            result.coefficients.erase(0);
        }
        return result;
    }
    polynomial operator *(int rhs)
    {
        polynomial result;
        for (std::pair<unsigned long long, double> const &term : this->coefficients)
        {
            result.coefficients[term.first] = rhs * term.second;
        }
        return result;
    }
    polynomial operator +(polynomial rhs)
    {
        polynomial result;
        for (std::pair<unsigned long long, double> const &term : this->coefficients)
        {
            result.coefficients[term.first] = term.second;
        }
        for (std::pair<unsigned long long, double> const &term : rhs.coefficients)
        {
            double &lhsx = this->coefficients[term.first];
            if (lhsx != -term.second)
            {
                result.coefficients[term.first] += term.second;
            }
            else
            {
                result.coefficients.erase(term.first);
            }
        }
        return result;
    }
    polynomial operator -(polynomial rhs)
    {
        polynomial result;
        for (std::pair<unsigned long long, double> const &term : this->coefficients)
        {
            result.coefficients[term.first] = term.second;
        }
        for (std::pair<unsigned long long, double> const &term : rhs.coefficients)
        {
            double &lhsx = this->coefficients[term.first];
            if (lhsx != term.second)
            {
                result.coefficients[term.first] -= term.second;
            }
            else
            {
                result.coefficients.erase(term.first);
            }
        }
        return result;
    }
    polynomial operator *(polynomial rhs)
    {
        polynomial result;
        for (std::pair<unsigned long long, double> const &term_i0 : this->coefficients)
        {
            for (std::pair<unsigned long long, double> const &term_i1 : rhs.coefficients)
            {
                result.coefficients[term_i0.first + term_i1.first] 
                    += term_i0.second * term_i1.second;
                std::cout << "    " << result << '\n';
            }
        }
        return result;
    }
};

polynomial operator ""_x(unsigned long long coefficient)
{
    polynomial result;
    if (coefficient)
    {
        result.coefficients[1] = coefficient;    
    }
    return result;
}

// I don't know how to make a user-defined literal that takes two arguments (like 1e9)
polynomial operator""_x0(unsigned long long coefficient){polynomial result;if(coefficient)result.coefficients[0]=coefficient;return result;}
polynomial operator""_x1(unsigned long long coefficient){polynomial result;if(coefficient)result.coefficients[1]=coefficient;return result;}
polynomial operator""_x2(unsigned long long coefficient){polynomial result;if(coefficient)result.coefficients[2]=coefficient;return result;}
polynomial operator""_x3(unsigned long long coefficient){polynomial result;if(coefficient)result.coefficients[3]=coefficient;return result;}
polynomial operator""_x4(unsigned long long coefficient){polynomial result;if(coefficient)result.coefficients[4]=coefficient;return result;}
polynomial operator""_x5(unsigned long long coefficient){polynomial result;if(coefficient)result.coefficients[5]=coefficient;return result;}
polynomial operator""_x6(unsigned long long coefficient){polynomial result;if(coefficient)result.coefficients[6]=coefficient;return result;}
polynomial operator""_x7(unsigned long long coefficient){polynomial result;if(coefficient)result.coefficients[7]=coefficient;return result;}
polynomial operator""_x8(unsigned long long coefficient){polynomial result;if(coefficient)result.coefficients[8]=coefficient;return result;}
polynomial operator""_x9(unsigned long long coefficient){polynomial result;if(coefficient)result.coefficients[9]=coefficient;return result;}
polynomial operator""_x10(unsigned long long coefficient){polynomial result;if(coefficient)result.coefficients[10]=coefficient;return result;}

polynomial pow(polynomial lhs, unsigned long long rhs)
{
    polynomial result = 1_x0;
    for (unsigned long long _0 = 0; _0 < rhs; ++_0)
    {
        result = result * lhs;
    }
    return result;
}

std::ostream &operator <<(std::ostream &lhs, polynomial rhs)
{
    lhs << "( ";
    for (auto x_it = rhs.coefficients.rbegin(); x_it != rhs.coefficients.rend(); ++x_it)
    {
        lhs << x_it->second 
#ifndef ALTERNATE_DISPLAY
            << "_x" << x_it->first << ' ';
#else
            << (x_it->first ? "x" : "") << (x_it->first > 1 ? "^" + std::to_string(x_it->first) : "") << ' ';
#endif
    }
    lhs << ')'; 
    return lhs;
}
add(X, Y, R) :- R is X + Y.
add0(_, _, _).
add_or_sub(X, Y, R) :- R is X + Y; R is X - Y.