🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of slaymance

slaymance's solution

to Transpose in the JavaScript Track

Published at Jun 05 2021 · 4 comments
Instructions
Test suite
Solution

Given an input text output it transposed.

Roughly explained, the transpose of a matrix:

ABC
DEF

is given by:

AD
BE
CF

Rows become columns and columns become rows. See https://en.wikipedia.org/wiki/Transpose.

If the input has rows of different lengths, this is to be solved as follows:

  • Pad to the left with spaces.
  • Don't pad to the right.

Therefore, transposing this matrix:

ABC
DE

results in:

AD
BE
C

And transposing:

AB
DEF

results in:

AD
BE
 F

In general, all characters from the input should also be present in the transposed output. That means that if a column in the input text contains only spaces on its bottom-most row(s), the corresponding output row should contain the spaces in its right-most column(s).

Setup

Go through the setup instructions for Javascript to install the necessary dependencies:

https://exercism.io/tracks/javascript/installation

Requirements

Please cd into exercise directory before running all below commands.

Install assignment dependencies:

$ npm install

Making the test suite pass

Execute the tests with:

$ npm test

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by changing xtest to test.

Submitting Solutions

Once you have a solution ready, you can submit it using:

exercism submit transpose.js

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

Exercise Source Credits

Reddit r/dailyprogrammer challenge #270 [Easy]. https://www.reddit.com/r/dailyprogrammer/comments/4msu2x/challenge_270_easy_transpose_the_input_text

transpose.spec.js

import { transpose } from './transpose';

describe('Transpose', () => {
  test('empty string', () => {
    expect(transpose([])).toEqual([]);
  });

  xtest('two characters in a row', () => {
    const input = ['A1'];
    const expected = ['A', '1'];
    expect(transpose(input)).toEqual(expected);
  });

  xtest('two characters in a column', () => {
    const input = ['A', '1'];
    const expected = ['A1'];
    expect(transpose(input)).toEqual(expected);
  });

  xtest('simple', () => {
    const input = ['ABC', '123'];
    const expected = ['A1', 'B2', 'C3'];
    expect(transpose(input)).toEqual(expected);
  });

  xtest('single line', () => {
    const input = ['Single line.'];
    const expected = [
      'S',
      'i',
      'n',
      'g',
      'l',
      'e',
      ' ',
      'l',
      'i',
      'n',
      'e',
      '.',
    ];
    expect(transpose(input)).toEqual(expected);
  });

  xtest('first line longer than second line', () => {
    const input = ['The fourth line.', 'The fifth line.'];
    const expected = [
      'TT',
      'hh',
      'ee',
      '  ',
      'ff',
      'oi',
      'uf',
      'rt',
      'th',
      'h ',
      ' l',
      'li',
      'in',
      'ne',
      'e.',
      '.',
    ];
    expect(transpose(input)).toEqual(expected);
  });

  xtest('second line longer than first line', () => {
    const input = ['The first line.', 'The second line.'];
    const expected = [
      'TT',
      'hh',
      'ee',
      '  ',
      'fs',
      'ie',
      'rc',
      'so',
      'tn',
      ' d',
      'l ',
      'il',
      'ni',
      'en',
      '.e',
      ' .',
    ];
    expect(transpose(input)).toEqual(expected);
  });

  xtest('square', () => {
    const input = ['HEART', 'EMBER', 'ABUSE', 'RESIN', 'TREND'];
    const expected = ['HEART', 'EMBER', 'ABUSE', 'RESIN', 'TREND'];
    expect(transpose(input)).toEqual(expected);
  });

  xtest('rectangle', () => {
    const input = ['FRACTURE', 'OUTLINED', 'BLOOMING', 'SEPTETTE'];
    const expected = [
      'FOBS',
      'RULE',
      'ATOP',
      'CLOT',
      'TIME',
      'UNIT',
      'RENT',
      'EDGE',
    ];
    expect(transpose(input)).toEqual(expected);
  });

  xtest('triangle', () => {
    const input = ['T', 'EE', 'AAA', 'SSSS', 'EEEEE', 'RRRRRR'];
    const expected = [
      'TEASER',
      ' EASER',
      '  ASER',
      '   SER',
      '    ER',
      '     R',
    ];
    expect(transpose(input)).toEqual(expected);
  });

  xtest('many lines', () => {
    const input = [
      'Chor. Two households, both alike in dignity,',
      'In fair Verona, where we lay our scene,',
      'From ancient grudge break to new mutiny,',
      'Where civil blood makes civil hands unclean.',
      'From forth the fatal loins of these two foes',
      "A pair of star-cross'd lovers take their life;",
      "Whose misadventur'd piteous overthrows",
      "Doth with their death bury their parents' strife.",
      "The fearful passage of their death-mark'd love,",
      "And the continuance of their parents' rage,",
      "Which, but their children's end, naught could remove,",
      "Is now the two hours' traffic of our stage;",
      'The which if you with patient ears attend,',
      'What here shall miss, our toil shall strive to mend.',
    ];
    const expected = [
      'CIFWFAWDTAWITW',
      'hnrhr hohnhshh',
      'o oeopotedi ea',
      'rfmrmash  cn t',
      '.a e ie fthow ',
      ' ia fr weh,whh',
      'Trnco miae  ie',
      'w ciroitr btcr',
      'oVivtfshfcuhhe',
      ' eeih a uote  ',
      'hrnl sdtln  is',
      'oot ttvh tttfh',
      'un bhaeepihw a',
      'saglernianeoyl',
      'e,ro -trsui ol',
      'h uofcu sarhu ',
      'owddarrdan o m',
      "lhg to'egccuwi",
      'deemasdaeehris',
      'sr als t  ists',
      ",ebk 'phool'h,",
      '  reldi ffd   ',
      'bweso tb  rtpo',
      'oea ileutterau',
      't kcnoorhhnatr',
      "hl isvuyee'fi ",
      ' atv es iisfet',
      'ayoior trr ino',
      'l  lfsoh  ecti',
      'ion   vedpn  l',
      'kuehtteieadoe ',
      'erwaharrar,fas',
      '   nekt te  rh',
      'ismdsehphnnosa',
      'ncuse ra-tau l',
      ' et  tormsural',
      "dniuthwea'g t ",
      'iennwesnr hsts',
      'g,ycoi tkrttet',
      "n ,l r s'a anr",
      "i  ef  'dgcgdi",
      't  aol   eoe,v',
      'y  nei sl,u; e',
      ',  .sf to l   ',
      '     e rv d  t',
      '     ; ie    o',
      '       f, r   ',
      '       e  e  m',
      '       .  m  e',
      '          o  n',
      '          v  d',
      '          e  .',
      '          ,',
    ];
    expect(transpose(input)).toEqual(expected);
  });
});
/**
 * Check out all my solutions to the Exercism JavaScript track:
 * github.com/slaymance/exercism/tree/main/javascript
 */

