teaching machines

CS 145 Lecture 19 – 2-D arrays

November 14, 2011 by . Filed under cs145, fall 2011, lectures.

Agenda

What does this do?

  1. public String[] fooize(String[] list) {
      String[] newList = new String[list.length];
      for (int i = 0; i < list.length; ++i) {
        newList[i] = list[list.length - 1 - i];
      }
      return newList;
    }

  2. public void whizpop(int[] list, int flerp) {
      for (int i = 0; i < list.length; ++i) {
        if (list[i] > flerp) {
          list[i] = flerp;
        }
      }
    }

Code

Imager.java

package lecture;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;

public class Imager {
  public static void main(String[] args) throws IOException {
    int width = 512;
    int height = 256;

    int[][] pixels = new int[height][width];
    
//    noisify(pixels);
    stripes(pixels);
    writeToFile(pixels);
  }

  private static void noisify(int[][] pixels) {
    Random jen = new Random();
    for (int r = 0; r < pixels.length; ++r) {
      for (int c = 0; c < pixels[0].length; ++c) {
        pixels[r][c] = jen.nextInt(256);
      }
    }
  }
  
  private static void checks(int[][] pixels) {
    for (int r = 0; r < pixels.length; ++r) {
      for (int c = 0; c < pixels[0].length; ++c) {
        if (r * c % 2 == 0) {
          pixels[r][c] = 0;
        } else {
          pixels[r][c] = 255;
        }
      }
    }
  }
  
  private static void stripes(int[][] pixels) {
    for (int r = 0; r < pixels.length; ++r) {
      for (int c = 0; c < pixels[0].length; ++c) {
        if (r / 5 % 2 == 0) {
          pixels[r][c] = 0;
        } else {
          pixels[r][c] = 255;
        }
      }
    }
  }

  private static void writeToFile(int[][] pixels) throws IOException {
    int height = pixels.length;
    int width = pixels[0].length;

    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);

    for (int r = 0; r < height; ++r) {
      for (int c = 0; c < width; ++c) {
        image.setRGB(c, r, new Color(pixels[r][c], pixels[r][c], pixels[r][c]).getRGB());
      }
    }

    ImageIO.write(image, "png", new File("/home/cjohnson/Desktop/foo.png"));
  }
}

Haiku

great game, Minesweeper
but in 1-D it lacks fun
guess, guess, guess, kaboom!