Hello experts, I was pondering how to do this in java from a long time . Can u help me figure it out. There is a stream of data which has lines of different length. We have an endofline() function. We want to output lines at random from the stream with equal probability. How will you do it? assuming that we do not want to store anylines in the intermediate datastructures.. is there a way that we can read the lines randomly from the stream itself? Thanks a lot Yours gratefully,
No work and all study makes Jack a dull boy, is that still valid?
Interesting question. First, a minor issue: We have an endofline() function. Is this something that's already been written, or is this what you're trying to write now? What's it do? What's it supposed to do? I'm not sure exactly how this relates to the rest of your question, so for now, I'm going to ignore it. You can read one line at a time from a stream by wrapping it with a BufferedReader, that's easy enough - it's the random access part that's more challenging. Fundamentally, a stream is not designed for random access - just sequential. You can skip ahead, but your ability to move backwards is generally limited. You can do some things, using either mark() and reset(), or using a PushBackInputStream - but it depends on how far you want to move back, and how big a buffer you have (if any) - it gets complicated. There are two basic solutions I can think of (plus various permutations and variations of these which I won't get into). It depends primarily on what you want to mean by outputting lines "at random". 1. If you want to randomly select from all lines available from a stream (including the ones you've already gone past) then you're going to have to store data from the stream in some sort of intermediate data structure. The simplest solution is to read all lines from the stream and store them all in an ArrayList of Strings - then just generate random numbers in the range [0, list.length()-1] to choose one String at a time and output it. 2. If you insist on not using any intermediate data structures, you will never be able to randomly select a line which came before the last one you outputted. But you can, for example, choose a number from 1 to 10, and based on that, output either the first full line after the current stream position, or the tenth, or somethign in between. If you choose 7, then call readLine() 6 times and ignore the result, then call it once more and output the result. Of course, you have to consider the possibility that the stream might reach end-of-file before you get there, and write the program to handle this possibility.