Jump to content
Existing user? Sign In

Sign In



Sign Up

[Ruse] Improved Random Enum Method


Flub

Recommended Posts

Hey everyone.

This is a better way to select a random entry from an enum :) 

An example of an enum group is:

@AllArgsConstructor
public enum SlayerTasks {


    DARKWIZARDS(SlayerMaster.SUMONA, 9203, "Find Darkblue Wizards at ::wizards", 1500, new Position(2903, 5203)),
    HEATED_PYRO(SlayerMaster.SUMONA, 172, "Heated Pyro can be found in the Elite Teleports", 1500, new Position(2863, 5354, 2)),
    PURPLE_WYRM(SlayerMaster.SUMONA, 9935, "Purple Wyrm can be found in the Elite Teleports", 1500, new Position(2602, 5713)),
    TRINITY(SlayerMaster.SUMONA, 170, "Trinity can be found in the Elite Teleports", 1500, new Position(2273, 4680, 1)),
    CLOUD(SlayerMaster.SUMONA, 169, "Cloud can be found in the Elite Teleports", 1500, new Position(1908, 4367));


    private SlayerMaster taskMaster;
    private int npcId;
    private String npcLocation;
    private int XP;
    private Position taskPosition;
}

Enums are incredibly useful for storing multiple types of data. You'll see them used in a load of places!

Now, the usual way to select a random entry from your enum list would be;

SlayerTasks task = SlayerTasks.values()[Misc.random(SlayerTasks.values().length - 1)];

Of course - this does work. However, why not improve it!

Here is a new method for you.. I've added mine into Misc.java along with my randomItem method!

public static <T extends Enum<?>> T randomEnum(Class<T> clazz){
        SecureRandom random = new SecureRandom();
        int x = random.nextInt(clazz.getEnumConstants().length);
        return clazz.getEnumConstants()[x];
    }

Now, lets select a entry from our enum using this new method!

(If added in Misc.java)

SlayerTasks task = Misc.randomEnum(SlayerTasks.class);

How much cleaner is that!

You **must** add .class to the end of the name in this bracket.

You can then use the entry as required!

E.g.

SlayerMaster master = task.taskMaster;
int npcId = task.npcId;
String npcLocation = task.npcLocation;
int XP = task.XP;
Position taskPosition = task.taskPosition;

Hopefully you can use this to clean up some code 😛

Link to comment
Share on other sites

  • 7 months later...
  • 4 months later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Contact

ltlimes

RSPS Partners

RedemptionRSPS

What is a RSPS?

A RSPS, also known as RuneScape private server, is an online game based on RuneScape, and controlled by independent individuals.

Popular RSPS Servers

oldschoolrsps Runewild RedemptionRSPS

Disclaimer

Runesuite is not affiliated with runescape, jagex, rune-server and runelocus in any way & exists solely for educational purposes.

×
×
  • Create New...