/*******************************************************************************
* Copyright (c) 2009 MATERNA Information & Communications. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html. For further
* project-related information visit http://www.ws4d.org. The most recent
* version of the JMEDS framework can be obtained from
* http://sourceforge.net/projects/ws4d-javame.
******************************************************************************/
package org.ws4d.java.util;
import java.util.Random;
/**
* Some maths functions missing on CLDC.
*/
public final class Math {
private static Random r = new Random(System.currentTimeMillis());
/**
* Returns a random value in the range [min, max[. When min == max, returns
* min. When min > max, returns nextInt(max, min).
*
* @param min The lower bound. Inclusive.
* @param max The upper bound. Exclusive.
* @return a random value in the range [min, max[.
*/
public static int nextInt(int min, int max) {
if (max == min) {
return max;
}
if (min > max) {
return nextInt(max, min);
}
int range = max - min;
int val = java.lang.Math.abs(r.nextInt() % range);
return val + min;
}
/**
* Returns a random value in the range [0, max[.
*
* @param max The upper bound. Exclusive.
* @return a random value in the range [0, max[.
*/
public static int nextInt(int max) {
return Math.nextInt(0, max);
}
/**
* Returns a random integer value.
*
* @return a random integer value.
*/
public static int nextInt() {
return r.nextInt();
}
/**
* Generates a random port number between 1025 and 65535.
*
* @return a random number to try as port number for the server.
*/
public static int getRandomPortNumber() {
return (r.nextInt() & 0xefff) + 1025;
}
/**
* Returns the Random generated by MathUtil.
*
* @return <code>Random</code>;
*/
public static Random getRandom() {
return r;
}
public static int pow(int a, int b) {
if (b == 0) return 1;
if (b == 1) return a;
int c = a;
while (b > 1) {
a = a * c;
b--;
}
return a;
}
}