简体   繁体   English

如何垂直循环遍历字符串数组

[英]How to vertically loop over an array of strings

I am trying to retrieve the first, and proceeding letters in an array of strings.我正在尝试检索字符串数组中的第一个字母和后续字母。 What I have been working on is looping over each item and then printing arr[i][0], but this does not work for the proceeding letters.我一直在做的是循环遍历每个项目,然后打印 arr[i][0],但这不适用于后面的字母。

For example:例如:

Input: 
'
00100
11110
10110

Output: 
011010111011000

Basically, I want to traverse vertically, not horizontally.基本上,我想垂直遍历,而不是水平遍历。

 function solution(s) { // transform string into array let arr = s.split('\n') for (let i = 0; i < arr.length; i++) { // log the first, then proceeding letter in each string console.log(arr[i][0]) } } console.log( solution(`00100 11110 10110 `) )

Use a nested for loop:使用嵌套for循环:

 function solution(s) { // transform string into array let arr = s.split('\n') for (let i = 0; i < arr[0].length; i++) { for(let f = 0; f < arr.length; f++){ console.log(arr[f][i]) } } } console.log(solution(`00100 11110 10110`))

You could split and split again for each row and map a new array with the characters transposed.您可以为每一行拆分并再次拆分,map 是一个新数组,其中字符已转置。

 function solution(s) { return s.split('\n').reduce((r, s) => [...s].map((c, i) => (r[i] || '') + c), []).join(''); } console.log(solution('00100\n11110\n10110'));

Turning a matrix's rows into columns and vice-versa is an operation called transposition .将矩阵的行转换为列,反之亦然,这是一种称为转置的操作。 A simple transposition function might look like this:一个简单的转置 function 可能如下所示:

const transpose = (xs) => 
  xs [0] .map ((_, i) => xs .map (r => r [i]))

You don't have an array of arrays, though.但是,您没有 arrays 数组。 After splitting the input on newlines, you will have an array of strings.在换行符上拆分输入后,您将拥有一个字符串数组。 But we can easily alter this function so that it will work on any iterable of iterables.但是我们可以很容易地改变这个 function 以便它适用于任何可迭代的迭代。 It will still return an array of arrays, but we can easily wrap it in a function that converts the output to an array of strings;它仍然会返回一个 arrays 数组,但我们可以轻松地将其包装在 function 中,将 output 转换为字符串数组; let's call it inColumns .我们称之为inColumns

Then we wrap it up in something that parses your string into an array of strings, calls, inColumns and then merges the results into a single string.然后我们将它包装在一个东西中,将你的字符串解析成一个字符串数组,调用, inColumns ,然后将结果合并成一个字符串。 We might call it, say, adventOfCodeDay3 :例如,我们可以称它为adventOfCodeDay3

 const transpose = (xs) => [... xs [0]].map ((_, i) => [... xs].map (r => r [i])) const inColumns = (xs) => transpose (xs).map (s => s.join ('')) const adventOfCodeDay3 = (s) => inColumns (s.split ('\n')).join ('') const input = `00100 11110 10110` console.log (adventOfCodeDay3 (input))

I find this sort of breakdown a much cleaner way to work a problem.我发现这种故障是解决问题的一种更清洁的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM