Home API Notes

2D Programming and Resources

There are lots of applications for 2D data. Common terms in 2D are tabular data, row/columns, matrix, etc. Nested iterative loops are often used to find or discover each cell in a 2D array.

Python 2D array

Example of pre-populating 2D array and printing using 3 different styles

  • Candy Challenge:print a christmas tree and trunk
"""
* Creator: Nighthawk Coding Society
2D arrays
"""

# Classic nested loops using ij indexes, this shows 2 dimensions
def print_matrix1(matrix):
    print("Classic nested loops using ij indexes")
    for i in range(len(matrix)):  # outer loop (i), built on length of matrix (rows)
        for j in range(len(matrix[i])):  # inner loop (j), built on length of items (columns)
            print(matrix[i][j], end=" ")  # [i][j] is 2D representation, end changes newline to space
        print()


# Enhanced nested for loops, row and col variables
def print_matrix2(matrix):
    print("Enhanced nested for loops")
    for row in matrix:  # short hand row iterator, index is not required
        for col in row:  # short hand column iterator
            print(col, end=" ")
        print()


# For loop with shortcut (*) row expansion
def print_matrix3(matrix):
    print("For loop with shortcut (*) row expansion")
    for row in matrix:
        print(*row)  # pythons has (*) that is one line expansion of row into columns


def test_matrices():
    # setup some text matrices
    keypad = [[1, 2, 3],
              [4, 5, 6],
              [7, 8, 9],
              [" ", 0, " "]]

    keyboard = [["`", 1, " ", 2, " ",3, " ",  4, " ", 5, " ", 6, " ", 7, " ", 8, " ", 9, " ", 0, " ", "-"," ", "="],
                [" ", " ", "Q", " ", "W", " ", "E", " ", "R", " ", "T", " ", "Y", " ", "U", " ", "I", " ", " ", "O", " ", "P", " ", "[", " ", "]", " ", "\\"],
                [" ", " ", " ", "A", " ", "S", " ", "D", " ", "F", " ", "G", " ", "H", " ", "J", " ", "K", " ", "L", " ", ";", " ", "'"],
                [" ", " ", " ", " ", "Z", " ", "X", " ", "C", " ", "V", " ", "B", " ", "N", " ", "M", " ", ",", " ", ".", " ", "/"]]

    numbers = [
            [0, 1], # binary
            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], # decimal
            [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "A", "B", "C", "D", "E", "F"] # hexadecimal
            ]
    

    # pack into a list of matrices with titles
    matrices = [
        ["Keypad", keypad], 
        ["Keyboard", keyboard], 
        ["Number Systems", numbers]
    ]

    # loop 2D matrix with returning list in [key, value] arrangement
    for title, matrix in matrices:  # unpack title and matrix as variables
        
        # formatted message with concatenation
        print(title, len(matrix), "x", "~" + str(len(matrix[0])))  
        
        # use three different methods
        print_matrix1(matrix)
        print_matrix2(matrix)
        print_matrix3(matrix)
        # blank link in between
        print()


# tester section
if __name__ == "__main__":
    test_matrices()
Keypad 4 x ~3
Classic nested loops using ij indexes
1 2 3 
4 5 6 
7 8 9 
  0   
Enhanced nested for loops
1 2 3 
4 5 6 
7 8 9 
  0   
For loop with shortcut (*) row expansion
1 2 3
4 5 6
7 8 9
  0  

Keyboard 4 x ~24
Classic nested loops using ij indexes
` 1   2   3   4   5   6   7   8   9   0   -   = 
    Q   W   E   R   T   Y   U   I     O   P   [   ]   \ 
      A   S   D   F   G   H   J   K   L   ;   ' 
        Z   X   C   V   B   N   M   ,   .   / 
Enhanced nested for loops
` 1   2   3   4   5   6   7   8   9   0   -   = 
    Q   W   E   R   T   Y   U   I     O   P   [   ]   \ 
      A   S   D   F   G   H   J   K   L   ;   ' 
        Z   X   C   V   B   N   M   ,   .   / 
