Morgan Stanley Interview Question
InternsCountry: India
Interview Type: In-Person
I agree with sk.
Just use FileChannel in Java. Truncate function is available.
Following is the example.
Initial file
1234 5678 1234 56
left-shift 6-9th character by 1 position
123456788 1234 56
left-shift 11-14th character by 2 position
12345678123434 56
left-shift 16-17th character by 3 position
12345678123456 56
The file has 17 bytes.17/5 is 3
Now truncate by 3
fnDefrag(string file)
{
using (var stream = File.Open(file, FileMode.Open))
{
byte[] barry=new byte[1];
int current=0;
int pivot=0;
while(current<(stream.length-1))
{
stream.position=current;
if((current+1)%5==0)
{
current++;
}
if(current!=pivot)
{
stream.read(barry,current,1);
stream.write(barry,pivot,1);
}
pivot++;
current++;
}
stream.SetLength=pivot;
}
}
int main(int argc, char* argv[])
{
FILE *fp_read, *fp_write;
int counter = 1, i = 0;
char ch;
fp_read = fopen("input_file.txt", "r");
fp_write = fopen("input_file.txt", "r+");
if(!fp_read || !fp_write)
{
printf("File not present\n");
exit(1);
}
fseek(fp_read, 0, SEEK_END);
int size = ftell(fp_read);
printf("Size = %d\n", size);
fseek(fp_read, 0, SEEK_SET);
while(counter < size)
{
ch = fgetc(fp_read);
if(counter % 5 != 0)
{
fputc(ch, fp_write);
}
else
i++;
//printf("%c ", ch);
counter++;
}
fclose(fp_read);
fclose(fp_write);
printf("Trucate by %d bytes", i);
//Here truncate the file by "i" size
return 0;
}
void removeBytes(char *s, int interval) {
if (s==nil || interval<=0)
return;
//copy *p to *q if it is NOT on interval
//shift p until '\0'
char *q = s;
char *p = s;
int k = interval;
while (*p != '\0') {
k--;
if (k > 0 && p!=q) {
*q++ = *p++;
}
else if (k==0) {
p++;
k = interval;
}
}
*q = '\0';
}
1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20
We know that we will delete 5, 10 and 15 in this case. So, for the block from index 6-9 will be shifted left 1. block index 11-14 will shift over by 2. 16-19 will shift over by 3. Here we see a pattern. Because of continuous shifts, each block of numbers not divisible by 5 will shift left one more than the last block.
So, something like the following:
}
- SK April 07, 2015