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

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.
add(X, Y, R) :- R is X + Y + 1.
add(X, Y, R) :- R is X + Y + 1.
Dates/Time
Data Types
Strings

You must display literally the difference between two dates textual

Exemple input howManyTimesBetween("1995-12-02 and 2010-01-05")
Will return "There are 14 year(s), 10 month(s), 8 day(s) between 1995-12-02 and 2010-01-05"

Constraints and permissions

If constraints are not respected, the function should return "Your question is strange"

  • The two dates can be inverted (the oldest can be at start or end), and will give the same gap between the twice dates
  • If there are no months/day/years gap. Don't display it in the sentence (exemple : howManyTimesBetween("2010-01-05 and 2010-01-10") will return "There are 5 day(s) between 1995-12-02 and 2010-01-05")
  • If the two date are the same, will return "Dates are equals"
  • The date format is Y-m-d (conforming to https://www.php.net/manual/fr/datetime.format.php). There is not hours or others
  • The sentence should always do "{date} and {date}"
  • The end of the response sentence will is the same than the input whatever the order of dates
function howManyTimesBetween(string $sentence): string
{
    $errorMessage = 'Your question is strange';
  
    $datesString = explode(' and ', $sentence);
  
    if (count($datesString) !== 2) {
      return $errorMessage;
    }
  
    $date1 = DateTime::createFromFormat('Y-m-d', $datesString[0]);
    $date2 = DateTime::createFromFormat('Y-m-d', $datesString[1]);
  
    if ($date1 === false or $date2 === false) {
        return $errorMessage;
    }
  
    $diffStrings = [];
  
    if ($date1 == $date2) {
        return 'Dates are equals';
    }
  
    $diff = $date1->diff($date2);
    
    if ($diff->y) {
        $diffStrings[] = $diff->y.' year(s)';
    }
    
    if ($diff->m) {
        $diffStrings[] = $diff->m.' month(s)';
    }
    
    if ($diff->d) {
        $diffStrings[] = $diff->d.' day(s)';
    }
  
    return 'There are '.implode(', ', $diffStrings).' between '.$sentence;
}
Lists
Data Structures
Numbers
Data Types
Functions
Control Flow
Basic Language Features
Fundamentals
Algorithms
Logic

Combination of List

Instructions

Below are Instructions for this Kumite.

Introduction

Given the two list or arrays, filter and combine the numbers into one list or arrays. There will only be numbers in the list.

Requirements

  • There will be no negative number in the list
  • The list must be ordered in ascending order.
  • There must be no repeating number in the list.
  • It must support an empty list.

Test Samples

Below are the test sample for this excercise


# Multiple list should be able to combine into one list
combine_list([1,2,3],[4,5,6])
> [1,2,3,4,5,6]
# Final list should be sorted
combine_list([3,2,1,5],[6,8,7])
> [1,2,3,5,6,7,8]
# There must be no repeating number in the list
combine_list([4,5,6],[7,7,8])
>[4,5,6,7,8]
# The will be no negative number in the list
combine_list([4,5,8],[99,0,11,665,-245])
> [0,4,5,8,11,99,665]
def combine_list(list1,list2):
    return list(set(list(filter(lambda c: (c > 0), list1 + list2))))