nus-cs2030 / 2021-s1

27 stars 48 forks source link

AY 19/20 Special Semester 1 Q10 #567

Open chingh20 opened 3 years ago

chingh20 commented 3 years ago

Hi, I am trying 19/20 special semester 1 pyp, and I am having trouble understanding and passing the second test case for number 10.

I'm not sure why the second test case is supposed to print 2345432 instead of 3454324, which is the substring(1,8) of "2345432" + "4321". My speculation is that the functions inside map and flatMap are not applied on the value yet, so the value of the CachedString remains the same. However this confuses me on when the the functions inside map and flatMap will actually be applied on the value.

Can someone please explain this?

Below is a screenshot of the problem and my code for reference.

Screenshot (78)

Screenshot (77)

kieron560 commented 3 years ago

Hi, I just took a look at the Java API, and I found that the for substring() method, the starting index and the ending index is indexed at 0 (meaning the first character of the string is index 0), which means your jshell computation is by right correct, but the question's substring() method is indexed at 1 (first character is index 1 instead of 0), hence this confusion. If you notice, your answer is just one character to the right from the actual answer.

PS I haven't really tried this question out myself, but this seems to be the problem, but I don't think your code is at fault here, unless I'm missing something myself haha

chingh20 commented 3 years ago

@kieron560 I think the problem is using the substring method for string from the Java API though, so this shouldn't be a problem. thank you for helping though! I've tried creating another String variable to store "" until the get() method is called, but I realized that if forEach doesn't use get(), the get() method would never be called and the String variable would be empty, and the forEach will always print "Answer: ". If the String variable stores this.supply.get() at the constructor, then the forEach will still print everything after the transformations ("3454324"). I'm not sure if there is a way to store the value of the original supplier without transforming it after calling map and flatMap. Screenshot (82)