Understanding the pseudocode in the Donald B. Johnson's algorithm - java

Does anyone know the Donald B. Johnson's algorithm, which enumerates all the elementary circuits (cycles) in a directed graph?
I have the paper he had published in 1975, but I cannot understand the pseudocode.
My goal is to implement this algorithm in Java.
Some questions I have, for example, is what is the matrix Ak it refers to. In the pseudocode, it mentions that
Ak:=adjacency structure of strong component K with least
vertex in subgraph of G induced by {s,s+1,....n};
Does that mean I have to implement another algorithm that finds the Ak matrix?
Another question is what the following means?
begin logical f;
Does also the line "logical procedure CIRCUIT (integer value v);" mean that the circuit procedure returns a logical variable? In the pseudocode also has the line "CIRCUIT := f;". What does this mean?
It would be great if someone could translate this 1970's pseudocode to a more modern type of pseudocode so I can understand it
In case you are interested to help but you cannot find the paper please email me at pitelk#hotmail.com and I will send you the paper.

The pseudo-code is reminiscent of Algol, Pascal or Ada.
Does that mean I have to implement another algorithm that finds the Ak matrix?
Ak appears to be a list of arrays of input values having the specified properties. It may be related to the corresponding adjacency matrix, but it's not clear to me. I'm guessing something like this:
int[][] a = new int[k][n];
int[][] b = new int[k][n];
boolean[] blocked = new boolean[n];
int s;
What does logical f mean?
This declares a local variable representing a true or false value, similar to Java's boolean.
logical procedure CIRCUIT (integer value v);
This declares a subprogram named CIRCUIT having a single integer parameter v that is passed by value. The subprogram returns a logical result of true or false, and CIRCUIT := f assigns f as the result. In Java,
boolean circuit(int v) {
boolean f;
...
f = false;
...
return f;
}
The keywords begin and end delimit a block scope that may be nested, so CIRCUIT is nested in the main block and UNBLOCK is nested inside of CIRCUIT. := is assignment; ¬ is not; ∈ is element; ∅ is empty; ≠ is !=; stack and unstack suggest push and pop.
It's only a start, but I hope it helps.
Addendum: On reflection, A and B must be isomorphic.
Here's a very literal outline. I don't know enough about A, B & V to choose a better data structure than arrays.
import java.util.Stack;
public final class CircuitFinding {
static int k, n;
int[][] a = new int[k][n];
int[][] b = new int[k][n];
boolean[] blocked = new boolean[n];
int[] v = new int[k];
int s = 1;
Stack<Integer> stack = new Stack<Integer>();
private void unblock(int u) {
blocked[u] = false;
for (int w : b[u]) {
//delete w from B(u)
if (blocked[w]) {
unblock(w);
}
}
}
private boolean circuit(int v) {
boolean f = false;
stack.push(v);
blocked[v] = true;
L1:
for (int w : a[v]) {
if (w == s) {
//output circuit composed of stack followed by s;
f = true;
} else if (!blocked[w]) {
if (circuit(w)) {
f = true;
}
}
}
L2:
if (f) {
unblock(v);
} else {
for (int w : a[v]) {
//if (v∉B(w)) put v on B(w);
}
}
v = stack.pop();
return f;
}
public void main() {
while (s < n) {
//A:= adjacency structure of strong component K with least
//vertex in subgraph of G induced by {s, s+ 1, n};
if (a[k] != null) {
//s := least vertex in V;
for (int i : v) {
blocked[i] = false;
b[i] = null;
}
L3:
circuit(s);
s++;
} else {
s = n;
}
}
}
}

You can find a Java implementation of this algorithm on github: https://github.com/1123/johnson. It uses the Jung2 java graph library.

Related

How to implement recursive function only using stacks?

