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

Example:

Find first most frequently occuring number in given array.

Given input {1, 2, 9, 3, 4, 3, 3, 1, 2, 4, 5, 3, 8, 3, 9, 0, 3, 2},
output should be 3 as it has highest frequency of occurence.

Note: This solution uses LinkedHashMap to preserve order of entry.

Code
Diff
  • import java.util.*;
    
    /**
      Time Complexity  : O(N)
      Space Complexity : O(N)
    */
    class MaxOccurence {
      public static int findMax(int[] nums) {
        return findMaxOccurenceLinkedHashMap(nums);
      }
      
      private static int findMaxOccurenceLinkedHashMap(int[] nums) {
        int maxKey = 0, maxNum = 0;
        
        if(nums.length < 1) return -1;
        if(nums.length == 1) return nums[0];
        
        Map<Integer, Integer> counts = new LinkedHashMap<Integer, Integer>(nums.length);
        
        for(int i = 0, len = nums.length; i < len; i++) {
          if(!counts.containsKey(nums[i])) {
            counts.put(nums[i], 1);
          } else {
            counts.put(nums[i], (counts.get(nums[i]) + 1));
          }
        }
        
        for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {  
          if (entry.getValue() > maxNum) {
            maxKey = entry.getKey();
            maxNum = entry.getValue();
          }  
        }  
        
        return maxKey;
      } 
    }
    • import java.util.*;
    • /**
    • Time Complexity : O(N)
    • Space Complexity : O(N)
    • */
    • class MaxOccurence {
    • public static int findMax(int[] nums) {
    • return findMaxOccurenceCountArray(nums);
    • return findMaxOccurenceLinkedHashMap(nums);
    • }
    • private static int findMaxOccurenceCountArray(int[] nums) {
    • int maxNum = 0;
    • int maxCount = 0;
    • private static int findMaxOccurenceLinkedHashMap(int[] nums) {
    • int maxKey = 0, maxNum = 0;
    • if(nums.length < 1) return -1;
    • if(nums.length == 1) return nums[0];
    • int[] counts = new int[nums.length];
    • Map<Integer, Integer> counts = new LinkedHashMap<Integer, Integer>(nums.length);
    • for(int i = 0, len = nums.length; i < len; i++) {
    • counts[nums[i]]++;
    • if(counts[nums[i]] > maxCount) {
    • maxCount = counts[nums[i]];
    • maxNum = nums[i];
    • if(!counts.containsKey(nums[i])) {
    • counts.put(nums[i], 1);
    • } else {
    • counts.put(nums[i], (counts.get(nums[i]) + 1));
    • }
    • }
    • return maxNum;
    • for (Map.Entry<Integer, Integer> entry : counts.entrySet()) {
    • if (entry.getValue() > maxNum) {
    • maxKey = entry.getKey();
    • maxNum = entry.getValue();
    • }
    • }
    • return maxKey;
    • }
    • }
Hashes
Data Structures
Code
Diff
  • /* HashMap Example */
     
    import java.util.*;
    import java.lang.*;
    import java.io.*;
     
    class HashMapDemo
    {
      public static void main (String[] args) throws java.lang.Exception {
        Map<Integer, Integer> map = new HashMap<Integer, Integer>() {{
            put(1, 1);
            put(2, 1);
            put(3, 1);
            put(4, 1);
            put(5, 1);
            put(6, 1);
        }};
    
        map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));
      }
    }
    • /* HashMap Example */
    • import java.util.*;
    • import java.lang.*;
    • import java.io.*;
    • class HashMapDemo
    • {
    • public static void main (String[] args) throws java.lang.Exception
    • {
    • Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    • map.put(1, 1);
    • map.put(2, 1);
    • map.put(3, 1);
    • map.put(4, 1);
    • map.put(5, 1);
    • map.put(6, 1);
    • for(Map.Entry<Integer, Integer> entry : map.entrySet()) {
    • int key = entry.getKey();
    • int value = entry.getValue();
    • System.out.println(key + " " + value);
    • }
    • }
    • public static void main (String[] args) throws java.lang.Exception {
    • Map<Integer, Integer> map = new HashMap<Integer, Integer>() {{
    • put(1, 1);
    • put(2, 1);
    • put(3, 1);
    • put(4, 1);
    • put(5, 1);
    • put(6, 1);
    • }};
    • map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + " " + e.getValue()));
    • }
    • }
