There's probably a more efficient and more Ruby-ish way to do this:
# Pad array to size n by adding x's. Don't do anything if n <= a.length.
def padleft(a, n, x)
return a if n <= a.length
return padleft([x] + a, n, x)
end
What would you suggest?
The array padding transformation sets a dimension in an array to a new size. The goal of this transformation is to reduce the number of memory system conflicts. The transformation is applied to a full function AST. The new size can be specified by the user or can be computed automatically.
pad() function is used to pad the Numpy arrays. Sometimes there is a need to perform padding in Numpy arrays, then numPy. pad() function is used. The function returns the padded array of rank equal to the given array and the shape will increase according to pad_width.
With the help of Numpy numpy. resize(), we can resize the size of an array.
Use np. zeros(shape) to create an array with the desired dimensions shape to pad a smaller array. Use the syntax padded_array[:shape[0],:shape[1]] = an_array to pad an_array with zeroes to the dimensions of padded_array .
Edited due to my misunderstanding of the question. Pervious version of my answer padded from the right side, but the question was asking to do it from the left side. I corrected it accordingly. This is due to naming convention. ljust
, rjust
are builtin methods for String
, and I extended that convention to Array
, but that corresponds to padright
and padleft
, respectively, in the terminology of the question.
Destructive methods
def padleft!(a, n, x)
a.insert(0, *Array.new([0, n-a.length].max, x))
end
def padright!(a, n, x)
a.fill(x, a.length...n)
end
It would be more natural to have it defined on Array
class:
class Array
def rjust!(n, x); insert(0, *Array.new([0, n-length].max, x)) end
def ljust!(n, x); fill(x, length...n) end
end
Non-destructive methods
def padleft(a, n, x)
Array.new([0, n-a.length].max, x)+a
end
def padright(a, n, x)
a.dup.fill(x, a.length...n)
end
or
class Array
def rjust(n, x); Array.new([0, n-length].max, x)+self end
def ljust(n, x); dup.fill(x, length...n) end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With