4
This is similar to the alignment used in word.
Task
3 inputs: A 1 line string, a positive integer k
, and direction (left or middle or right)
Your job is to insert new lines(\n
) and spaces in the string such that every line has k
characters in it and aligned to the direction given.
Rules
The words must not be split(unless their length is greater than k
)
Direction can be taken as any 3 unique characters(must be mentioned).
Any format and order of input is valid(must be mentioned).
Input will only have alphabetical characters of any case(and spaces).
There will not be any trailing or leading spaces in the input and will have only 1 space between words.
Output can be either a string on one line as is in examples or multiple lines.
If the direction is left:
There should not be any spaces in left of the line and only 1 space between words.
If the direction is right:
There cannot be any spaces to the right of the line and only 1 space between words.
If the direction is middle:
There cannot be any spaces to the left or right of a line and an equal number of spaces between words on one line.
In case the word length is shorter than k
and only 1 word can fit in 1 line, then spaces on the right is allowed.
If more than 2 words can fit in one line but they cannot be divided keeping number of spaces equal, words will shift to next line to keep number of spaces equal.
Test Cases
input: 'Hello World',6,right
output: ' Hello\n World'
input: 'Hello World',7,left
output: 'Hello \nWorld '
input: 'Hello World',7,middle
output: 'Hello \nWorld '
input: 'This is a test case',5,middle
output: 'This \nis a\ntest \ncase '
input: 'This is a test case',5,left
output: 'This \nis a \ntest \ncase '
input: 'For example',1,left
output: 'F\no\nr\ne\nx\na\nm\np\nl\ne' #The space is removed as the next word is in a newline.
input: 'Hello Worlds How are you',5,left
output: 'Hello\nWorld\ns How\nare \nyou '
input: 'qwert asdfghjkl zxcvbnm',7,middle
output: 'qwert \nasdfghj\nkl \nzxcvbnm'
input: 'ab abcdefg',6,middle
output: 'ab \nabcdef\ng '
input: 'This is code golf so shortest code wins',10,middle
output: 'This is\ncode golf\nso \nshortest \ncode wins'
input: 'Credit to Jo for this case',13,middle
output: 'Credit to\nJo for this\ncase '
This is code-golf so shortest code wins
Related. – Bubbler – 2018-11-14T07:19:58.853
Can we remove trailing whitespace? – Jo King – 2018-11-14T07:31:48.460
@JoKing, No, you can't. – Vedant Kandoi – 2018-11-14T07:34:46.090
input: 'the maximums',6,middle
; output: ? from the post, I could argue both'the \nmaximu\nms '
, or'the ma\nximums'
. – Chas Brown – 2018-11-14T08:28:21.340@ChasBrown,
the...\nmaximu\nms....
(same as left) – Vedant Kandoi – 2018-11-14T08:31:08.997@ChasBrown, 1 example was wrong,fixed it – Vedant Kandoi – 2018-11-14T09:30:17.573