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

Create a function to return True if the number is even and False if odd.

e.g. check_even(2) => True, check_even(9) => False

check_even = lambda x: x%2==0
Fundamentals
Puzzles
Games

Your task is to find the minimum SQUARE area in which you can place two identical rectangles. The sides of the rectangles should be parallel to the sides of the square.

  • You are given two identical rectangles with side lengths a and b with 1 <= a, b <= 100.
  • Find the square with minimum area that contains both given rectangles. Rectangles can be rotated (both or just one) and moved, but the sides of the rectangles should be parallel to the sides of the desired square.
def minimal_square(a, b):
    return max(min(a, b)*2, max(a, b))**2

Given an integer array and an positive integer variable, find the maximum or largest product you get after multiplying it by the elements in the array.

Input: arr = {1,2,3};
num = 3;
Output: 6
Because, 3 * 2 = 6

class Kata1 {
  public static int maxPairProduct(int[] arr, int num) {
    //Never Gonna Give You Up, Never Gonna Let You Down, Never Gonna Run Around And Desert You!
    
  }
}
Strings
Data Types
split
Haskell Packages

Basics

Verlan is a type of argot in the french language and is common in slang and youth language.
It rests on a long french tradition of transposing syllables of individual words to create slang words.
The word itself is an example for verlan.

Task

In this example you will create a function that takes a word and makes a verlan word out of it.

e.g.

  • Maestro => Stromae
  • Verlan => Lanver
function maestroSplit(string) {
  let newWord = string.slice(parseInt(string.length / 2)) + string.slice(0, parseInt(string.length / 2));
  return newWord.toLowerCase().charAt(0).toUpperCase() + newWord.toLowerCase().slice(1);
}

Given the following numbers:

100 75 50 25 6 3

and the following operators:

(*) (-) (+) (/)

build an Expression, that yields 952 when it is evaluated (evaluate applies all the operators bottom - up)

Doubles are used for convenience, number is rounded and checked against an integer to mitigate floating point error that might accumulate.

module Example (solve, Expression(Value, Expr)) where

data Expression = Value Double | Expr Expression (Double -> Double -> Double) Expression

solve :: [Double] -> Expression
--solve = undefined


--- my brute-force solution
solve xs = head . filter validate . allExpressions os . allOrders $ xs
  where os = getPermutationsAtDepth (length xs - 1) ops

evaluate :: Expression -> Double
evaluate (Value x) = x
evaluate (Expr i o j) = (evaluate i) `o` (evaluate j)

validate :: Expression -> Bool
validate = (==952) . round . evaluate

-- ok because all the numbers are unique
removed :: Eq a => a -> [a] -> [a]
removed x = filter (/=x)

allOrders :: Eq a => [a] -> [[a]]
allOrders [x] = [[x]]
allOrders xs = concat [ [ x:ns | ns <- allOrders (removed x xs)] | x <- xs]


ops = [(*), (-), (+), (/)] :: [Op]
type Op = Double -> Double -> Double

data NodeTree a = Node a [NodeTree a] | Leaf a deriving (Show)

genTree :: a -> [a] -> Int -> NodeTree a
genTree root es 1     = Node root (map Leaf es)
genTree root es depth = Node root (map (\x -> genTree x es (depth-1)) es)

getPaths :: NodeTree a -> [[a]]
getPaths (Leaf x)    = [[x]]
getPaths (Node r xs) = concat [ [ r:t | t <- getPaths c] | c <- xs]

getPermutationsAtDepth :: Int -> [a] -> [[a]]
getPermutationsAtDepth 1     xs = [xs]
getPermutationsAtDepth depth xs = concat . map getPaths . map (\x -> genTree x xs d) $ xs where d = depth - 1

toExpression :: [Op] -> [Double] -> Expression
toExpression _  []             = error "should not be more operators than values!"
toExpression [] [e]            = Value e
toExpression (o:os) (e:es) = Expr (Value e) o (toExpression os es)

allExpressions :: [[Op]] -> [[Double]] -> [Expression]
allExpressions os es = [toExpression o e | o <- os, e <- es]

