본문 바로가기
알고리즘/Codewars

[Codewars] Consecutive strings (6 kyu) / JavaScript

by fluss 2023. 4. 18.

https://www.codewars.com/kata/56a5d994ac971f1ac500003e

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

DESCRIPTION:

You are given an array(list) strarr of strings and an integer k. Your task is to return the first longest string consisting of k consecutive strings taken in the array.

 

Examples:

strarr = ["tree", "foling", "trashy", "blue", "abcdef", "uvwxyz"], k = 2

Concatenate the consecutive strings of strarr by 2, we get:

treefoling   (length 10)  concatenation of strarr[0] and strarr[1]
folingtrashy ("      12)  concatenation of strarr[1] and strarr[2]
trashyblue   ("      10)  concatenation of strarr[2] and strarr[3]
blueabcdef   ("      10)  concatenation of strarr[3] and strarr[4]
abcdefuvwxyz ("      12)  concatenation of strarr[4] and strarr[5]

Two strings are the longest: "folingtrashy" and "abcdefuvwxyz".
The first that came is "folingtrashy" so 
longest_consec(strarr, 2) should return "folingtrashy".

In the same way:
longest_consec(["zone", "abigail", "theta", "form", "libe", "zas", "theta", "abigail"], 2) --> "abigailtheta"

n being the length of the string array, if n = 0 or k > n or k <= 0 return "" (return Nothing in Elm, "nothing" in Erlang).

 

Note

consecutive strings : follow one after another without an interruption

 

코드

function longestConsec(strarr, k) {
  if(strarr.length === 0 || strarr.length < k || k <= 0) return "";
  let sIndex = 0;
  let maxCount = 0;
  for(let i = 0; i <= strarr.length - k; i++){
    let count = 0;
    for(let j = i; j < i + k; j++){
      count += strarr[j].length;
    }
    if(maxCount < count){
      maxCount = count;
      sIndex = i;
    }
  }
  let result = strarr.splice(sIndex, k);
  return result.join('');
}

댓글