简体   繁体   中英

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.

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:

 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.

 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:

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

You don't have an array of arrays, though. 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. 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; let's call it 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. We might call it, say, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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