I have an assignment where I am given recursive functions, and have to rewrite it using only stacks (no recursion). I do not know how to implement the following function
public static void fnc1(int a, int b) {
if (a <= b) {
int m = (a+b)/2;
fnc1(a, m-1);
System.out.println(m);
fnc1(m+1, b);
}
}
The problem is I cannot figure out how to implement recursive functions where there is head and tail recursion.
I tried to loop through a stack, popping a value (a, b) each time and pushing a new value (a, m-1) or (m+1, b) instead of caling "fnc1()", but the output was always out of order.
EDIT:
Here is my attempted Code:
public static void Fnc3S(int a, int b) {
myStack stack1_a = new myStack();
myStack stack1_b = new myStack();
myStack output = new myStack();
stack1_a.push(a);
stack1_b.push(b);
while(!stack1_a.isEmpty()) {
int aVal = stack1_a.pop();
int bVal = stack1_b.pop();
if(aVal <= bVal) {
int m = (aVal+bVal)/2;
stack1_a.push(aVal);
stack1_b.push(m-1);
output.push(m);
stack1_a.push(m+1);
stack1_b.push(bVal);
}
}
while(!output.isEmpty()) {
System.out.println(output.pop());
}
}
And this outputs:
(a, b) = (0, 3)
Recursive:
0
1
2
3
Stack Implementation:
0
3
2
1
to implement this recursion properly you need to understand order in which execution happens and then insert variables in reverse order (as stack pops latest element):
Check code below with comments:
public static void Fnc3S(int a, int b) {
Stack<Integer> stack = new Stack<>(); // single stack for both input variables
Stack<Integer> output = new Stack<>(); // single stack for output variable
stack.push(a); // push original input
stack.push(b);
do {
int bVal = stack.pop();
int aVal = stack.pop();
if (aVal <= bVal) {
int m = (aVal + bVal) / 2;
output.push(m); // push output
stack.push(m + 1); // start with 2nd call to original function, remember - reverse order
stack.push(bVal);
stack.push(aVal); // push variables used for 1st call to original function
stack.push(m - 1);
} else {
if (!output.empty()) { // original function just returns here to caller, so we should print any previously calculated outcome
System.out.println(output.pop());
}
}
} while (!stack.empty());
}

DFS iterative function does not work properly

I'm trying to do some basic function on a graph (using a boolean matrix). They all work except the DFS one. It give me some random number. I'm trying to resolve this problem since few hours now, but still nothing.. (the code compile, but what it show its wrong). Btw, the result of DFS must be a matrix, with the number of stack, and also the "Unwinding" of each graph vertex.
Where's my error?
My program :
public int[][] DFS(int s) {
Stack<Integer> stack = new Stack<Integer>();
stack.push(s);
int recorder = 1;
int[][] mark = new int[nbs][2];
mark[s][0] = recorder++;
boolean[] decouvert = new boolean[nbs];
while (!stack.isEmpty()) {
s = stack.pop();
mark[s][1] = recorder++;
if (!decouvert[s]) {
decouvert[s] = true;
for (int i = 0; i < nbs; i++) {
if (m[s][i]) {
stack.push(i);
mark[s][0] = recorder++;
}
}
}
}
return mark;
}
Well, I think one problem is the line:
mark[s][0] = recorder++;
If I read your code correctly, it should be mark[i][0]. And then, it just overrides the value even if you have already been in that node before effectively messing up the counter for it.

creating java generic data structure

