Reputation: 57
I'm just starting with Java, so I'm transcribing some of my Ruby stuff. I have a Ruby function like this, which generates something that looks like an IPv6 address:
def generate_ip()
list = ["a", "b", "c", "d", "e", "f", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"]
address = ""
8.times do
4.times do
address << list.shuffle[5]
end
address << ":"
end
return address[0..-2].to_sym
end
This method simply takes an array of strings and then repeatedly jumbles them up, choosing the 5th element each time to construct the returned string.
As far as I can tell, there's no "shuffle()" method for String Arrays in Java, so I figured I'd write my own. But then I started to get completely mired in sub-problems, such as:
Apparently there's no built-in way to remove items from a String Array, which seems strange -- is that correct? I saw several other SO posts where the responses for this features were a 10-line block of code. So I decided to use ArrayLists, since according to the doc, they have sane methods like size(), get(), and remove(), although...
...I haven't found a way to instantiate them using a literal, or to add multiple items with a single method call. Every tutorial I see (including the official Oracle Java Tutorial) uses multiple calls to ArrayList.add(). That can't be the way to do it, can it?
etc.
So before I go spiraling down into sub-problem land and asking 50 different questions, I thought I'd ask how to solve the most important problem. Is there a simple way to translate the above Ruby code into Java?
FWIW, my in-progress "shuffle" method is below. I'm just looping array.length times, copying/removing a random element from the old array to a new array each time.
public ArrayList<String> shuffle(ArrayList<String> array) {
Random generator = new Random();
ArrayList<String> shuffled = new ArrayList<String>();
for (int i = 0; i > array.size(); i++) {
int index = generator.nextInt(array.size());
String popped = array.get(index);
array.remove(index);
shuffled.add(popped);
}
return shuffled;
}
Upvotes: 2
Views: 281
Reputation: 272367
If you create a List
(either ArrayList
or LinkedList
), you can use Collections.shuffle()
ArrayList and LinkedList are both implementations of the List interface. I suspect either would be ok for your needs here, although the ArrayList would be preferable (being backed by an array). Here's the Java List tutorial.
Arrays are of a fixed length in Java, whereas a List
is variable in size, and so the List
is more appropriate in general for your above conversion. To create a list with a given set of starting elements, see Arrays.asList() e.g.
List stooges = Arrays.asList("Larry", "Moe", "Curly");
Upvotes: 3
Reputation: 41230
Collections.shuffle(List<?> list, Random rnd)
built-in library available in java.
Randomly permute the specified list using the specified source of randomness. All permutations occur with equal likelihood assuming that the source of randomness is fair.
Upvotes: 2