Discuss Scratch

JhonnyTwest
New Scratcher
3 posts

Help!!

program to find second largest number in a list
anyone knows how to make this code in scratch
Spentine
Scratcher
1000+ posts

Help!!

when gf clicked
set [largest number v] to [-Infinity]
set [second largest number v] to [-Infinity]
set [index v] to (0)
repeat (length of [list v])
change [index v] by (1)
if <not <(item (index) of [list v]) < (largest number)>> then
set [second largest number v] to [largest number v]
set [largest number v] to (item (index) of [list v])
else
if <(item (index) of [list v]) > (second largest number)> then
set [second largest number v] to (item (index) of [list v]

This is untested because I'm on mobile, but in theory it should work.

examples:
3, 2, 1 will return 2
4, 4, 8 will return 4
1 will return -Infinity

Hope this helps!

Last edited by Spentine (Jan. 8, 2023 20:17:36)

medians
Scratcher
1000+ posts

Help!!

Do you mean something like this?

Just copies over everything from the list so you can delete it if you want to save the original list. Then it repeats finding the max until the length is 2 and removes the index that is the largest. And then takes the last element, which will be the 2nd largest num
JhonnyTwest
New Scratcher
3 posts

Help!!

Thank You

Last edited by JhonnyTwest (Jan. 8, 2023 22:17:58)

Powered by DjangoBB