For loop with shortcut (*) row expansion
` 1   2   3   4   5   6   7   8   9   0   -   =
    Q   W   E   R   T   Y   U   I     O   P   [   ]   \
      A   S   D   F   G   H   J   K   L   ;   '
        Z   X   C   V   B   N   M   ,   .   /

Number Systems 3 x ~2
Classic nested loops using ij indexes
0 1 
0 1 2 3 4 5 6 7 8 9 
0 1 2 3 4 5 6 7 8 9 A B C D E F 
Enhanced nested for loops
0 1 
0 1 2 3 4 5 6 7 8 9 
0 1 2 3 4 5 6 7 8 9 A B C D E F 
For loop with shortcut (*) row expansion
0 1
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9 A B C D E F

def print_matrix1(matrix):
    print("Classic nested loops using ij indexes")
    for i in range(len(matrix)):
        for j in range(len(matrix[i])):
            print(matrix[i][j], end=" ")
        print()

# Enhanced nested for loops, row and col variables
def print_matrix2(matrix):
    print("Enhanced nested for loops")
    for row in matrix:
        for col in row:
            print(col, end=" ")
        print()

# For loop with shortcut (*) row expansion
def print_matrix3(matrix):
    for row in matrix:
        print(*row)

def print_christmas_tree():
    tree = [
        [" ", " ", "*", " ", " ", " "],
        [" ", "*", "*", "*", " ", " "],
        ["*", "*", "*", "*", "*", "*"],
        [" ", " ", "*", " ", " ", " "],
        [" ", " ", "*", " ", " ", " "],
        [" ", " ", "*", " ", " ", " "]
    ]


    print("Christmas Tree (Kind-Of) :) ")
    print_matrix3(tree)

# tester section
if __name__ == "__main__":
    print_christmas_tree()
Christmas Tree (Kind-Of) :) 
    *      
  * * *    
* * * * * *
    *      
    *      
    *      

JavaScript 2D array

Example below populate a 2D array. Key concepts are ij loop and assignments. Observe the object that is created in console. Learn the basics of iteration through 2D array in JavaScript.

  • Candy challenge:Work of pairs. Create one of the Python examples (christmas tree, keyboard, ...). Use the element.append to output within the notebook. As you work on JavaScript make sure your development enviornment is setup like JavaScript programmer.
<script>
// Create a multiplication table
function createMultiplicationTable() {
  var table = document.createElement("table");

  for (var i = 1; i <= 10; i++) {
    var row = document.createElement("tr");

    for (var j = 1; j <= 10; j++) {
      var cell = document.createElement("td");
      var result = i * j;
      var text = document.createTextNode(i + " x " + j + " = " + result);
      cell.appendChild(text);
      row.appendChild(cell);
    }

    table.appendChild(row);
  }

  return table;
}

// Output the multiplication table in the notebook
var output = document.createElement("div");
output.append(createMultiplicationTable());
    document.body.appendChild(output);
</script>

Monkey Jumpers Poem

Here are some of the key parts of these arrays

  • Build ASCII monkeys, 5 different monkeys using ASCII Art for the "Monkey Jumpers" countdown poem
  • ANSII Color codes are added to each Monkey
  • Candy Challenge:Print monkeys horizontally versus vertically.
import time
from IPython.display import clear_output

def main():    
    # ANSI Color Codes
    Red = "\u001b[31m"
    Green = "\u001b[32m"
    Yellow = "\u001b[33m"
    Blue = "\u001b[34m"
    Magenta = "\u001b[35m"

    monkeys = [
        [
            Red,
            "ʕง ͠° ͟ل͜ ͡°)ʔ ",
            "  \\_⏄_/  ",
            "  --0--   ",
            "  ⎛   ⎞   "
        ],
        [
            Green,
            " ʕ༼ ◕_◕ ༽ʔ ",
            "  \\_⎏_/  ",
            "  ++1++  ",
            "   ⌋ ⌊   "
        ],
        [
            Yellow,
            " ʕ(▀ ⍡ ▀)ʔ",
            "  \\_⎐_/ ",
            "  <-2->  ",
            "  〈  〉 "
        ],
        [
            Blue,
            "ʕ ͡° ͜ʖ ° ͡ʔ",
            "  \\_⍾_/  ",
            "  ==3==  ",
            "  _/ \\_  "
        ],
        [
            Magenta,
            "  (◕‿◕✿) ",
            "  \\_⍾_/ ",
            "  ==4==  ",
            "  _/ \\_ "
        ]
    ]

    for i in range(len(monkeys), -1, -1):
        clear_output(wait=True)
        
        print("Nursery Rhyme")
        print(str(i) + " little monkeys jumping on the bed...")

        for row in range(i - 1, -1, -1):
            for col in range(len(monkeys[row])):
                print(monkeys[row][col] + " ")

            print("\u001b[0m")
            
        time.sleep(2)

    clear_output(wait=True)
    print("No more monkeys jumping on the bed")
    print("0000000000000000000000000000000000")
    print("             THE END              ")


if __name__ == "__main__":
    main()
No more monkeys jumping on the bed
0000000000000000000000000000000000
             THE END              

Animation, the Energetic versus Lazy Programmer methods

Animation is done like the old Disney films, lots of little images put togehter. In these examples we eliminate using a 2D array, but simulate int with a sequence of print statements.

  • This 1st sequence is a lot of lines of code.
  • The 2nd takes the lazy programmer method to do the same.
  • Candy challenge:Make your own ASCII art animation.

Fish Animation

import time # used for delay
from IPython.display import clear_output  # jupyter specific clear


# ANSI Color Codes
OCEAN_COLOR = u"\u001B[34m\u001B[2D"
FISH_COLOR = u"\u001B[36m\u001B[2D"
RESET_COLOR = u"\u001B[0m\u001B[2D"

def fish_print(position):  # print fish with colors and leading spaces according to position
    clear_output(wait=True)
    print(RESET_COLOR)

    sp = " " * position
    print(sp + "     ><(((('> ")
    print(sp + "   ><(((('>   ")
    print(FISH_COLOR, end="")
    print(sp + "><(((('>     ")
    print(sp + "   ><(((('>   ")
    print(sp + "     ><(((('> ")
    print(OCEAN_COLOR + "--"*32 + RESET_COLOR)


def fish():  # fish function, loop/controller for animation speed and times
    # loop control variables
    start = 0  # start at zero
    distance = 60  # how many times to repeat
    step = 2  # count by 2

    # loop purpose is to animate fish swimming
    for position in range(start, distance, step):
        fish_print(position)  # call to function with parameter
        time.sleep(.2)

        
fish() # activate/call fish function
                                                               ><(((('> 
                                                             ><(((('>   
                                                          ><(((('>     
                                                             ><(((('>   
                                                               ><(((('> 
----------------------------------------------------------------
"""
* Creator: Nighthawk Coding Society
Sailing Ship Animation (programatic method)
"""

import time # used for delay
from IPython.display import clear_output  # jupyter specific clear


# ANSI Color Codes
OCEAN_COLOR = u"\u001B[34m\u001B[2D"
SHIP_COLOR = u"\u001B[35m\u001B[2D"
RESET_COLOR = u"\u001B[0m\u001B[2D"

def ship_print(position):  # print ship with colors and leading spaces according to position
    clear_output(wait=True)
    print(RESET_COLOR)
    
    sp = " " * position
    print(sp + "    |\   ")
    print(sp + "    |/   ")
    print(SHIP_COLOR, end="")
    print(sp + "\__ |__/ ")
    print(sp + " \____/  ")
    print(OCEAN_COLOR + "--"*32 + RESET_COLOR)


def ship():  # ship function, loop/controller for animation speed and times
    # loop control variables
    start = 0  # start at zero
    distance = 60  # how many times to repeat
    step = 2  # count by 2

    # loop purpose is to animate ship sailing
    for position in range(start, distance, step):
        ship_print(position)  # call to function with parameter
        time.sleep(.2)

        
ship() # activate/call ship function
                                                              |\   
                                                              |/   
                                                          \__ |__/ 
                                                           \____/  
----------------------------------------------------------------