posted 2 years ago

Hello, I was trying to substract the smallest element from each elements of an arraylist .here is my code :

and here is my input :

and the output is :

This code is only substracting the smallest element which is 2 from the first index whereas my desired output will be :

Can anyone of you please tell me where I am going wrong?

Thanks

and here is my input :

and the output is :

This code is only substracting the smallest element which is 2 from the first index whereas my desired output will be :

Can anyone of you please tell me where I am going wrong?

Thanks

posted 2 years ago

Thanks, I was able to figure out the mistake, list.get(0) after the first iteration becomes zero, and thus no other values are changed.

works fine now

Dave Tolls wrote:What is going to be the value of list.get(0) after the first time round that loop?

That should answer your question.

Thanks, I was able to figure out the mistake, list.get(0) after the first iteration becomes zero, and thus no other values are changed.

works fine now

Dave Tolls

Master Rancher

Posts: 3330

38

posted 2 years ago

FYI: You could actually do it faster with two loops and no sort: one to find the smallest value and the other to do the "cutting", both of which will take O(n) time ... although you're not likely to see any difference until you have a few thousand values in your list.

Winston

dhrubo bhattacharjee wrote:Thanks, I was able to figure out the mistake, list.get(0) after the first iteration becomes zero, and thus no other values are changed.

FYI: You could actually do it faster with two loops and no sort: one to find the smallest value and the other to do the "cutting", both of which will take O(n) time ... although you're not likely to see any difference until you have a few thousand values in your list.

Winston

"Leadership is nature's way of removing morons from the productive flow" - Dogbert

Articles by Winston can be found here

Don't get me started about those stupid light bulbs. |