Microsoft Interview Question
Software EngineersCountry: India
Interview Type: In-Person
// C++ program to implement your own tail
#include <bits/stdc++.h>
using namespace std;
#define SIZE 100
// Utility function to sleep for n seconds
void sleep(unsigned int n)
{
clock_t goal = n * 1000 + clock();
while (goal > clock());
}
// function to read last n lines from the file
// at any point without reading the entire file
void tail(FILE* in, int n)
{
int count = 0; // To count '\n' characters
// unsigned long long pos (stores upto 2^64 – 1
// chars) assuming that long long int takes 8
// bytes
unsigned long long pos;
char str[2*SIZE];
// Go to End of file
if (fseek(in, 0, SEEK_END))
perror("fseek() failed");
else
{
// pos will contain no. of chars in
// input file.
pos = ftell(in);
// search for '\n' characters
while (pos)
{
// Move 'pos' away from end of file.
if (!fseek(in, --pos, SEEK_SET))
{
if (fgetc(in) == '\n')
// stop reading when n newlines
// is found
if (count++ == n)
break;
}
else
perror("fseek() failed");
}
// print last n lines
printf("Printing last %d lines -\n", n);
while (fgets(str, sizeof(str), in))
printf("%s", str);
}
printf("\n\n");
}
I just wrote this .. and I believe it is beautiful. From elegance perspective. Hence, sharing.
def tail_function( file_name , n ) {
last_n_lines = list( [0:n] ) as { null }
cur_inx = 0
lc = 0
for ( line : file(file_name) ){
lc += 1
cur_inx %= n
last_n_lines[cur_inx] = line
cur_inx += 1
}
// print back the last_n_lines, imagining a circular buffer
start_inx = lc % n
for ( [start_inx:n] ){ (x = last_n_lines[$]) || x == null || println(x) }
for ( [0:start_inx] ){ (x = last_n_lines[$]) || x == null || println(x) }
}
tail_function( @ARGS[0] , @ARGS[1])
create a queue with size 10, start reading the file line by line and as you do so, insert them in the queue, keeping on popping elements from the queue if max size reached. Towards the end you will have last ten lines of the file.
- avm008 October 28, 2019