// Helper function for clarity
const getMaxLength = input => input.reduce((maxLength, { length }) => Math.max(maxLength, length), 0)

export const transpose = input => Array.from(Array(getMaxLength(input)),
  (_, i) => input.reduce((transposedText, text, j) =>
    transposedText + (text[i]?.padStart(j - transposedText.length + 1, ' ') || ''), '')
);

Community comments

Find this solution interesting? Ask the author a question to learn more.
Avatar of marmoure

WoW i never knew you can destructure length out of string this will get to think more about how things work

Avatar of slaymance

@marmoure Yeah I find myself destructuring decently often in array method callbacks. I wonder if my solution to get a max length from an array of strings would be faster than mapping and spreading the results into a Math.max function:

const getMaxLength = input => Math.max(...input.map(({ length }) => length));
Avatar of marmoure

@slaymance thanks to a previous comment of yours i can compare functions performance now

const getMaxLengthReduce = input => input.reduce((maxLength, { length }) => Math.max(maxLength, length), 0)

const getMaxLengthMath = input => Math.max(...input.map(({ length }) => length));

const performanceTest = (getLEngthFn, iterations) => {
    const testArray = [
        'Chor. Two households, both alike in dignity,',
        'In fair Verona, where we lay our scene,',
        'From ancient grudge break to new mutiny,',
        'Where civil blood makes civil hands unclean.',
        'From forth the fatal loins of these two foes',
        "A pair of star-cross'd lovers take their life;",
        "Whose misadventur'd piteous overthrows",
        "Doth with their death bury their parents' strife.",
        "The fearful passage of their death-mark'd love,",
        "And the continuance of their parents' rage,",
        "Which, but their children's end, naught could remove,",
        "Is now the two hours' traffic of our stage;",
        'The which if you with patient ears attend,',
        'What here shall miss, our toil shall strive to mend.',
      ];

    console.time(getLEngthFn.name);

    for (let i = 0; i < iterations; i++) {
        getLEngthFn(testArray);
    }

    console.timeEnd(getLEngthFn.name);
};


performanceTest(getMaxLengthReduce, 100_000_0); // getMaxLengthReduce: 49 ms - timer ended

performanceTest(getMaxLengthMath, 100_000_0); // getMaxLengthMath: 193 - timer ended

its not obvious at first but after seeing the results i tried to see where is the diffrance seems like using reduce is only looping once and math.max in it its not costty at all as for the other one

  • using map to tranform each string to its length
  • spreading the lengths array
  • using math.max on a large list of numbers

i thinks these three operations as adding up to the cost alot what do you think @slaymance

Avatar of slaymance

@marmoure Wow nice breakdown! The difference in runtime is pretty clear. I would have thought that spreading a large array is what would make the Math solution so much less efficient, but good observation that it could also be using Math.max with a large list of arguments.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?