Write a function that will solve a 9x9 Sudoku puzzle. The function will take one argument consisting of the 2D puzzle array, with the value 0 representing an unknown square.

The Sudokus tested against your function will be "easy" (i.e. determinable; there will be no need to assume and test possibilities on unknowns) and can be solved with a brute-force approach.

For Sudoku rules, see the Wikipedia article.


const int sudoku[9][9] = {
  {0,0,0,0,0,0,6,0,0},
  {0,0,0,0,0,7,0,0,1},
  {2,0,8,0,0,0,0,4,0},
  {6,0,0,0,0,0,0,0,0},
  {0,5,1,4,0,9,0,0,0},
  {0,0,0,5,0,0,0,2,0},
  {0,0,4,0,0,0,0,5,0},
  {0,0,7,1,9,6,0,0,0},
  {0,8,0,0,0,0,3,0,0},
};

#include <stddef.h>
typedef int (*T)[9];
T solve (const T sudoku) {
   /* Write your code here */
  return NULL;
}

test

public class test{
public void testSomething(){
  
  

}
  }

Recovering a type as a string, working with GCC, Clang & MSVC.

getTypeStr<const int*>() // Returns "const int*"
getTypeStr<decltype("Hello world!")>() // Returns "const char (&)[13]"

Each type string may vary according to the compiler's formatting style.

template <typename T>
constexpr std::string_view getTypeStr() noexcept {
#if defined(__clang__)
  // Has the form "std::string_view getTypeStr() [T = ...]"

  constexpr std::string_view funcSignature = __PRETTY_FUNCTION__;
  constexpr std::size_t startStride        = std::size("std::string_view getTypeStr() [T = ") - 1;

  return std::string_view(funcSignature.data() + startStride, funcSignature.size() - startStride - 1);

  // The following implementation would be ideal, but can't be resolved at compile-time (yet?)
  // See: https://stackoverflow.com/questions/56484834/constexpr-stdstring-viewfind-last-of-doesnt-work-on-clang-8-with-libstdc

//  constexpr std::size_t firstPos = funcSignature.find_first_of('=');
//  static_assert(firstPos != std::string_view::npos, "Error: Character '=' not found in the function's signature.");
//
//  constexpr std::size_t lastPos = funcSignature.find_last_of(']');
//  static_assert(lastPos != std::string_view::npos, "Error: Character ']' not found in the function's signature.");
//
//  static_assert(firstPos < lastPos, "Error: Trailing character found before leading one in the function's signature.");
//
//  return std::string_view(funcSignature.data() + firstPos + 2, lastPos - firstPos - 2);
#elif defined(__GNUC__)
  // Has the form "constexpr std::string_view getTypeStr() [with T = ...; std::string_view = std::basic_string_view<char>]"

  constexpr std::string_view funcSignature = __PRETTY_FUNCTION__;

  constexpr std::size_t firstPos = funcSignature.find_first_of('=');
  static_assert(firstPos != std::string_view::npos, "Error: Character '=' not found in the function's signature.");

  constexpr std::size_t lastPos = funcSignature.find_first_of(';', firstPos);
  static_assert(lastPos != std::string_view::npos, "Error: Character ';' not found in the function's signature.");

  static_assert(firstPos < lastPos, "Error: Trailing character found before leading one in the function's signature.");

  return std::string_view(funcSignature.data() + firstPos + 2, lastPos - firstPos - 2);
#elif defined(_MSC_VER)
  // Has the form "class std::basic_string_view<char,struct std::char_traits<char> > __cdecl getTypeStr<...>(void) noexcept"

  constexpr std::string_view funcSignature = __FUNCSIG__;

  constexpr std::size_t startStride = std::size("class std::basic_string_view<char,struct std::char_traits<char> > __cdecl getTypeStr<") - 1;
  constexpr std::size_t endStride   = std::size(">(void) noexcept") - 1;

  return std::string_view(funcSignature.data() + startStride, funcSignature.size() - startStride - endStride);

  // The following implementation would be ideal, but can't be resolved at compile-time because of a bug fixed only recently
  // See: https://developercommunity.visualstudio.com/content/problem/331234/stdbasic-string-viewfind-is-not-always-constexpr.html

//  constexpr std::string_view funcName = __FUNCTION__;
//
//  constexpr std::size_t firstPos = funcSignature.find(funcName);
//  static_assert(firstPos != std::string_view::npos, "Error: Function name not found in the function's signature.");
//
//  constexpr std::size_t lastPos = funcSignature.find_last_of('>');
//  static_assert(lastPos != std::string_view::npos, "Error: Character '>' not found in the function's signature.");
//
//  static_assert(firstPos < lastPos, "Error: Trailing character found before leading one in the function's signature.");
//
//  return std::string_view(funcSignature.data() + firstPos + funcName.size(), lastPos - firstPos - funcName.size());
#else
  static_assert(false, "Error: The current compiler is not supported.");
#endif
}

