0 Replies - 4015 Views - Last Post: 01 November 2011 - 09:29 PM

#1 stackoverflow   User is offline

  • D.I.C Addict
  • member icon

Reputation: 166
  • View blog
  • Posts: 545
  • Joined: 06-July 11

Two Dimensional Array Class

Posted 01 November 2011 - 09:29 PM

Description: The class is simple enough to use-- you declare an array object according to the constructor. The default value is optional. You can fill or display the values with the appropriate methods. You can also access the array itself via object.map[x][y] as long as x and y are valid indexes into the original dimensions. There is a function the class calls to create the array-- I left that outside the class because it's pretty general and useful on its own. This is a simple class to create and manipulate two dimensional arrays.
import sys


class TDArray(object):
  '''A two dimensional array.'''

  def __init__(self, width, height, default_value=None):
    '''
    Constructor: Initializes the array dimensions and fills with 
    a value, None is the default value. Throws a ValueError if the
    width or height is 0 or less. 
    '''

    if width <= 0 or height <= 0: raise ValueError('Invalid dimensions.')
    self.width = width
    self.height = height
    self.map = new_tdarray(self.width, self.height, default_value)

  def fill(self, value):
    '''Flood fills the array with the given value. '''
    for i in range(self.width):
      for j in range(self.height):
        self.map[i][j] = value

  def display(self):
    '''Displays the contents of the array to standard out, inserts new lines.'''
    for i in range(self.width):
      for j in range(self.height):
        sys.stdout.write(str(self.map[i][j]))
      print("");


def new_tdarray(width, height, default_value=None):
  '''
  Creates a new two dimensional array, and inserts a default value if one is
  specified. Throws a ValueError if the width or height is 0 or less. 
  '''

  if width <= 0 or height <= 0: raise ValueError('Invalid dimensions.')
  tdarray = [[default_value for i in range(width)] for j in range(height)]
  return tdarray


Is This A Good Question/Topic? 0
  • +

Page 1 of 1