Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

How to substract the smallest element of an arraylist from each element  RSS feed

 
dhrubo bhattacharjee
Greenhorn
Posts: 20
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Dave Tolls
Rancher
Posts: 2914
35
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What is going to be the value of list.get(0) after the first time round that loop?

That should answer your question.
 
dhrubo bhattacharjee
Greenhorn
Posts: 20
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Campbell Ritchie
Marshal
Posts: 55698
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why are you sorting the List?
 
Dave Tolls
Rancher
Posts: 2914
35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the subtraction part is supposed to be separate from the data entry part.
At least that was my assumption.
So imagine the code Collections.sort onwards as being in a method that takes a List...

Obviously, all the usual caveats around "making assumptions" apply.
 
Winston Gutkowski
Bartender
Posts: 10573
65
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!