Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pad an array to be a certain size

Tags:

arrays

ruby

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?

like image 544
dreeves Avatar asked Apr 10 '11 00:04

dreeves


People also ask

What does it mean to pad an array?

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.

How do you padding an array in Python?

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.

Can you change array size in Python?

With the help of Numpy numpy. resize(), we can resize the size of an array.

How do you add padding to a matrix in python?

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 .


1 Answers

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
like image 86
sawa Avatar answered Sep 29 '22 09:09

sawa