I am building a data structure to learn more about java. I understand this program might be useless.
Here's what I want. I want to create a data structure that store smallest 3 values. if value is high, then ignore it. When storing values than I also want to put them in correct place so I don't have to sort them later. I can enter values by calling the add method.
so let's say I want to add 20, 10, 40, 30 than the result will be [10,20,30]. note I can only hold 3 smallest values and it store them as I place them.
I also understand that there are a lot of better ways for doing this but again this is just for learning purposes.
Question: I need help creating add method. I wrote some code but I am getting stuck with add method. Please help.
My Thinking: we might have to use a Iterator in add method?
public class MyJavaApp {
public static void main(String[] args){
MyClass<Integer> m = new MyClass<Integer>(3);
m.add(10);
m.add(20);
m.add(30);
m.add(40);
}
}
public class MyClass<V extends Comparable<V>> {
private V v[];
public MyClass(int s){
this.v = (V[])new Object[s];
}
public void add(V a){
}
}
Here is a rough sketch of the add method you have to implement.
You have to use the appropriate implementation of the compareTo method when comparing elements.
public void add(V a){
V temp = null;
if(a.compareTo( v[0]) == -1 ){
/*
keeping the v[0] in a temp variable since, v[0] could be the second
smallest value or the third smallest value.
Therefore call add method again to assign it to the correct
position.
*/
temp = v[0];
v[0] = a;
add(temp);
}else if(a.compareTo(v[0]) == 1 && a.compareTo(v[1]) == -1){
temp = v[1];
v[1] = a;
add(temp);
}else if(a.compareTo(v[1]) == 1 && a.compareTo(v[2]) == -1){
temp = v[2];
v[2] = a;
add(temp);
}
}
Therefore the v array will contain the lowerest elements.
Hope this helps.
A naive, inefficient approach would be (as you suggest) to iterate through the values and add / remove based on what you find:
public void add(Integer a)
{
// If fewer than 3 elements in the list, add and we're done.
if (m.size() < 3)
{
m.add(a);
return;
}
// If there's 3 elements, find the maximum.
int max = Integer.MIN_VALUE;
int index = -1;
for (int i=0; i<3; i++) {
int v = m.get(i);
if (v > max) {
max = v;
index = i;
}
}
// If a is less than the max, we need to add it and remove the existing max.
if (a < max) {
m.remove(index);
m.add(a);
}
}
Note: this has been written for Integer, not a generic type V. You'll need to generalise. It also doesn't keep the list sorted - another of your requirements.
Here's an implementation of that algorithm. It consists of looking for the right place to insert. Then it can be optimized for your requirements:
Don't bother looking past the size you want
Don't add more items than necessary
Here's the code. I added the toString() method for convenience. Only the add() method is interesting. Also this implementation is a bit more flexible as it respects the size you give to the constructor and doesn't assume 3.
I used a List rather than an array because it makes dealing with generics a lot easier. You'll find that using an array of generics makes using your class a bit more ugly (i.e. you have to deal with type erasure by providing a Class<V>).
import java.util.*;
public class MyClass<V extends Comparable<V>> {
private int s;
private List<V> v;
public MyClass(int s) {
this.s = s;
this.v = new ArrayList<V>(s);
}
public void add(V a) {
int i=0;
int l = v.size();
// Find the right index
while(i<l && v.get(i).compareTo(a) < 0) i++;
if(i<s) {
v.add(i, a);
// Truncate the list to make sure we don't store more values than needed
if(v.size() > s) v.remove(v.size()-1);
}
}
public String toString() {
StringBuilder result = new StringBuilder();
for(V item : v) {
result.append(item).append(',');
}
return result.toString();
}
}

Learning to debug in Java

