Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Last 100 bytes" Interview Scenario

Tags:

java

algorithm

I got this question in an interview the other day and would like to know some best possible answers(I did not answer very well haha):

Scenario: There is a webpage that is monitoring the bytes sent over a some network. Every time a byte is sent the recordByte() function is called passing that byte, this could happen hundred of thousands of times per day. There is a button on this page that when pressed displays the last 100 bytes passed to recordByte() on screen (it does this by calling the print method below).

The following code is what I was given and asked to fill out:

public class networkTraffic {     public void recordByte(Byte b){     }     public String print() {     } } 

What is the best way to store the 100 bytes? A list? Curious how best to do this.

like image 695
Yottagray Avatar asked Nov 02 '11 19:11

Yottagray


2 Answers

Something like this (circular buffer) :

byte[] buffer = new byte[100]; int index = 0;  public void recordByte(Byte b) {    index = (index + 1) % 100;    buffer[index] = b;  }  public void print() {    for(int i = index; i < index + 100; i++) {        System.out.print(buffer[i % 100]);    } } 

The benefits of using a circular buffer:

  1. You can reserve the space statically. In a real-time network application (VoIP, streaming,..)this is often done because you don't need to store all data of a transmission, but only a window containing the new bytes to be processed.
  2. It's fast: can be implemented with an array with read and write cost of O(1).
like image 100
Heisenbug Avatar answered Oct 13 '22 04:10

Heisenbug


I don't know java, but there must be a queue concept whereby you would enqueue bytes until the number of items in the queue reached 100, at which point you would dequeue one byte and then enqueue another.

public void recordByte(Byte b) {    if (queue.ItemCount >= 100)   {     queue.dequeue();       }   queue.enqueue(b); } 

You could print by peeking at the items:

public String print()  {    foreach (Byte b in queue)   {     print("X", b);  // some hexadecimal print function   } }   
like image 29
Duck Avatar answered Oct 13 '22 04:10

Duck