loading...

Daily Challenge #261 - Diagonal Strings

thepracticaldev profile image dev.to staff ・1 min read

In this challenge, you'll be given an array of strings with N elements and each element has N length.

First, sort the given array alphabetically. Your output will consist of letters obtained diagonally (from top left to bottom right). Collect the new string, then change the order and obtain a new string. Repeat this process until you have as many strings as was originally given in the array.

Example:

  1234                       Abcd                           
  aBcd                       kAta                           
  kaTa                       qwEr                           
  qweR -> 1234 => "1btr"     1234 -> abcd => "aae4"         

  Kata                       Qwer
  qWer                       1234
  1234                       abCd
  abcD -> kata => "kw3d"     katA -> qwer => "q2ca"

  Output : {"aae4","kw3d","1btr","q2ca"} (by input order)

Tests:
string[] { "1a8er", "B36jh", "AiYe3", "B1t0a", "g47uj" };
string[] { "ab", "12" };

Good luck!


This challenge comes from frkn2076 on CodeWars. Thank you to CodeWars, who has licensed redistribution of this challenge under the 2-Clause BSD License!

Want to propose a challenge idea for a future post? Email yo+challenge@dev.to with your suggestions!

Discussion

pic
Editor guide
Collapse
citizen428 profile image
Michael Kohl

A simple Nim solution:

import algorithm

func diagonal*(strings: seq[string]): seq[string] =
  var
    len = strings.len
    sorted = strings.sorted
    word: string

  for _ in 0..<len:
    for i in 0..<len:
      word.add(sorted[i][i])
    result.add(word)
    word = ""
    sorted.rotateLeft(1)

Didn't feel like writin proper tests, so just stuck this into the same file:

if isMainModule:
  let expected1 = @["1btr", "aae4", "kw3d", "q2ca"]
  assert(diagonal(@["1234", "abcd", "kata", "qwer"]) == expected1)
  assert(diagonal(@["ab", "12"]) == @["1b", "a2"])
Collapse
_bkeren profile image
''
const solution = (arrayOfStrings) => {
    arrayOfStrings.sort()
    let resultList = []
    let N = arrayOfStrings[0].length
    for(let i=0; i < N; i++) {
        let diagonalWord = [...Array(N).keys()].map(j => (j+i)%N).map((dIndex,index) => arrayOfStrings[dIndex][index]).join("")
        resultList.push(diagonalWord)
    }
    return p;
}