8
1
Intro
More complex than A square of text since this requires padding and input has unknown data type.
Every year, Dyalog Ltd. holds a student competition. The challenge there is to write good APL code. This is a language agnostic code-golf edition of this year's tenth problem.
I have explicit permission to post this challenge here from the original author of the competition. Feel free to verify by following the provided link and contacting the author.
Problem
Write a program/function that will reshape a given string or numeric list into the smallest square that will contain all the elements of the input, padding with additional elements if necessary. The pad element should be the default fill element for the given data type, or any one element of your choice. The elements of the square should be in such order that flattening it will give the original order of input data (with trailing padding elements, if any).
Test cases
[1,2,3,4]
→
[[1,2],
[3,4]]
[1,2,3,4,5]
→
[[1,2,3],
[4,5,0],
[0,0,0]]
"Dyalog APL"
→
[["Dyal"], [["D","y","a","l"],
["og A"], or ["o","g"," ","A"],
["PL "], ["P","L"," "," "],
[" "]] [" "," "," "," "]]
[100]
→
[[100]]
[]
→
your language's closest equivalent to an empty matrix, e.g. []
or [[]]
Do we have to be able to handle both strings and arrays as input or only one? Can output be a string containing newlines? Should the output for [100] not be [[1,0],[0,0]]? If not, is [[100,1],[2,0]] the expected output for input [100,1,2]? – Shaggy – 2017-05-15T07:41:40.627
@Shaggy Yes, numeric lists and strings/lists of characters (whatever your language uses). Output per default rules. "100" gives [["1",0"],["0"," "]] (or whatever the fill element is. Yes, [100,1,2] → [[100,1],[2,0]]. – Adám – 2017-05-15T07:43:52.297
Hi Adám, I have three questions... 1. What does "The pad element should be the default fill element for the given data type, or any one element of your choice." mean, - is it restricted or free (it seems contradictory or redundant)? 2. What should the output be for an input like
[1,2,3,4,'O']
, or is it guaranteed not to occur? 3. Is the required order after flattening requirement ignoring the pad elements (e.g. could an input of[1,2,3,4,5]
yield[[0,0,0],[0,1,2],[3,4,5]]
or even[[0,1,0],[2,0,3],[0,4,5]]
)? – Jonathan Allan – 2017-05-15T14:00:38.5671@JonathanAllan 1. Some languages will automatically pad. Whatever they pad with is fine. If your's don't, choose an element. 2. string or numeric list. 3. The padding elements must be trailing. – Adám – 2017-05-15T14:04:01.823