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

Type Initializers

When you define a derived data type in GNU Fortran, you are automatically given a type initializer which allows you to initialize an instance of your derived data type in one go. One can think of a type initializer as a primitive type of constructor. However, custom-defined constructors weren't available until Fortran 2003 so it may not be available in GNU Fortran (which is an extension of the Fortran 95 standard).

module Solution
  implicit none
  type Vec3D ! A three-dimensional vector
    integer :: x, y, z
  end type Vec3D
  type(Vec3D) :: v = Vec3D(1, 2, 3) ! Using the type initializer provided by Fortran
end module Solution

Alternative Function Syntax

Just discovered this by looking at a few Fortran code examples online, but it seems that in as early as Fortran 95 (perhaps even earlier!), functions can be defined in at least two ways.

The traditional way:

function FUNCTION_NAME(PARAMETER) ! or parameters
  PARAMETER_TYPE :: PARAMETER
  RETURN_TYPE :: FUNCTION_NAME ! or explicit result variable
  ! Function body
end function FUNCTION_NAME

And the second (perhaps more C-like) way:

RETURN_TYPE function FUNCTION_NAME(PARAMETER)
  PARAMETER_TYPE :: PARAMETER
  ! Function body
end function FUNCTION_NAME

Of course, with either syntax, it is possible to add modifiers such as pure, recursive or result(RESULT_VAR).

module Solution
  implicit none
contains
  integer pure function add(a, b) result(c)
    integer, intent(in) :: a, b
    c = a + b
  end function add
end module Solution

heres the instruction:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.

Finish the solution so that it returns the sum of all the multiples of 3 or 5 below the number passed in.

Note: If the number is a multiple of both 3 and 5, only count it once.

I got the output of 23 by adding all multiple of 3 and 5 but it saying, I'm wrong.

I'm new here plss help

function test() {
  var a = [];
  for (i=1; i<10; i++){
    if ((i%3==0) || (i%5==0)){
    a.push(i);
    }
  }
   return a;
}

function sum(number){ 
  var sum= 0;
  for(i=0; i<number.length; i++){
    sum += number[i];
    }
    return sum;
  }
var ab = test();
var abc = sum(ab);
console.log(abc);

Objective: given 1 <= K <= 26, 0 <= N count the number of different strings of length N that contain exactly K different characters from the alphabet.

Ideas: for small values of N it should be bruteforce-able.
For large values of N?

Clarifications:
-> "The alphabet" is the 26 lowercase letters of the English alphabet

alphabet = 'abcdefghijklmnopqrstuvwxyz'

import itertools

def counter(N, K):
    return counterNaive(N, K)

def counterNaive(N, K):
#    print(f"counterNaive({K}, {N})")
    allCombs = [x for x in itertools.product(alphabet, repeat=N)]
#    print(f"All combinations of length {N}: 26^N = {26**N}")
    return sum( len(set(x)) == K for x in allCombs )
    
def counterSmart(N, K):
    # Idea:
    # Find all ways of splitting N in K parts
    # For each such way, once we know the lenght of the parts K1, ..., Kn
    # (And they must be such that K1+...+Kn = N)
        # Calculate the possible combinations: they are N!/(N-K)! options for the choice of K letters
        # divided by the product of:
            # L! where L = count(Kn == j) for j in range(N)
            # to compensate the fact that if letters 'a' and 'b' appear in the same amount,
            # then doing (a, b) = (b, a) does not give a different sequenec
        # times the permutations of N elements with K1, ..., Kn repetitions
    # Then add these up
    pass
Data Structures
Algorithms
Logic
Linked Lists
Lists
Maps

Map/Dictionary/Associative Array as a linked list of entries

Related article: Associative Array - Wikipedia

Many modern and/or popular programming languages such as Python, Java and C++ (and even some not-so-modern and/or popular languages such as Objective-C) provide a built-in datatype (either natively or in a built-in library) which maintains association between keys and values, commonly known as a map/dictionary and sometimes less known as an associative array (in languages such as PHP). However, for simpler and/or older languages such as C, such convenient data types do not exist. So, is it possible to define your own map/dictionary/assoc-array datatype in such languages? Of course - it all just boils down to data structures and algorithms (and perhaps some simple wrappers to hide your implementation from the user). Perhaps the easiest way to implement your own map data type is by using a linked list of key-value entries which will be demonstrated in this Kumite but the downside is that pretty much every operation you perform on your map (be it insertion, query or deletion) will have O(n) time complexity, i.e. the time taken to execute the operation varies directly with the number of entries in the map. The related Wikipedia article (link posted above) says that insertion should be an O(1) operation (since you could insert the key-value pair at the head of the list) but only if it is assumed that the key does not already exist in the map; otherwise, problems may arise if one attempts to iterate through the map.

This map implementation is seldomly used in real-world applications (and not even provided in built-in libraries of languages such as Java) due to its inefficiency and is only considered if the map is expected to be very small.

#include <stddef.h>

typedef struct {
  // A key-value pair of integers
  int key, value;
} Entry;

typedef struct node_t {
  // A node in a linked list - internal implementation of a Map
  Entry *entry; // The current entry in our map
  struct node_t *next; // The rest of our map
} Node;

typedef struct {
  // Outer map wrapper (to hide interal implementation and
  // reserve `NULL` for representing an invalid map reference instead of an empty map)
  Node *root;
} Map;