Now you are going to make a simple calculator.
The expression will be like this: n {symbol} m = {return value};

Example:
int result = calculate(4, 5, +); // 4 + 5 = 9;

Symbols are +, -, *.

public class calculator {
  public static int calculate(int n, int m, char symbol) {
    // do your best :)
    int result = 0;
    switch(symbol) {
        case '+':
      result = n + m;
      break;
        case '-':
      result = n - m;
      break;
        case '*':
      result = n * m;
      break;
    }
  return result;
  }
}

Mindbend is BF with extra steps.

What if BF had named registers? More operations? What if we fused that with assembly?

This is Mindbend, a silly little interpreter I made in an hour or two killing time on a Friday at school.

Basic rundown

There are 26 registers, a - z.
Each register is a 32-bit integer.

Commands

Keep in mind this notation:

  • R is a register
  • N is a number
  • M is either
  • C is a condition
  • * represents an unfinished instruction

Here's the arithmetic:

  • !RM moves M into R
  • +RM is R += M (addition)
  • -RM is R -= M (subtraction)
  • *RM is R *= M (multiplication)
  • /RM is R /= M (integer division)
  • %RM is R %= M (modulo)

Handling I/O:

  • .R print out the value of R as a number
  • ;R print out the value of R as a character (unicode codepoint)
  • ,R accept one input character into R
  • #R read the input as a number, consuming the most amount of characters that creates a proper number
  • _ take and discard an input character
  • 'M seek to M in the input
  • |R store the length of the input in R

Conditions:

  • M=M if M == M
  • M!M if M != M
  • M>M if M > M
  • M<M if M < M

Control structures:

  • iC[ ... ] if C is true, then do what's inside, otherwise skip past ]
  • wC[ ... ] while C is true, do what's inside, otherwise skip past ]

Examples

#a*a2.a Read a number from input, double, and output

#a_#b+ab.a Read two numbers delimited by a non-number character, add, and output

#bwa<b[.a+a1] Read a number from the input and output every number from 0 to 1 less than it, e.g. if you pass in 10, the output will be 0123456789

An example with a breakdown

Here's the last example with a breakdown, using comments (:):