I'm both learning to use the JPDA on Netbeans and solving the Prime Generator problem of Sphere's Online Judge.
I've been reading this tutorial on netbeans.org about he JPDA, but haven't found it of much help.
This code, which is based on a Sieve of Eratostenes implementation provided by starblue here, is running like this:
2
1 10
//here the primes between 1 and 10 should print
3 5
//here the primes between 3 and 5 should print
package sphere;
/**
*
* #author Administrator
*/
//import java.util.ArrayList;
import java.util.BitSet;
import java.lang.Math.*;
import java.util.ArrayList;
public class Main
{
public static int ApproximateNthPrime(int nn)
{
double n = (double)nn;
double p;
if (nn >= 7022)
{
p = n * Math.log(n) + n * (Math.log(Math.log(n)) - 0.9385);
}
else if (nn >= 6)
{
p = n * Math.log(n) + n * Math.log(Math.log(n));
}
else if (nn > 0)
{
p = new int[] { 2, 3, 5, 7, 11 }[nn - 1];
}
else
{
p = 0;
}
return (int)p;
}
// Find all primes up to and including the limit
public static BitSet SieveOfEratosthenes(int limit)
{
final BitSet primes = new BitSet();
primes.set(0,false);
primes.set(1,false);
primes.set(2,limit,true);
for (int i =0; i*i<limit;i++)
{
if (primes.get(i))
{
for (int j=i*1; j<limit;j+=1)
{
primes.clear(j);// hace que el indice j sea false (no primo)
}
}
}
return primes;
}
public static ArrayList<Integer> GeneratePrimesSieveOfEratosthenes(int n)
{
int limit = ApproximateNthPrime(n);
BitSet bits = SieveOfEratosthenes(limit);
ArrayList <Integer> primes = new ArrayList<Integer>();
for (int i = 0, found = 0; i < limit && found < n; i++)
{
if (bits.get(i))
{
primes.add(i);
found++;
}
}
return primes;
}
public static void main (String[] args) throws java.lang.Exception
{
java.io.BufferedReader r = new java.io.BufferedReader (new java.io.InputStreamReader (System.in));
String s;
s= r.readLine();
int test_cases = Integer.parseInt(s);
int case_counter =0;
while (case_counter<test_cases) {
// System.out.println(s);
s = r.readLine();
String [] splitted = s.split(" ");
int lower_bound = Integer.parseInt(splitted[0]);
int upper_bound = Integer.parseInt(splitted[1]);
ArrayList <Integer> primesList= GeneratePrimesSieveOfEratosthenes(upper_bound);
for (int i =0; i<primesList.size();i++){
if (primesList.get(i)<=lower_bound)System.out.println(primesList.get(i));
}
case_counter++;
System.out.println(" "); // space that separates test cases
}
}
}
I know that the ArrayList primesList isn't getting initialized and I'm suspicious of this bit of code, cause honestly, I don't quite understand it:
if (primes.get(i))
{
for (int j=i*1; j<limit;j+=1)
{
primes.clear(j);
}
}
It occurred to me to use a conditional breakpoint here with the condition of:
primes.get(j)==false
But I'm not sure if I'm able to get meaningful info this way. These are the screens I'm getting:
alt text http://img525.imageshack.us/img525/6238/breakpoints.jpg
alt text http://img98.imageshack.us/img98/5262/watchesz.jpg
I don't know how to get useful info out of this.
My questions are:
a)I want to watch the primes BitSet as its going through this loop.
How do I do that?
b) What's exactly wrong with this code?
How did you spot it using the debugger?
Please, mention the step-by-step process.
So, I extracted out the following method:
private static void printPrimes(int lower_bound, int upper_bound) {
ArrayList<Integer> primesList = GeneratePrimesSieveOfEratosthenes(upper_bound);
for (int i = 0; i < primesList.size(); i++) {
if (primesList.get(i) <= lower_bound)
System.out.println(primesList.get(i));
}
}
and changed the main() method to just call that with a couple of arbitrary arguments (10 and 100), because I didn't want to mess around with the console and the debugger at the same time. I then (I'm using Eclipse) put ordinary breakpoints at the beginning and end lines of ApproximateNthPrime(), SieveOfEratosthenes() and GeneratePrimesSieveOfEratosthenes() to make sure they were being called. (By the way, Java convention, unlike C#, is for method names to start with a lower-case letter.)
All that was without bothering to understand the code. :) However, after the first run-through, it was pretty clear that the problem is that the BitSet produced by SieveOfEratosthenes() is always empty (or rather, always entirely false). I haven't used the NetBeans debugger, but I suspect the "Local Variables" tab is your friend here.
I'm not going to do your homework for you. :) But the idea of the Sieve of Eratosthenes is to skip the prime numbers and only eliminate the non-primes. Examine your SieveOfEratosthenes() method and ask yourself: when will it skip a number?

Picking a random element from a set