int map_get(const Map *map, int key) {
  // Returns the corresponding value to the key in the map
  // Assumption: the key is present in the map
  // (querying a nonexistent key yields undefined behavior)
  const Node *n = map->root;
  while (n->entry->key != key)
    n = n->next;
  return n->entry->value;
}

void map_set(Map *map, int key, int value) {
  // Adds the key-value pair to the map if not present;
  // otherwise reassigns it at the corresponding entry
  Node *n = map->root;
  while (n != NULL && n->entry->key != key)
    n = n->next;
  if (n != NULL)
    n->entry->value = value;
  else {
    Node *tmp = map->root;
    map->root = malloc(sizeof(Node));
    map->root->entry = malloc(sizeof(Entry));
    map->root->entry->key = key;
    map->root->entry->value = value;
    map->root->next = tmp;
  }
}

void map_remove(Map *map, int key) {
  // Removes an entry from the map with the given key
  // Assumption: The given key-value pair exists
  // (attempting to delete a nonexistent entry yields undefined behavior)
  // This also implies that the map cannot be empty
  if (map->root->entry->key == key) {
    Node *tmp = map->root->next;
    free(map->root->entry);
    free(map->root);
    map->root = tmp;
  } else {
    Node *parent = map->root, *child = parent->next;
    while (child->next != NULL && child->entry->key != key) {
      parent = child;
      child = child->next;
    }
    parent->next = child->next;
    free(child->entry);
    free(child);
  }
}

Really simple problem to work on if you have just started learing C#.

Determine the SUM of the 3 arrays and return the total in an int format.

Enjoy..

#Arrays

using System;
using System.Linq;

 public static class Kata
 {
 public static int ArraySum(int[] arr1, int[] arr2, int[] arr3)
        {
            int[] newArray1 = arr1.Concat(arr2).ToArray();
            int[] newArray2 = newArray1.Concat(arr3).ToArray(); 
            int sum = newArray2.Sum();
            return sum; 
        }
}
#

Some user interactions, such as resizing and scrolling, can create a huge number of browser events in a short period of time. If listeners attached to these events take a long time to execute, the user's browser can start to slow down significantly. To mitigate this issue, we want to to implement a throttle function that will detect clusters of events and reduce the number of times we call an expensive function.

Your function will accept an array representing a stream of event timestamps and return an array representing the times that a callback should have been called. If an event happens within wait time of the previous event, it is part of the same cluster. Your function should satisfy the following use cases:

  1. Firing once on the first event in a cluster, e.g. as soon as the window starts resizing.
  2. Firing once after the last event in a cluster, e.g. after the user window stops resizing.
  3. Firing every interval milliseconds during a cluster, e.g. every 100ms while the window is resizing.
function throttle(wait, onLast, onFirst, interval, timestamps) {
  let ret = [];
  let cluster = [timestamps[0]];
  
  for(let i=1; i<timestamps.length; i++) {
    if(timestamps[i] - timestamps[i-1] <= wait) {
      cluster.push(timestamps[i]);
    } else {
      let clusterEventTimes = evaluateCluster(wait, onLast, onFirst, interval, cluster);
      clusterEventTimes.forEach( function(el){ ret.push(el); });
      cluster = [timestamps[i]];
    }
    
    if(i == timestamps.length-1) {
      let clusterEventTimes = evaluateCluster(wait, onLast, onFirst, interval, cluster);
      clusterEventTimes.forEach( function(el){ ret.push(el); });
    }
  }
  
  return ret;
}

// Determines all times when an event needs to be fired
function evaluateCluster(wait, onLast, onFirst, interval, cluster){
  let ret = [];
  
  if(onFirst) {
    ret.push(cluster[0]); // push cluster start
  }
  if(interval != 0) {
    let maxInterval = cluster[cluster.length-1];
    if(onLast) {
      maxInterval += wait;
    }
    for(let intEv = cluster[0]+interval; intEv < maxInterval; intEv+=interval) {
      ret.push(intEv);
    }
  }
  if(onLast) {
    ret.push(cluster[cluster.length-1]+wait); // push cluster end
  }
    
  return ret;
}

Set 1 Challenge 1 for the cryptopal crypto challenges (https://cryptopals.com/sets/1/challenges/1).

Convert hex to base64

function hexToBase64(hex) {
  return hex;
}
doomsbyFailed Tests

Pairs

You will be given an array of integers and a target value. Determine the number of pairs of array elements that have a difference equal to the target value.

For example, given an array of [1,2,3,4] and a target value of 1, we have three pairs meeting the condition. 2 - 1 = 1, 3 - 2 = 1, and 4 - 3 = 1.

Input Format:

The first line contains n and k, the number of array elements and the target value.
The second line contains n space-separated integers of the array.

Constraints:

2 ≤ n ≤ 105
0 < k < 109
each integer element arr[i], will conform to 0 < arr[i] < 2^31 - 1
each integer arr[i] will be unique
Output Format
An integer representing the number of pairs of integers whose difference is k.

Sample Input:

5, 2, [1, 5, 3, 4, 2]

Sample Output:

3

Explanation:

There are 3 pairs of integers in the set with a difference of 2: [5,3], [4,2], and [3,1].

function pairs(num_elements, target_value, array) {
  
  return 0;
}