How to resolve the algorithm Word wrap step by step in the jq programming language

Published on 12 May 2024 09:40 PM
#Jq

How to resolve the algorithm Word wrap step by step in the jq programming language

Table of Contents

Problem Statement

Even today, with proportional fonts and complex layouts, there are still cases where you need to wrap text at a specified column.

The basic task is to wrap a paragraph of text in a simple way in your language.
If there is a way to do this that is built-in, trivial, or provided in a standard library, show that. Otherwise implement the minimum length greedy algorithm from Wikipedia. Show your routine working on a sample of text at two different wrap columns.

Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm.
If your language provides this, you get easy extra credit, but you must reference documentation indicating that the algorithm is something better than a simple minimum length algorithm. If you have both basic and extra credit solutions, show an example where the two algorithms give different results.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Word wrap step by step in the jq programming language

Source code in the jq programming language

# Simple greedy algorithm.
# Note: very long words are not truncated.
# input: a string
# output: an array of strings
def wrap_text(width):
  reduce splits("\\s+") as $word
    ([""];
     .[length-1] as $current
     | ($word|length) as $wl
     | (if $current == "" then 0 else 1 end) as $pad
     | if $wl + $pad + ($current|length) <= width
       then .[-1] += ($pad * " ") + $word
       else . + [ $word]
       end );

"aaa bb cc ddddd" | wrap_text(6)[]  # wikipedia example

"aaa bb cc ddddd" | wrap_text(5)[]

$ jq -M -R -s -r -f Word_wrap.jq Russian.txt
советских военных судов и самолетов была
отмечена в Японском море после появления
там двух американских авианосцев. Не
менее 100 советских самолетов поднялись
в воздух, когдаамериканские авианосцы
"Уинсон" и "Мидуэй" приблизились на 50
миль к Владивостоку.


  

You may also check:How to resolve the algorithm Bitwise operations step by step in the Modula-3 programming language
You may also check:How to resolve the algorithm Kronecker product step by step in the Go programming language
You may also check:How to resolve the algorithm Stem-and-leaf plot step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Hello world/Standard error step by step in the PL/I programming language
You may also check:How to resolve the algorithm Legendre prime counting function step by step in the Vlang programming language