How do I pick a random element from a set?
I'm particularly interested in picking a random element from a
HashSet or a LinkedHashSet, in Java.
Solutions for other languages are also welcome.
int size = myHashSet.size();
int item = new Random().nextInt(size); // In real life, the Random object should be rather more shared than this
int i = 0;
for(Object obj : myhashSet)
{
if (i == item)
return obj;
i++;
}
A somewhat related Did You Know:
There are useful methods in java.util.Collections for shuffling whole collections: Collections.shuffle(List<?>) and Collections.shuffle(List<?> list, Random rnd).
In Java 8:
static <E> E getRandomSetElement(Set<E> set) {
return set.stream().skip(new Random().nextInt(set.size())).findFirst().orElse(null);
}
Fast solution for Java using an ArrayList and a HashMap: [element -> index].
Motivation: I needed a set of items with RandomAccess properties, especially to pick a random item from the set (see pollRandom method). Random navigation in a binary tree is not accurate: trees are not perfectly balanced, which would not lead to a uniform distribution.
public class RandomSet<E> extends AbstractSet<E> {
List<E> dta = new ArrayList<E>();
Map<E, Integer> idx = new HashMap<E, Integer>();
public RandomSet() {
}
public RandomSet(Collection<E> items) {
for (E item : items) {
idx.put(item, dta.size());
dta.add(item);
}
}
#Override
public boolean add(E item) {
if (idx.containsKey(item)) {
return false;
}
idx.put(item, dta.size());
dta.add(item);
return true;
}
/**
* Override element at position <code>id</code> with last element.
* #param id
*/
public E removeAt(int id) {
if (id >= dta.size()) {
return null;
}
E res = dta.get(id);
idx.remove(res);
E last = dta.remove(dta.size() - 1);
// skip filling the hole if last is removed
if (id < dta.size()) {
idx.put(last, id);
dta.set(id, last);
}
return res;
}
#Override
public boolean remove(Object item) {
#SuppressWarnings(value = "element-type-mismatch")
Integer id = idx.get(item);
if (id == null) {
return false;
}
removeAt(id);
return true;
}
public E get(int i) {
return dta.get(i);
}
public E pollRandom(Random rnd) {
if (dta.isEmpty()) {
return null;
}
int id = rnd.nextInt(dta.size());
return removeAt(id);
}
#Override
public int size() {
return dta.size();
}
#Override
public Iterator<E> iterator() {
return dta.iterator();
}
}
This is faster than the for-each loop in the accepted answer:
int index = rand.nextInt(set.size());
Iterator<Object> iter = set.iterator();
for (int i = 0; i < index; i++) {
iter.next();
}
return iter.next();
The for-each construct calls Iterator.hasNext() on every loop, but since index < set.size(), that check is unnecessary overhead. I saw a 10-20% boost in speed, but YMMV. (Also, this compiles without having to add an extra return statement.)
Note that this code (and most other answers) can be applied to any Collection, not just Set. In generic method form:
public static <E> E choice(Collection<? extends E> coll, Random rand) {
if (coll.size() == 0) {
return null; // or throw IAE, if you prefer
}
int index = rand.nextInt(coll.size());
if (coll instanceof List) { // optimization
return ((List<? extends E>) coll).get(index);
} else {
Iterator<? extends E> iter = coll.iterator();
for (int i = 0; i < index; i++) {
iter.next();
}
return iter.next();
}
}
If you want to do it in Java, you should consider copying the elements into some kind of random-access collection (such as an ArrayList). Because, unless your set is small, accessing the selected element will be expensive (O(n) instead of O(1)). [ed: list copy is also O(n)]
Alternatively, you could look for another Set implementation that more closely matches your requirements. The ListOrderedSet from Commons Collections looks promising.
In Java:
Set<Integer> set = new LinkedHashSet<Integer>(3);
set.add(1);
set.add(2);
set.add(3);
Random rand = new Random(System.currentTimeMillis());
int[] setArray = (int[]) set.toArray();
for (int i = 0; i < 10; ++i) {
System.out.println(setArray[rand.nextInt(set.size())]);
}
List asList = new ArrayList(mySet);
Collections.shuffle(asList);
return asList.get(0);
This is identical to accepted answer (Khoth), but with the unnecessary size and i variables removed.
int random = new Random().nextInt(myhashSet.size());
for(Object obj : myhashSet) {
if (random-- == 0) {
return obj;
}
}
Though doing away with the two aforementioned variables, the above solution still remains random because we are relying upon random (starting at a randomly selected index) to decrement itself toward 0 over each iteration.
Clojure solution:
(defn pick-random [set] (let [sq (seq set)] (nth sq (rand-int (count sq)))))
Java 8+ Stream:
static <E> Optional<E> getRandomElement(Collection<E> collection) {
return collection
.stream()
.skip(ThreadLocalRandom.current()
.nextInt(collection.size()))
.findAny();
}
Based on the answer of Joshua Bone but with slight changes:
Ignores the Streams element order for a slight performance increase in parallel operations
Uses the current thread's ThreadLocalRandom
Accepts any Collection type as input
Returns the provided Optional instead of null
Perl 5
#hash_keys = (keys %hash);
$rand = int(rand(#hash_keys));
print $hash{$hash_keys[$rand]};
Here is one way to do it.
C++. This should be reasonably quick, as it doesn't require iterating over the whole set, or sorting it. This should work out of the box with most modern compilers, assuming they support tr1. If not, you may need to use Boost.
The Boost docs are helpful here to explain this, even if you don't use Boost.
The trick is to make use of the fact that the data has been divided into buckets, and to quickly identify a randomly chosen bucket (with the appropriate probability).
//#include <boost/unordered_set.hpp>
//using namespace boost;
#include <tr1/unordered_set>
using namespace std::tr1;
#include <iostream>
#include <stdlib.h>
#include <assert.h>
using namespace std;
int main() {
unordered_set<int> u;
u.max_load_factor(40);
for (int i=0; i<40; i++) {
u.insert(i);
cout << ' ' << i;
}
cout << endl;
cout << "Number of buckets: " << u.bucket_count() << endl;
for(size_t b=0; b<u.bucket_count(); b++)
cout << "Bucket " << b << " has " << u.bucket_size(b) << " elements. " << endl;
for(size_t i=0; i<20; i++) {
size_t x = rand() % u.size();
cout << "we'll quickly get the " << x << "th item in the unordered set. ";
size_t b;
for(b=0; b<u.bucket_count(); b++) {
if(x < u.bucket_size(b)) {
break;
} else
x -= u.bucket_size(b);
}
cout << "it'll be in the " << b << "th bucket at offset " << x << ". ";
unordered_set<int>::const_local_iterator l = u.begin(b);
while(x>0) {
l++;
assert(l!=u.end(b));
x--;
}
cout << "random item is " << *l << ". ";
cout << endl;
}
}
Solution above speak in terms of latency but doesn't guarantee equal probability of each index being selected.
If that needs to be considered, try reservoir sampling. http://en.wikipedia.org/wiki/Reservoir_sampling. Collections.shuffle() (as suggested by few) uses one such algorithm.
Since you said "Solutions for other languages are also welcome", here's the version for Python:
>>> import random
>>> random.choice([1,2,3,4,5,6])
3
>>> random.choice([1,2,3,4,5,6])
4
Can't you just get the size/length of the set/array, generate a random number between 0 and the size/length, then call the element whose index matches that number? HashSet has a .size() method, I'm pretty sure.
In psuedocode -
function randFromSet(target){
var targetLength:uint = target.length()
var randomIndex:uint = random(0,targetLength);
return target[randomIndex];
}
PHP, assuming "set" is an array:
$foo = array("alpha", "bravo", "charlie");
$index = array_rand($foo);
$val = $foo[$index];
The Mersenne Twister functions are better but there's no MT equivalent of array_rand in PHP.
Icon has a set type and a random-element operator, unary "?", so the expression
? set( [1, 2, 3, 4, 5] )
will produce a random number between 1 and 5.
The random seed is initialized to 0 when a program is run, so to produce different results on each run use randomize()
In C#
Random random = new Random((int)DateTime.Now.Ticks);
OrderedDictionary od = new OrderedDictionary();
od.Add("abc", 1);
od.Add("def", 2);
od.Add("ghi", 3);
od.Add("jkl", 4);
int randomIndex = random.Next(od.Count);
Console.WriteLine(od[randomIndex]);
// Can access via index or key value:
Console.WriteLine(od[1]);
Console.WriteLine(od["def"]);
Javascript solution ;)
function choose (set) {
return set[Math.floor(Math.random() * set.length)];
}
var set = [1, 2, 3, 4], rand = choose (set);
Or alternatively:
Array.prototype.choose = function () {
return this[Math.floor(Math.random() * this.length)];
};
[1, 2, 3, 4].choose();
In lisp
(defun pick-random (set)
(nth (random (length set)) set))
How about just
public static <A> A getRandomElement(Collection<A> c, Random r) {
return new ArrayList<A>(c).get(r.nextInt(c.size()));
}
For fun I wrote a RandomHashSet based on rejection sampling. It's a bit hacky, since HashMap doesn't let us access it's table directly, but it should work just fine.
It doesn't use any extra memory, and lookup time is O(1) amortized. (Because java HashTable is dense).
class RandomHashSet<V> extends AbstractSet<V> {
private Map<Object,V> map = new HashMap<>();
public boolean add(V v) {
return map.put(new WrapKey<V>(v),v) == null;
}
#Override
public Iterator<V> iterator() {
return new Iterator<V>() {
RandKey key = new RandKey();
#Override public boolean hasNext() {
return true;
}
#Override public V next() {
while (true) {
key.next();
V v = map.get(key);
if (v != null)
return v;
}
}
#Override public void remove() {
throw new NotImplementedException();
}
};
}
#Override
public int size() {
return map.size();
}
static class WrapKey<V> {
private V v;
WrapKey(V v) {
this.v = v;
}
#Override public int hashCode() {
return v.hashCode();
}
#Override public boolean equals(Object o) {
if (o instanceof RandKey)
return true;
return v.equals(o);
}
}
static class RandKey {
private Random rand = new Random();
int key = rand.nextInt();
public void next() {
key = rand.nextInt();
}
#Override public int hashCode() {
return key;
}
#Override public boolean equals(Object o) {
return true;
}
}
}
The easiest with Java 8 is:
outbound.stream().skip(n % outbound.size()).findFirst().get()
where n is a random integer. Of course it is of less performance than that with the for(elem: Col)
With Guava we can do a little better than Khoth's answer:
public static E random(Set<E> set) {
int index = random.nextInt(set.size();
if (set instanceof ImmutableSet) {
// ImmutableSet.asList() is O(1), as is .get() on the returned list
return set.asList().get(index);
}
return Iterables.get(set, index);
}
In Mathematica:
a = {1, 2, 3, 4, 5}
a[[ ⌈ Length[a] Random[] ⌉ ]]
Or, in recent versions, simply:
RandomChoice[a]
Random[] generates a pseudorandom float between 0 and 1. This is multiplied by the length of the list and then the ceiling function is used to round up to the next integer. This index is then extracted from a.
Since hash table functionality is frequently done with rules in Mathematica, and rules are stored in lists, one might use:
a = {"Badger" -> 5, "Bird" -> 1, "Fox" -> 3, "Frog" -> 2, "Wolf" -> 4};
PHP, using MT:
$items_array = array("alpha", "bravo", "charlie");
$last_pos = count($items_array) - 1;
$random_pos = mt_rand(0, $last_pos);
$random_item = $items_array[$random_pos];
you can also transfer the set to array use array
it will probably work on small scale i see the for loop in the most voted answer is O(n) anyway
Object[] arr = set.toArray();
int v = (int) arr[rnd.nextInt(arr.length)];
If you really just want to pick "any" object from the Set, without any guarantees on the randomness, the easiest is taking the first returned by the iterator.
Set<Integer> s = ...
Iterator<Integer> it = s.iterator();
if(it.hasNext()){
Integer i = it.next();
// i is a "random" object from set
}
A generic solution using Khoth's answer as a starting point.
/**
* #param set a Set in which to look for a random element
* #param <T> generic type of the Set elements
* #return a random element in the Set or null if the set is empty
*/
public <T> T randomElement(Set<T> set) {
int size = set.size();
int item = random.nextInt(size);
int i = 0;
for (T obj : set) {
if (i == item) {
return obj;
}
i++;
}
return null;
}

Categories