How to resolve the algorithm Align columns step by step in the JavaScript programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Align columns step by step in the JavaScript programming language

Table of Contents

Problem Statement

Given a text file of many lines, where fields within a line are delineated by a single 'dollar' character, write a program that aligns each column of fields by ensuring that words in each column are separated by at least one space. Further, allow for each word in a column to be either left justified, right justified, or center justified within its column. Use the following text to test your programs:

Note that:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Align columns step by step in the JavaScript programming language

Explanation of the First Code Snippet:

The first code snippet is a JavaScript program that takes input text, which is expected to be a string containing multiple lines of text, where fields within each line are delineated by the dollar ($) character. The program aligns the columns of fields by ensuring that words in each column are separated by at least one space. It also allows for each word in a column to be either left-justified, right-justified, or center-justified within its column.

Step-by-step Explanation:

  1. Variables and Initializations:

    • justification is a global variable used to specify the desired justification for the columns - left, right, or center.
    • input is an array containing the input text, where each element represents a line of text.
    • x and y are loop variables.
    • cols keeps track of the maximum number of columns in the input text.
    • max is used to determine the maximum length of words in each column.
    • left and right are used to define the padding for left and right justification, respectively.
  2. Determining Column Count:

    • The code iterates through each line of input and calculates the number of columns in each line.
    • The maximum number of columns across all lines is stored in the cols variable.
  3. Determining Maximum Word Length:

    • For each column, the code iterates through all the lines and finds the longest word in that column.
  4. Padding and Justification:

    • For each column, the code creates padding for left, right, or center justification based on the value of the justification variable.
    • Words are padded with spaces to ensure a minimum spacing of one space between words.
  5. Output:

    • Finally, the code joins the modified input lines into a single string and displays the aligned result in the browser's document window.

Explanation of the Second Code Snippet:

The second code snippet is also a JavaScript program that takes input text and aligns the columns of fields. However, it uses a more functional approach, leveraging functional programming techniques.

Step-by-step Explanation:

  1. Transpose Function:

    • This function takes a list of lists (i.e., a matrix) and transposes it, effectively swapping rows and columns.
  2. ZipWith Function:

    • This function takes three arguments: a binary function, two lists, and applies the function element-wise between the two lists.
  3. MaximumBy Function:

    • This function takes a binary function (e.g., comparing lengths) and a list, and returns the element that maximizes the result of the binary function.
  4. Widest Function:

    • This function takes a list of strings and returns the length of the longest string.
  5. FullRow Function:

    • This function takes two arguments: a list and an integer representing the desired number of elements. It returns a new list by padding the original list with empty strings to the specified length.
  6. Nreps Function:

    • This function takes two arguments: a string and an integer representing the number of repetitions. It returns the string repeated the specified number of times.
  7. Unwords Function:

    • This function takes a list of strings and joins them with a single space.
  8. Unlines Function:

    • This function takes a list of strings and joins them with new line characters.
  9. PadWords Function:

    • This function takes three arguments: a target width, a list of words, and a justification type. It returns a list of strings where each string represents a padded version of the corresponding word. The padding includes spaces to ensure the desired justification (left, center, or right).
  10. Main Program:

    • The main program defines constants for left, center, and right justification.
    • It splits the input text into rows and then transposes the rows to create columns.
    • It calculates the widest width for each column.
    • It applies the padWords function to pad the words in each column according to the specified justification.
    • Finally, it transposes the matrix again and joins the columns into strings, which are then joined into a single string with new line characters.

Source code in the javascript programming language

var justification="center",
input=["Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
"are$delineated$by$a$single$'dollar'$character,$write$a$program",
"that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$",
"column$are$separated$by$at$least$one$space.",
"Further,$allow$for$each$word$in$a$column$to$be$either$left$",
"justified,$right$justified,$or$center$justified$within$its$column."],
x,y,cols,max,cols=0,diff,left,right

String.prototype.repeat=function(n){return new Array(1 + parseInt(n)).join(this);}

for(x=0;x<input.length;x++) {
 input[x]=input[x].split("$");
 if(input[x].length>cols) cols=input[x].length;
}
for(x=0;x<cols;x++) {
 max=0;
 for(y=0;y<input.length;y++) if(input[y][x]&&max<input[y][x].length) max=input[y][x].length;
 for(y=0;y<input.length;y++) 
  if(input[y][x]) {
   diff=(max-input[y][x].length)/2;
   left=" ".repeat(Math.floor(diff));
   right=" ".repeat(Math.ceil(diff));
   if(justification=="left") {right+=left;left=""}
   if(justification=="right") {left+=right;right=""}
   input[y][x]=left+input[y][x]+right;
  }
}
for(x=0;x<input.length;x++) input[x]=input[x].join(" ");
input=input.join("\n");
document.write(input);


//break up each string by '$'. The assumption is that the user wants the trailing $.
var data = [
  "Given$a$text$file$of$many$lines,$where$fields$within$a$line$",
  "are$delineated$by$a$single$'dollar'$character,$write$a$program",
  "that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$",
  "column$are$separated$by$at$least$one$space.",
  "Further,$allow$for$each$word$in$a$column$to$be$either$left$",
  "justified,$right$justified,$or$center$justified$within$its$column."
].map(function (str) { return str.split('$'); })