Sequences
Arrays
Data Types
Code
Diff
  • module Collatz where
    
    collatz :: Int -> [Int]
    collatz = iterate next
      where next n | even n = n `div` 2
                   | odd n = n * 3 + 1
    • module Collatz where
    • collatz :: Int -> [Int]
    • collatz n = n : collatz next
    • where next | even n = n `div` 2
    • | odd n = n * 3 + 1
    • collatz = iterate next
    • where next n | even n = n `div` 2
    • | odd n = n * 3 + 1
Code
Diff
  • // basic merge callback
    var merge = function(array1, array2, callback){  
    	// error check array lengths with ternary operator
      //(array1.length != array2.length) ? return new Error('array\'s not same length') : null;
     
     	// instantiate our result array that we will return
      var result = [];
     	
      // loop through each index of array1
      array1.forEach( function(v,i) {
     		// append the return of our callback to our results array
        result.push(callback(array1[i], array2[i]));
      });
     
      return result;
    }
    
    // how you would write merge if you wanted to use the map method
    var mergemap = function(array1, array2, callback) {
      return array1.map(function(v, i) {
        return v + array2[i];
      });
    }
    
    // our function call with anonymous callback
    var x = merge([1, 2, 3, 4], [5, 6, 7, 8], function(a, b){  
      return a + b;
    });
    
    console.log('Merge result: ', x);
    //x should now equal [6, 8, 10, 12].
    
    // Think distance formula from physics except
    // it should be able to find distance in any dimensional system
    // 2D = x,y coord, 3D = x,y,z coord, etc.
    var euclid = function(coords1, coords2){  
      //Your code here.
      //You should not use any loops and should
      //instead use your original merge function.
      
      // This does the (x1 - x2 - xN)^2, (y1 + y2 + yN)^2 + ...
      var dimensions = merge(coords1, coords2, function(a, b) {
        return Math.pow((a - b), 2);
      });
      
      // This sums the dimension and takes the square root
      // sqrt( x + y + z + ...)
      // .reduce is acting as a sum function for our dimension array
      // We then use Math.sqrt to get the square root
      // We use Math.round with * 100 and / 100 to round to two decimal places
      // The rounding is optional but makes for a nicer looking result
      var distance = Math.round( Math.sqrt( dimensions.reduce(function(previousVal, currentVal) {
      	return previousVal + currentVal;
    	})) * 100) / 100;
    
    	return distance;
    }
    
    var x = euclid([1.2, 3.67], [2.0, 4.4]);
    console.log('Euclid result: ', x);
    //x should now equal approximately 1.08.
    • // basic merge callback
    • var merge = function(array1, array2, callback){
    • var array3 = [];
    • // error check array lengths with ternary operator
    • //(array1.length != array2.length) ? return new Error('array\'s not same length') : null;
    • // instantiate our result array that we will return
    • var result = [];
    • // loop through each index of array1
    • array1.forEach( function(v,i) {
    • // append the return of our callback to our results array
    • result.push(callback(array1[i], array2[i]));
    • });
    • return result;
    • }
    • if (array1.length !== array2.length) {
    • console.log("Array length mismatch");
    • return new Error("Array length mismatch");
    • } else {
    • length = array1.length;
    • }
    • for (var i = 0; i < length; i++) {
    • array3[i] = callback(array1[i], array2[i]);
    • }
    • return array3;
    • // how you would write merge if you wanted to use the map method
    • var mergemap = function(array1, array2, callback) {
    • return array1.map(function(v, i) {
    • return v + array2[i];
    • });
    • }
    • // our function call with anonymous callback
    • var x = merge([1, 2, 3, 4], [5, 6, 7, 8], function(a, b){
    • return a + b;
    • });
    • console.log('Merge result: ', x);
    • //x should now equal [6, 8, 10, 12].
    • // Think distance formula from physics except
    • // it should be able to find distance in any dimensional system
    • // 2D = x,y coord, 3D = x,y,z coord, etc.
    • var euclid = function(coords1, coords2){
    • //Your code here.
    • //You should not use any loops and should
    • //instead use your original merge function.
    • }
    • // This does the (x1 - x2 - xN)^2, (y1 + y2 + yN)^2 + ...
    • var dimensions = merge(coords1, coords2, function(a, b) {
    • return Math.pow((a - b), 2);
    • });
    • // This sums the dimension and takes the square root
    • // sqrt( x + y + z + ...)
    • // .reduce is acting as a sum function for our dimension array
    • // We then use Math.sqrt to get the square root
    • // We use Math.round with * 100 and / 100 to round to two decimal places
    • // The rounding is optional but makes for a nicer looking result
    • var distance = Math.round( Math.sqrt( dimensions.reduce(function(previousVal, currentVal) {
    • return previousVal + currentVal;
    • })) * 100) / 100;
    • var y = euclid([1.2, 3.67], [2.0, 4.4]);
    • return distance;
    • }
    • //y should now equal approximately 1.08.
    • var x = euclid([1.2, 3.67], [2.0, 4.4]);
    • console.log('Euclid result: ', x);
    • //x should now equal approximately 1.08.