#b    : Take a number from the input
wa<b[ : While a < b
.a    : Add a to output
+a1   : Add 1 to a
]     : End of while block
module Mindbend
	class Parser
		getter registers : Hash(Char, Int32)
		getter program : String = ""
		getter position : Int32 = 0
		getter input : String = ""
		getter output : String = ""
		getter input_position = 0
		getter loop_pairs = [] of Tuple(Int32, Int32)
    
    def reset
      @program = ""
      @position = 0
      @input = ""
      @input_position = 0
      @output = ""
      @loop_pairs = [] of Tuple(Int32, Int32)
      ('a'..'z').each { |char| @registers[char] = 0 }
    end

		def initialize()
			@registers = {} of Char => Int32
		end
    
    def load_program(program)
      reset
      @program = program
    end

		def quick_run(program, input)
			reset
			@program = program
			run(input)
			@output
		end

		def run(input)
			@input = input
			while @position < @program.size
				read_instruction
			end
		end

		def read_char
			char = @program[@position]?
			@position += 1
			char
		end

		def read_char!
			read_char.not_nil!
		end

		def read_register
			char = read_char!
			raise Exception.new("#{char} is not a register") unless ('a'..'z').includes? char
			char
		end

		def read_number
			number_string = ""
			loop do
				char = read_char!
				if number_string == "" && char == '-'
					number_string += '-'
				elsif ('0'..'9').includes? char
					number_string += char
				else
					@position -= 1
					break
				end
			end
			raise Exception.new("Invalid number") if number_string == ""
			number_string.to_i32
		end

		def read_number_from_input
			number_string = ""
			loop do
				char = @input[@input_position]?
				@input_position += 1
				if number_string == "" && char == '-'
					number_string += '-'
				elsif char.nil?
					break
				elsif ('0'..'9').includes? char
					number_string += char
				else
					@input_position -= 1
					break
				end
			end
			raise Exception.new("Invalid number from input") if number_string == ""
			number_string.to_i32
		end

		def read_register_or_number
			begin
				return read_register
			rescue
				@position -= 1
				return read_number
			end
			raise Exception.new("Invalid register/number")
		end

		def read_register_or_number_value : Int32
			target = read_register_or_number
			return target if target.is_a? Int32
			return @registers[target] if target.is_a? Char
			raise Exception.new("Invalid register/number")
		end

		def read_condition : Bool
			a = read_register_or_number_value
			operator = read_char!
			raise Exception.new("Invalid conditional operator") unless ['=', '!', '>', '<'].includes? operator
			b = read_register_or_number_value
			case operator
			when '='
				return a == b
			when '!'
				return a != b
			when '>'
				return a > b
			when '<'
				return a < b
			end
			false
		end

		def read_open_block
			raise Exception.new("Invalid block opening") unless read_char! == '['
		end

		def seek_close_block
			level = 0
			start = @position
			end_position = -1
			loop do
				char = read_char
				case char
				when '['
					level += 1
				when ']'
					if level > 0
						level -= 1
					else
						end_position = @position
						break
					end
				end
				raise Exception.new("Block never closed") if @position > @program.size
			end
			@position = start
			end_position
		end

		def read_instruction
			case c = read_char
			when '!'
				# move instruction
				register = read_register
				from = read_register_or_number_value
				@registers[register] = from
			when '+'
				# add instruction
				register = read_register
				operand = read_register_or_number_value
				@registers[register] += operand
			when '-'
				# subtract instruction
				register = read_register
				operand = read_register_or_number_value
				@registers[register] -= operand
			when '*'
				register = read_register
				operand = read_register_or_number_value
				@registers[register] *= operand
			when '/'
				register = read_register
				operand = read_register_or_number_value
				@registers[register] //= operand
			when '%'
				register = read_register
				operand = read_register_or_number_value
				@registers[register] = @registers[register] % operand
			when ','
				register = read_register
				value = @input[@input_position]? || '0'
				@registers[register] = value.to_i32? || value.ord
				@input_position += 1
			when '#'
				register = read_register
				value = read_number_from_input
				@registers[register] = value
			when '.'
				register = read_register
				@output += @registers[register].to_s
			when ';'
				register = read_register
				@output += @registers[register].chr
			when '\''
				@input_position = read_register_or_number_value
			when 'i'
				condition = read_condition
				read_open_block
				unless condition
					# skip to the next matching close block
					@position = seek_close_block
				end
			when 'w'
				start = @position - 1
				condition = read_condition
				read_open_block
				end_pos = seek_close_block
				if condition
					loop_pairs << {end_pos, start}
				else
					@position = end_pos
				end
			when ']'
				if lp = loop_pairs.find { |lp| lp[0] == @position }
					@position = lp[1]
					loop_pairs.delete lp
				end
			when '|'
				@registers[read_register] = @input.size
			when '_'
				@input_position += 1
			when ':'
				until read_char == '\n'
				end
			when nil
				# program is over
			else
				# ignore invalid instruction
			end
		end
	end
end