nus-cs2030 / 2021-s2

2 stars 2 forks source link

AY20/21 Sem1 Q6b #386

Closed rljw closed 3 years ago

rljw commented 3 years ago

Hi, anyone had any comments for part (b)? I'm not too sure what is expected, as the stream seems to work fine

image

brendancjz commented 3 years ago

Hi, the way this stream was constructed is flawed. This is because there are side effects in this stream, where s, a local variable outside of the lambda expression is being manipulated. But the stream works fine because the .forEach(x -> ...) method allows side effects to occur. A better way to construct the stream would be to use the reduce method. Hope this helps!

int s = IntStream.range(1,100).boxed().reduce(0, (x,y) -> x + y); s;

glennbjorn commented 3 years ago

I did a similar method to @brendancjz. I thought that since the purpose of the stream was just to sum up integers 1 to 99, I didn't see a need to store the result. I also didn't see a need to box the IntStream, so I simply did: IntStream.range(1,100).reduce(0, (x,y) -> x + y)

rljw commented 3 years ago

Ah I get it now, thank you guys!

Zekeseoj commented 3 years ago

hello does anyone know how to do part e for this qn? 1231

bandytan commented 3 years ago

image

I used this reduce method. The accumulator I used (x,y) -> x + y.length(), and the combiner u can just use (p,q) -> p to reduce the stream to the first element.

glennbjorn commented 3 years ago

hello does anyone know how to do part e for this qn? 1231

Hi @Zekeseoj, what I did was add all the words into one line of string before calculating the length. reduce("", (x,y) -> x + y).length() It's an alternative solution that seems to get the answer, so hope this helps!