Ha doesn't really work but yeah

Code
Diff
  • function fizzbuzzy(n) {
      var cones = 1;
      for (i = 0; i < n; i++){
    		!(i % 5) && cones++;
        !(i % 3) && cones++;       
      }
      return cones;
    }
    
    • function fizzbuzzy(n) {
    • var cones = 1;
    • for (i = 0; i < n; i++){
    • if (i % 5 === 0) cones++;
    • if (i % 3 === 0) cones++;
    • !(i % 5) && cones++;
    • !(i % 3) && cones++;
    • }
    • return cones;
    • }

I suggest to make the following changes in your code:

  1. Initialize variable i only once.

There are two ways to do that. You may move initialization to top variable declaration block. In this case your for loop starts looking like this:

var i = 0,
    ...
for(; i < n; i++) {     // Loop initialization part is empty! (Some may confused)
    ...
}

You may rewrite it to 'while' loop.

while(i < n) {
    ...
    i++;
}

But there may be issue with manually hoisting variables declaration outside of loop. You cannot copy/paste loop in another place within you code base (you may need it in some cases) whitout issues (if you use strict mode, you'll get ReferenceError, because variable i may not be declared and initialized). In this case you need to find all variable declarations related to loop (i, n) and paste them too.

I suggest to move loop variable declaration logic to initialization part of for loop. In this case all loop variables are closely related to each other (high cohesion) and you may safely move this loop to any place within your code base.

  1. Better check input parameter s.

As i understand, balanced_parenthesis fuction should work with strings as input parameters. If this function is public API function, we need to check input parameters properly and fail fast.

You may add additional check for string type of input parameter. This check is not only save us from array-like objects and arrays (because they have length property), but also allows us to use loose equal operator (two equal signs) inside our loop (yes, we can safely use loose equal operator because we are sure that we are working with string).

  1. Use ternary operator in return statement.
    Some prefer to use ternary operator for simple if/else cases due to it's readability. Also we may harness implicit coercion feature of JS for startCnt variable.

My solution is also imperfect, so i'll appreciate if you say what's wrong with my solution. Thanks.

P.S. Please, be patient to my English. It's also imperfect:)

Code
Diff
  • function balanced_parenthesis(s) {
        if(s == null || typeof s != 'string') return null;
        
        var startCnt = 0;
     
        for(var i = 0, n = s.length; i < n; i++) {
            if(s[i] == "(") {
                startCnt += 1;
            } else if(s[i] == ")") {
                startCnt -= 1;
                if(startCnt < 0) {
                    break;
                }
            }
        }
        
        return startCnt ? 'Unbalanced' : 'Balanced';
    }
    • function balanced_parenthesis(s) {
    • if(s == null) return null;
    • if(s == null || typeof s != 'string') return null;
    • var i = 0,
    • startCnt = 0,
    • n = s.length;
    • var startCnt = 0;
    • for(i = 0; i < n; i++) {
    • if(s[i] === "(") {
    • for(var i = 0, n = s.length; i < n; i++) {
    • if(s[i] == "(") {
    • startCnt += 1;
    • } else if(s[i] === ")") {
    • } else if(s[i] == ")") {
    • startCnt -= 1;
    • if(startCnt < 0) {
    • break;
    • }
    • }
    • }
    • if(startCnt !== 0) {
    • return 'Unbalanced';
    • } else {
    • return 'Balanced';
    • }
    • return startCnt ? 'Unbalanced' : 'Balanced';
    • }
Code
Diff
  • cat("Hello World!\n")
    • c("Hello World!")
    • cat("Hello World!\n")
Code
Diff
  • #include <iostream>
    
    int main()
    {
      std::cout << "Hello C++" << std::endl;
      return 0;
    }
    • #include <iostream>
    • int main(){
    • int main()
    • {
    • std::cout << "Hello C++" << std::endl;
    • return 0;
    • }