Google Interview Question
Software Engineer / Developersvoid DrawRectangle(char *Screen, int x1, int y1, int x2, int y2)
{
if (x1>=width || x2>=width || x1>x2 || y1>=height || y2>=height || y1>y2)
return;
for (int i=y1; i<=y2; i++)
{
if (i==y1 || i==y2)
{
for (int j=x1; j<=x2; j++)
setPixel(j,i);
}
else
{
setPixel(x1,i);
setPixel(x2,i);
}
}
}
void setPixel(char *Screen, int x, int y)
{
int n = (y>0) ? y*width : 0;
n+=x;
int a = n/8;
int b = n%8;
Screen[a]+= 256>>b;
}
From function signature it looks like line draw function:
1) Find slope between (x1, y1) and (x2, y2). m= (y2-y1)/(x2-x1)
2) User linear equation, y = m*x + b, find out b.
3) Now apply all x point between x1 to x2 and apply to linear equation and find all y point.
4) Set pixels in all x, y
Repeat above for all 4 edges of rectangle.
// Write a function void DrawRectangle(char *Screen, int x1, int y1, int
// x2, int y2). Height and width of the monitor is known. To set a pixel,
// you need to set that particular bit of the screen.
// Pixels for 1080p (FULL HD screen) -- 1920x1080
#define WIDTH 1920
#define HEIGHT 1080
void DrawRectangle(char *Screen, int x1, int y1, int x2, int y2){
for (size_t i = x1; i <= x2; i++) {
for (size_t j = y1; j <= y2; j++) {
if(j == y1 || j == y2 || i == x1 || i == x2){
Screen[WIDTH * j + i] = 0xFF;
}
}
}
}
Is the monitor a bit array? If so, is the question very simple since we only need to set some bits in four boarders of the rectangle?
- chenming831@gmail.com May 29, 2010