+ 3

Java (Need Help)

https://code.sololearn.com/cvirEMwQI2VO/?ref=app While I was doing the java play/challenge I stumbled across this question and I was wondering if anyone can explain how did it get 51 as the answer? I tried slowly debugging and understand but I just couldn't.... Any help would be appreciated

6th Oct 2017, 10:19 AM
Dexter Siah
Dexter Siah - avatar
4 Réponses
+ 5
It's a 2D-Array stored as a 1D array :) If you look at that double loop, every 100 iterations will make y bigger by 1, and x resets. So at 99, y = 0, x = 99 At 100, y = 1, x = 0 And at 150, y = 1, x = 50 And pixels[i] is set to x+y of course so 1 + 50 = 51. Theres actually a formula for that: To figure out x and y given i: x = i % width y = i / width
6th Oct 2017, 10:34 AM
Schindlabua
Schindlabua - avatar
+ 12
//for y=0 , index can't be greater than 100 obviously , for y=1 & x = 50 , index will be 150 // for index 150 , x+y = 50+1 therefore answer is 51 //hope it helps ☺
6th Oct 2017, 10:30 AM
Gaurav Agrawal
Gaurav Agrawal - avatar
+ 8
So we are going to find pixels[150]. We know that from the loop:- index = x + y * 100; pixels[index] = x + y; Plug in 150 and we will get:- 150 = x + y * 100; pixels[150] = x + y and since the value of x and y falls between 0 and 99 inclusive, then it must be:- x = 50 y = 1 *which satisfy 150 = 50 + 1 * 100 Therefore, pixels[150] = x + y = 50 + 1 = 51.
6th Oct 2017, 10:49 AM
Zephyr Koo
Zephyr Koo - avatar
+ 2
Thank you everyone I figured out why I couldn't find the answer in the beginning..... I totally forgot about simple BODMAS where I need to multiply first before I add.... Which is why I couldn't get the answer. Thank you everyone for answering to my help :)
6th Oct 2017, 1:21 PM
Dexter Siah
Dexter Siah - avatar