Microsoft Interview Question
Software EngineersCountry: India
Interview Type: In-Person
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])
- Nits August 15, 2019