Sunday 12 November 2017

java - Effectively print a long sequence

itemprop="text">

I've to print a number which is a huge
sequence of 5's and 3's (upto 100,000 ints). Instead of storing it in array, I just kept
their count in noOfThrees and
noOfFives.



For
simplicity call this number x.
.



Since I have to print the largest number in
the sequence, x will be initially 5's and then followed with
3's (I have working logic to print if there's no 5's or no
3's)




To print the number, I am using
a for loop like this :



for(int
i=0; i System.out.print(5);
for(int i=0;
i
System.out.print(3);


But
if x is a 100,000 long int number, it takes about 4-5sec to
print it on console which is not
desirable.




My
take:




  • If the
    noOfFives is even, then print 55 in
    the for loop which increases the performance by x2 and increment the loop by two,
    else

  • Use the same for loop as above. Same goes for
    noOfThrees.



But
the problem here is if it's odd, it will again end up printing in steps of 1. How do I
effectively print this sequence?


class="post-text" itemprop="text">
class="normal">Answer



If you
think that the number of print calls is the issue, you could
reduce it to just 1: put the right number of 3s and 5s into a char array, then print
that:




char[] cs = new
char[noOfFives + noOfThrees];
Arrays.fill(cs, 0, noOfFives,
'5');
Arrays.fill(cs, noOfFives, cs.length,
'3');
System.out.print(cs);


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...