//boilerplate: get longest array or string in array
var getLongest = function (arr) {
  return arr.reduce(function (acc, item) { return acc.length > item.length ? acc : item; }, 0);
};

//boilerplate: this function would normally be in a library like underscore, lodash, or ramda
var zip = function (items, toInsert) {
  toInsert = (toInsert === undefined) ? null : toInsert;
  var longestItem = getLongest(items);
  return longestItem.map(function (_unused, index) {
    return items.map(function (item) {
      return item[index] === undefined ? toInsert : item[index];
    });
  });
};

//here's the part that's not boilerplate
var makeColumns = function (formatting, data) {
  var zipData = zip(data, '');
  var makeSpaces = function (num) { return new Array(num + 1).join(' '); };
  var formattedCols = zipData.map(function (column) {
    var maxLen = getLongest(column).length;//find the maximum word length
    if (formatting === 'left') {
      return column.map(function (word) { return word + makeSpaces(maxLen - word.length); });
    } else if (formatting === 'right') {
      return column.map(function (word) { return makeSpaces(maxLen - word.length) + word; });
    } else {
      return column.map(function (word) {
        var spaces = maxLen - word.length,
            first = ~~(spaces / 2),
            last = spaces - first;
        return makeSpaces(first) + word + makeSpaces(last);
      });
    }
  });

  return zip(formattedCols).map(function (row) { return row.join(' '); }).join('\n');
};


(function (strText) {
    'use strict';
 
    // [[a]] -> [[a]]
    function transpose(lst) {
        return lst[0].map(function (_, iCol) {
            return lst.map(function (row) {
                return row[iCol];
            })
        });
    }
 
    // (a -> b -> c) -> [a] -> [b] -> [c]
    function zipWith(f, xs, ys) {
        return xs.length === ys.length ? (
            xs.map(function (x, i) {
                return f(x, ys[i]);
            })
        ) : undefined;
    }
 
    // (a -> a -> Ordering) -> [a] -> a 
    function maximumBy(f, xs) {
        return xs.reduce(function (a, x) {
            return a === undefined ? x : (
                f(x) > f(a) ? x : a
            );
        }, undefined)
    }
 
    // [String] -> String
    function widest(lst) {
        return maximumBy(length, lst)
            .length;
    }
 
    // [[a]] -> [[a]]
    function fullRow(lst, n) {
        return lst.concat(Array.apply(null, Array(n - lst.length))
            .map(function () {
                return ''
            }));
    }
 
    // String -> Int -> String
    function nreps(s, n) {
        var o = '';
        if (n < 1) return o;
        while (n > 1) {
            if (n & 1) o += s;
            n >>= 1;
            s += s;
        }
        return o + s;
    }
 
    // [String] -> String
    function unwords(xs) {
        return xs.join('  ');
    }
 
    // [String] -> String
    function unlines(xs) {
        return xs.join('\n');
    }
 
    // [a] -> Int
    function length(xs) {
        return xs.length;
    }
 
    // -- Int -> [String] -> [[String]]
    function padWords(n, lstWords, eAlign) {
        return lstWords.map(function (w) {
            var lngPad = n - w.length;
 
            return (
                    (eAlign === eCenter) ? (function () {
                        var lngHalf = Math.floor(lngPad / 2);
 
                        return [
                            nreps(' ', lngHalf), w,
                            nreps(' ', lngPad - lngHalf)
                        ];
                    })() : (eAlign === eLeft) ? 
                        ['', w, nreps(' ', lngPad)] :
                        [nreps(' ', lngPad), w, '']
                )
                .join('');
        });
    }
 
    // MAIN
 
    var eLeft = -1,
        eCenter = 0,
        eRight = 1;
 
    var lstRows = strText.split('\n')
        .map(function (x) {
            return x.split('$');
        }),
 
        lngCols = widest(lstRows),
        lstCols = transpose(lstRows.map(function (r) {
            return fullRow(r, lngCols)
        })),
        lstColWidths = lstCols.map(widest);
 
    // THREE PARAGRAPHS, WITH VARIOUS WORD COLUMN ALIGNMENTS:
 
    return [eLeft, eRight, eCenter]
        .map(function (eAlign) {
            var fPad = function (n, lstWords) {
                return padWords(n, lstWords, eAlign);
            };
 
            return transpose(
                    zipWith(fPad, lstColWidths, lstCols)
                )
                .map(unwords);
        })
        .map(unlines)
        .join('\n\n');
 
})(
    "Given$a$text$file$of$many$lines,$where$fields$within$a$line$\n\
are$delineated$by$a$single$'dollar'$character,$write$a$program\n\
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$\n\
column$are$separated$by$at$least$one$space.\n\
Further,$allow$for$each$word$in$a$column$to$be$either$left$\n\
justified,$right$justified,$or$center$justified$within$its$column."
);


  

You may also check:How to resolve the algorithm Long year step by step in the Arturo programming language
You may also check:How to resolve the algorithm Terminal control/Dimensions step by step in the PicoLisp programming language
You may also check:How to resolve the algorithm Continued fraction/Arithmetic/G(matrix ng, continued fraction n1, continued fraction n2) step by step in the Nim programming language
You may also check:How to resolve the algorithm Word ladder step by step in the 11l programming language
You may also check:How to resolve the algorithm Haversine formula step by step in the C programming language