Skip to content

Instantly share code, notes, and snippets.

@happyWinner
Created July 27, 2014 13:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save happyWinner/aace24b9511a40db764f to your computer and use it in GitHub Desktop.
Save happyWinner/aace24b9511a40db764f to your computer and use it in GitHub Desktop.
/**
* A monochrome screen is stored as a single array of bytes, allowing eight consecutive pixels to be stored in one byte.
* The screen has width w, where w is divisible by 8 (that is, no byte will be split across rows).
* The height of the screen, of course, can be derived from the length of the array and the width.
* Implement a function drawHorizontalLine(byte[] screen, int width, int x1, int x2, int y)
* which draws a horizontal line from (x1, y) to (x2, y).
*
* Time Complexity: O(x2 - x1)
* Space Complexity: O(1)
*/
public class Question5_8 {
public void drawHorizontalLine(byte[] screen, int width, int x1, int x2, int y) {
int height = screen.length / (width / 8);
if (y < 0 || y >= height || x1 < 0 || x1 >= screen.length * 8 || x2 < 0 || x2 >= screen.length * 8) {
return;
}
int idx = y * (width / 8);
int idx1 = idx + (x1 / 8);
int idx2 = idx + (x2 / 8);
for (int i = idx1 + 1; i < idx2; ++i) {
screen[i] = (byte) 0xFF;
}
byte mask1 = (byte) (0xff >>> x1 % 8);
byte mask2 = (byte) (~((1 << (7 - x2 % 8)) - 1));
if (idx1 == idx2) {
screen[idx1] |= (mask1 & mask2);
} else {
screen[idx1] |= mask1;
screen[idx2] |= mask2;
}
}
public static void main(String[] args) {
Question5_8 question5_8 = new Question5_8();
byte[] screen = new byte[12];
int width = 4;
for (int i = 0; i < screen.length / width; ++i) {
for (int j = 0; j < width; ++j) {
System.out.print(screen[i * width + j]);
}
System.out.println();
}
System.out.println();
question5_8.drawHorizontalLine(screen, width * 8, 9, 26, 1);
for (int i = 0; i < screen.length / width; ++i) {
for (int j = 0; j < width; ++j) {
System.out.print(screen[i * width + j]);
}
System.out.println();
}
System.out.println();
screen = new byte[12];
question5_8.drawHorizontalLine(screen, width * 8, 1, 5, 0);
for (int i = 0; i < screen.length / width; ++i) {
for (int j = 0; j < width; ++j) {
System.out.print(screen[i * width + j]);
}
System.out.println();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment