error: illegal start of expression; reached end of file while parsing - java

I'm new to Java programming. This is part of homework questions. I need to provide a set of comparison methods on arrays. I tried my best and this is my attempt so far. Can somebody enlighten me? Any help will be much appreciated!
Several requirements I need to follow:
You must not add any public methods to the Selector class. You are free to add any private methods that you think are appropriate, but you can't add any public methods.
You must not add any fields, either public or private, to the Selector class.
You must not import anything other than java.util.Arrays, but you are not required to import this at all.
You are only allowed to use sorting as part of your solution in the nearest and farthest
methods.
You must not modify the existing constructor or add other constructors. This class is designed to be strictly a provider of static methods and should not be instantiated.
import java.util.Arrays;
/**
* A class that contains various selection methods on arrays.
* All methods assume that the array is completely filled with
* non-null values. If this is not true, the behavior is not specified.
* All the methods throw an IllegalArgumentException if the array
* parameter is null or has zero length. The array parameter to
* each method is guaranteed to not be changed as a result of the call.
*/
public final class Comparision{
/**
* C A N N O T I N S T A N T I A T E T H I S C L A S S .
*
*/
private Comparision(){
}
/**
* Return the element of a nearest to val. This method throws an
* IllegalArgumentException if a is null or has zero-length.
* The array a is not changed as a result of calling this method.
*
* #param a the array to be searched
* #param val the reference value
* #return the element a[i] such that ABS(a[i] - val) is minimum
*
*/
public static int nearest(int[] a, int val) {
int[] a = new int[10];
if (a == null || a.length == 0){
throw new IllegalArgumentException("a is null or has zero-length");
}
int idx = 0;
int distance = Math.abs(a[0]-val);
for(int c = 1; c< a.length; c++){
int cdistance = Math.abs(a[c] - val);
if(cdistance < distance){
idx=c;
distance = cdistance;
}
}
int theNumber = a[idx];
return theNumber;
}
/**
* Return the element of a farthest from val. This method throws an
* IllegalArgumentException if a is null or has zero-length.
* The array a is not changed as a result of calling this method.
*
* #param a the array to be searched
* #param val the reference value
* #return the element a[i] such that ABS(a[i] - val) is maximum
*
*/
public static int farthest(int[] a, int val) {
int[] a = new int[10];
if (a == null || a.length == 0){
throw new IllegalArgumentException("a is null or has zero-length");
}
int idx = 0;
int distance = Math.abs(a[0]-val);
for(int c = 1; c< a.length; c++){
int cdistance = Math.abs(a[c] - val);
if(cdistance > distance){
idx=c;
distance = cdistance;
}
}
int theNumber = a[idx];
return theNumber;
}
/**
* Return the k elements of a nearest to val.
* The array a is not changed as a result of calling this method.
* This method throws an IllegalArgumentException if k is negative.
* This method returns an array of zero length if k == 0 or if
* k > a.length.
*
* #param a the array to be searched
* #param val the reference value
* #param k the number of near elements to identify
* #return the k elements a[i] such that ABS(a[i] - val)
* are the k smallest evaluations
*
*/
public static int[] nearestK(int[] a, int val, int k) {
int[] b = new int[10];
for (int i = 0; i < b.length; i++){
b[i] = Math.abs(a[i] - val);
}
Arrays.sort(b);
int[] c = new int[w];
w = 0;
for (int i = 0; i < k; i++){
if (k < 0){
throw new IllegalArgumentException("k is not invalid!");
}
c[w] = b[i];
w++;
}
return c;
}
/**
* Return the k elements of a farthest from val.
* The array a is not changed as a result of calling this method.
* This method throws an IllegalArgumentException if k is negative.
* This method returns an array of zero length if k == 0 or if
* k > a.length.
*
* #param a the array to be searched
* #param val the reference value
* #param k the number of far elements to identify
* #return the k elements a[i] such that ABS(a[i] - val)
* are the k largest evaluations
*
*/
public static int[] farthestK(int[] a, int val, int k) {
int[] b = new int[10];
for (int i = 0; i < 10; i++){
b[i] = Math.abs(a[i] - val);
}
Arrays.sort(b);
int[] c = new int[w];
int w = 0;
for (int i = array.length-1; i >= array.length-k; i--){
if (k < 0){
throw new IllegalArgumentException("k is not invalid!");
}
else if (k == 0 || k > a.length){
int[] c = "";
}
c[w] = b[i];
w++;
}
return c;
}
/**
* Return the number of elements of a that are greater than val.
*
* #param a the array to be searched
* #param val the reference value
* #return the number of elements a[i] such that a[i] > val
*
*/
public static int numGreater(int[] a, int val) {
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)>0){
w++;
}
return w;
}
/**
* Return an array of all the elements of a that are greater than val.
* If a contains no elements greater than val, this method returns an
* array of zero length.
*
* #param a the array to be searched
* #param val the reference value
* #return the elements a[i] such that a[i] > val
*
*/
public static int[] greater(int[] a, int val){
int[] b = new int[w];
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)>0){
b[w] = a[i];
w++;
}
}
if (w = 0){
int[] b = {};
}
return b;
}
/**
* Return the number of elements of a that are less than val.
*
* #param a the array to be searched
* #param val the reference value
* #return the number of elements a[i] such that a[i] < val
*
*/
public static int numLess(int[] a, int val) {
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)<0){
w++;
}
return w;
}
/**
* Return an array of all the elements of a that are less than val.
* If a contains no elements less than val, this method returns an
* array of zero length.
*
* #param a the array to be searched
* #param val the reference value
* #return the elements a[i] such that a[i] < val
*
*/
public static int[] less(int[] a, int val) {
int[] b = new int[w];
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)<0){
b[w] = a[i];
w++;
}
}
if (w = 0){
int[] b = {};
}
return b;
}
}

You problem is in lines 194-197: you aren't closing your if statement, so your close curly braces after that are all messed up. To fix it, change numLess to:
public static int numLess(int[] a, int val) {
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)<0){
w++;
} // This is the curly brace you are missing
}
return w;
}
EDIT: the other answer is right as well; you have the same problem in both numGreater and numLess. Add the close-curly brace in both functions and it should compile correctly.

I think you're missing brackets or semi-colons:
This should be:
public static int numGreater(int[] a, int val) {
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)>0){
w++;
}
return w;
}
Should be:
public static int numGreater(int[] a, int val) {
int w = 0;
for (int i = 0; i < a.length; i++){
if ((a[i] - val)>0){
w++;
}//<---missing this fella
}
return w;
}

Related

What exactly should I be returning in this code?

We are creating a program that will return a topographic map and show the user the best way to navigate the terrain without making steep climbs or descents. For the files that I am working with, I am not sure what maximum and minimum values need to be returned. The assignment is mostly complete except for 3 errors regarding an expected return value. I've submitted the primary code that we are working with and included a link to the other files the professor has given us for the assignment.
I've tried return maxValue, return minValue, return max, return min, and a few other combinations but the issue is I'm not sure if I am supposed to be returning a value from this MapDataDrawer.java file or from one of the other two files that we have to use for the assignment from the professor.
//MapDataDrawer.java
//This is the code that is returning the error
import java.util.*;
import java.io.*;
import java.awt.*;
public class MapDataDrawer
{
private int[][] grid;
public MapDataDrawer(String filename, int rows, int cols){
// initialize grid
grid = new int[rows][cols];
//read the data from the file into the grid
File dataFile = new File(filename);
try {
Scanner dataInput = new Scanner(dataFile);
for (int i=0; i<rows; i++) {
for (int j=0; j<cols;j++) {
grid[i][j] = dataInput.nextInt();
}
}
} catch (Exception e) { e.printStackTrace();}
}
/**
* #return the min value in the entire grid
*/
public int findMin() {
// Implement this method
}
/**
* #return the max value in the entire grid
*/
public int findMax(){
// Implement this method
}
/**
* #param col the column of the grid to check
* #return the index of the row with the lowest value in the given col for the grid
*/
public int indexOfMinRow(int col){
//Implement this method
}
/**
* Draws the grid using the given Graphics object.
* Colors should be grayscale values 0-255, scaled based on min/max values in grid
*/
public void drawMap(Graphics g){
int min = findMin();
int max = findMax();
for (int i=0; i<480; i++) {
for (int j=0; j<480; j++) {
int c = (255 * (grid[i][j] - min)) / (max - min);
g.setColor(new Color(c, c, c));
g.fillRect(j, i, 1, 1);
}
}
}
/**
* Find a path from West-to-East starting at given row.
* Choose a foward step out of 3 possible forward locations, using greedy method described in assignment.
* #return the total change in elevation traveled from West-to-East
*/
public int drawLowestElevPath(Graphics g, int row){
int elevChange = 0;
// Implement this method
return elevChange;
}
private int minOfThree(int a, int b, int c) {
if ((a > b) && (a > c)) return a;
if ((b > a) && (b > c)) return b;
if ((c > a) && (c > b)) return c;
return 0;
}
}
These are the professors submitted files, of which I am unsure if I am supposed to be returning some value from one of these files or from the actual homework file (MapDataDrawer.java) https://drive.google.com/drive/folders/1siRoY1K0ngptE2rL-wscXLK8Ct7Qo1hb?usp=sharing
It also includes the topographic data we are supposed to use.
As you have filled grid:
public int findMin() {
int min = Integer.MAX_VALUE;
for (int i = 0; i < grid.length; i++) {
for (int j = 0; j < grid[i].length; j++) {
int value = grid[i][j];
if (value < min) {
min = value;
}
}
}
return min;
}

CopyOf returning array

jump is an array that has been initialised.
FunctionMonius3.difRandoms method returns an array
jump = FunctionMonius3.difRandoms(posMonius.length, lines * col, generator);
or
jump = Arrays.copyOf(FunctionMonius3.difRandoms(posMonius.length, lines * col, generator), v.length);
Does the first option just creates a reference that is destroyed when the method FunctionMonius3.difRandoms ends or is it ok?
* #param n - number of array elements
* #param sup - max value
* #param g - generator
public static int[] difRandom (int n, int sup, Random g){
int[] result = new int [n];
int i = 0;
while (i < result.length) {
int random = g.nextInt(sup) + 1;
if (!contidoEmParte(aleatorio,result,i)){
result[i] = random;
i++;
}
}
return result;
}

Why can't I set list.size as the length of my integer array?

I've been struggling for hours to eliminate a bug that I don't understand.
In line 190 of the code below (int s = n[0]) I get an array out of bounds exception which as I've narrowed down has to do with array e. Array e is declared at the top of the code given below with the length/size of an object list a (a.size()) and if I replace size with an arbitrary integer (for example 10) the error disappears.
Why can't I set a.size as the length of my array? Is there a way to go around this?
Summary of the code: powerize(int n) is supposed to Write a number n as a power with maximal exponent. factorize decomposes a number into the product of primes and gcd returns the greatest common divisor of an array of integers.
public static Power powerize(int n) throws IllegalArgumentException {
List<Power> a = MathStuff.factorize(n); //make a list of Power objects from factorize n
int size = a.size();
int[] e = new int[size];
int[] b = new int[size];
for (int i = 0; i < size; i++) { //collect all the base and exponent of each object in a. This LOOP 1
if(i >= a.size() || i >= e.length || i > b.length){System.out.print("Out of bounds in LOOP 1");} //test for out of bounds
e[i] = a.get(i).exponent;
b[i] = a.get(i).base;
}
int g = gcd(e);
int h = 1; //endproduct base
for (int i = 1; i < b.length; i++) { //Construct the base by taking the product of each base with its exponent divided by g.
if(i >= e.length || i >= b.length){System.out.print("Out of bounds in LOOP 3");} //test for out of bounds
h *= MathStuff.power(b[i], e[i] / g);
}
return new Power(h, g); //replace 2
}
/**
* factorize n
*
* #param n the number to 'powerize'
* #modifies none
* #pre {#code 2 <= n}
* #return factorization of n
*/
public static List<Power> factorize(int n) {
List<Integer> f = new ArrayList<Integer>(); // f are factors
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
f.add(i);
n /= i;
}
}
//return f; //returns factors
List<Power> p = new ArrayList<Power>(); // p are the factors with powers
for (int j = 2; j <= n; j++) { //j will be the base
int e = 0; //exponent
for (int k = 0; k <= f.size(); k++) {
if (f.get(k) == j) {
e++;
}
}
p.add(new Power(j, e));
}
return p; //returns factors in powered form
}
/**
* gcd returns the greatest common divisor of an integer array
* #param n
* #return greatest common divisor
*/
public static int gcd(int... n) {
//------------------------------------------------THE ERROR OCCURS HERE
int s = n[0];
for (int i = 1; i < n.length; i++) {
if (n[i] < s) {
s = n[i];
}
}
while (s > 1) {
int counter = 0;
int modTot = 0;
while (counter < n.length) {
modTot += n[counter] % s;
counter++;
}
if (modTot == 0) {
return s;
}
s--;
}
//return 0 if there is no gcd
return 0;
}
Here:
public static int gcd(int... n) {
int s = n[0];
This code assumes (without any further checking) that gcd() was invoked with at least one array element. But obviously that is not true.
Keep in mind that you can invoke that method like:
gcd(); // NO array at all or
gcd(someArray); // but someArray happens to be null !
So you have to step back and check your source code for all situations where gcd() is called. There must be one where you pass 0 parameters; or you pass an array of int that is actually null.
I'll assume that your question is why you can't set the size of an array using the size property.
When an array is initialized (via new int[x]), the OS will look for a continuous block of memory that will be big enough to hold x ints. Once that memory is found, the size of the array will be fixed as x.
Think of what would happen if you could change the array size using size. This would mean that, if you wanted to expand this array, you would have to take over the memory that comes immediately after it. What if that memory is being used by something else? That would present a problem.
However, java.util.ArrayList solves this problem for you as and when necessary. So that's the work-around if you need it.

Can't get array to copy with written copy() method

So the premise of this code is to build apon it as we learn different things like nodes and such through out the semester.
Currently, in this version of the code, I need to replace anything that uses 0 to signify the end of the collection of numbers. So let's say if array A has [1,2,5,4,0], 0 would be the indicator that we are at the end of the array.
Now in this version, we have to use a counter(a.k.a howmany in this code) to signify the end of the collection of numbers.
Currently, with this code, I'm getting out of bounds errors and I'm not fully understanding why. I'm getting it in the copy()method and also the omit() method.
Here is the main class:
import java.util.*;
public class Intcoll2client {
public static final int SENTINEL = 0;
public static void main(String[] args) {
int value;
Scanner keyboard = new Scanner(System.in);
Intcoll2 P = new Intcoll2(), N = new Intcoll2(), L = new Intcoll2(5);
System.out.println("Enter an integer to be inserted or 0 to quit:");
value = keyboard.nextInt();
while (value != SENTINEL) {
if (value > 0) {
P.insert(value);
L.insert(value);
} else {
N.insert(-value);
L.omit(-value);
}
// L.arraySize();
System.out.println("Enter next integer to be inserted or 0 to quit:");
value = keyboard.nextInt();
}
System.out.println("\nThe values in collection P are:");
P.print();
System.out.println("\nThe values in collection N are:");
N.print();
System.out.println("\nThe values in collection L are:");
L.print();
if (P.equals(N)) {
System.out.println("\nP and N are equal.");
} else {
System.out.println("\nP and N are NOT equal.");
}
Intcoll2 A = new Intcoll2();
A.copy(L);
System.out.println("\nThe values in the copy of L are:\n");
A.print();
}
}
Here is the class with all of the methods I'm working with:
import java.util.*;
public class Intcoll2 {
private int[] c;
private int howmany;
/**
* Creates a new array c with the size 500
*/
public Intcoll2() {
c = new int[500];
howmany = 0;
}
/**
* Creates a new array with the size i
*
* #param i positive integer
*/
public Intcoll2(int i) {
c = new int[i];
howmany = 0;
}
/**
* Pre-condition: Takes in an object of Intcoll2 Post-condition: If obj does
* not equal c, create a new array and copy all elements from c to obj
*
* #param obj
*/
public void copy(Intcoll2 obj) {
if (this != obj) {
c = new int[obj.c.length];
int j = 0;
while (obj.c[j] != 0) {
c[j] = obj.c[j];
j++;
}
c[j] = 0;
}
}
/**
* Pre-condition: Take in positive integer i
* Post-condition: Return true if
* i is greater than 0 and i is equal to element in array. Otherwise, false
*
* #param i positive integer
* #return
*/
public boolean belongs(int i) {
int j = 0;
while ((c[j] != 0) && (c[j] != i)) {
j++;
}
return ((i > 0) && (c[j] == i));
}
/**
* Pre-condition: Take in a positive integer i
* Post-condition: If i is greater than 0 and is not in the current collection, insert
* into collection. Otherwise, do nothing. If current array is too small to
* insert new integer, create new array double the size and copy all
* elements into new array. Redirect new array to old reference variable.
*
* #param i positive integer to insert in object
*/
public void insert(int i) {
if (i > 0) {
int j = 0;
while ((j < howmany) && (c[j] != 0)) {
j++;
}
if (j == howmany) {
if (j == c.length) {
int[] newC = new int[c.length * 2];
for (int index = 0; index < c.length; index++) {
newC[index] = c[index];
}
c = newC;
}
c[j] = i;
howmany++;
}
}
}
public void arraySize(){
int size = c.length;
System.out.println("Howmany: " + howmany);
System.out.println("Size of L: " + size);
}
/**
* if i is greater than 0, then scan array. If i is found in the array, take
* away and move any element after the index to fill in the 0 space
*
* #param i positive integer
*/
public void omit(int i) {
if (i > 0) {
int j = 0;
while ((c[j] != 0) && (c[j] != i)) {
j++;
}
if (c[j] == i) {
int k = j + 1;
while (c[k] != 0) {
k++;
}
c[j] = c[k - 1];
c[k - 1] = 0;
}
}
}
/**
* Returns number of integers in a collection until loop hits 0
*
* #return howmany
*/
public int get_howmany() {
return howmany;
}
/**
* Prints out the entire collection until it reaches an element of 0
*/
public void print() {
int j = 0;
System.out.println();
while (j < howmany) {
System.out.println(c[j]);
j++;
}
}
/**
* Pre-condition: Takes in an existing object of Intcoll1 Post-condition:
* Compares two objects, if both collections are equal, return true.
* Otherwise, false.
*
* #param obj object containing an array
* #return result
*/
public boolean equals(Intcoll2 obj) {
int j = 0;
boolean result = true;
while ((c[j] != 0) && result) {
result = obj.belongs(c[j]);
j++;
}
j = 0;
while ((obj.c[j] != 0) && result) {
result = belongs(obj.c[j]);
j++;
}
return result;
}
}
Any type of input or help would be greatly appreciated!

Can't create instance of class in Java: "X() has private access in X"

I am trying to instantiate the StdRandom class (see below) in my own Java program so that I can generate random integers by calling it's uniform method. However, I kept getting this error during compilation:
MyProgram.java:43: StdRandom() has private access in StdRandom
StdRandom random = new StdRandom();
1 error
I noticed this line in the code which is preventing me from instantiating the StdRandom class:
// singleton pattern - can't instantiate
private StdRandom() { }
My questions are: how am I supposed to instantiate this class and use the methods in this class in my own programs? Why was the above singleton pattern included in this code? Should I just comment the pattern out and use it? Or is there another way to access this class's methods in my Java programs?
/*************************************************************************
* Compilation: javac StdRandom.java
* Execution: java StdRandom
*
* A library of static methods to generate pseudo-random numbers from
* different distributions (bernoulli, uniform, gaussian, discrete,
* and exponential). Also includes a method for shuffling an array.
*
*
* % java StdRandom 5
* seed = 1316600602069
* 59 16.81826 true 8.83954 0
* 32 91.32098 true 9.11026 0
* 35 10.11874 true 8.95396 3
* 92 32.88401 true 8.87089 0
* 72 92.55791 true 9.46241 0
*
* % java StdRandom 5
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
* % java StdRandom 5 1316600616575
* seed = 1316600616575
* 96 60.17070 true 8.72821 0
* 79 32.01607 true 8.58159 0
* 81 59.49065 true 9.10423 1
* 96 51.65818 true 9.02102 0
* 99 17.55771 true 8.99762 0
*
*
* Remark
* ------
* - Relies on randomness of nextDouble() method in java.util.Random
* to generate pseudorandom numbers in [0, 1).
*
* - This library allows you to set and get the pseudorandom number seed.
*
* - See http://www.honeylocust.com/RngPack/ for an industrial
* strength random number generator in Java.
*
*************************************************************************/
import java.util.Random;
/**
* <i>Standard random</i>. This class provides methods for generating
* random number from various distributions.
* <p>
* For additional documentation, see Section 2.2 of
* <i>Introduction to Programming in Java: An Interdisciplinary Approach</i> by Robert Sedgewick and Kevin Wayne.
*/
public final class StdRandom {
private static Random random; // pseudo-random number generator
private static long seed; // pseudo-random number generator seed
// static initializer
static {
// this is how the seed was set in Java 1.4
seed = System.currentTimeMillis();
random = new Random(seed);
}
// singleton pattern - can't instantiate
private StdRandom() { }
/**
* Set the seed of the psedurandom number generator.
*/
public static void setSeed(long s) {
seed = s;
random = new Random(seed);
}
/**
* Get the seed of the psedurandom number generator.
*/
public static long getSeed() {
return seed;
}
/**
* Return real number uniformly in [0, 1).
*/
public static double uniform() {
return random.nextDouble();
}
/**
* Return an integer uniformly between 0 and N-1.
*/
public static int uniform(int N) {
return random.nextInt(N);
}
///////////////////////////////////////////////////////////////////////////
// STATIC METHODS BELOW RELY ON JAVA.UTIL.RANDOM ONLY INDIRECTLY VIA
// THE STATIC METHODS ABOVE.
///////////////////////////////////////////////////////////////////////////
/**
* Return real number uniformly in [0, 1).
*/
public static double random() {
return uniform();
}
/**
* Return int uniformly in [a, b).
*/
public static int uniform(int a, int b) {
return a + uniform(b - a);
}
/**
* Return real number uniformly in [a, b).
*/
public static double uniform(double a, double b) {
return a + uniform() * (b-a);
}
/**
* Return a boolean, which is true with probability p, and false otherwise.
*/
public static boolean bernoulli(double p) {
return uniform() < p;
}
/**
* Return a boolean, which is true with probability .5, and false otherwise.
*/
public static boolean bernoulli() {
return bernoulli(0.5);
}
/**
* Return a real number with a standard Gaussian distribution.
*/
public static double gaussian() {
// use the polar form of the Box-Muller transform
double r, x, y;
do {
x = uniform(-1.0, 1.0);
y = uniform(-1.0, 1.0);
r = x*x + y*y;
} while (r >= 1 || r == 0);
return x * Math.sqrt(-2 * Math.log(r) / r);
// Remark: y * Math.sqrt(-2 * Math.log(r) / r)
// is an independent random gaussian
}
/**
* Return a real number from a gaussian distribution with given mean and stddev
*/
public static double gaussian(double mean, double stddev) {
return mean + stddev * gaussian();
}
/**
* Return an integer with a geometric distribution with mean 1/p.
*/
public static int geometric(double p) {
// using algorithm given by Knuth
return (int) Math.ceil(Math.log(uniform()) / Math.log(1.0 - p));
}
/**
* Return an integer with a Poisson distribution with mean lambda.
*/
public static int poisson(double lambda) {
// using algorithm given by Knuth
// see http://en.wikipedia.org/wiki/Poisson_distribution
int k = 0;
double p = 1.0;
double L = Math.exp(-lambda);
do {
k++;
p *= uniform();
} while (p >= L);
return k-1;
}
/**
* Return a real number with a Pareto distribution with parameter alpha.
*/
public static double pareto(double alpha) {
return Math.pow(1 - uniform(), -1.0/alpha) - 1.0;
}
/**
* Return a real number with a Cauchy distribution.
*/
public static double cauchy() {
return Math.tan(Math.PI * (uniform() - 0.5));
}
/**
* Return a number from a discrete distribution: i with probability a[i].
* Precondition: array entries are nonnegative and their sum equals 1.
*/
public static int discrete(double[] a) {
double EPSILON = 1E-14;
double sum = 0.0;
for (int i = 0; i < a.length; i++) {
if (a[i] < 0.0) throw new IllegalArgumentException("array entry " + i + " is negative: " + a[i]);
sum = sum + a[i];
}
if (sum > 1.0 + EPSILON || sum < 1.0 - EPSILON)
throw new IllegalArgumentException("sum of array entries not equal to one: " + sum);
double r = uniform();
sum = 0.0;
for (int i = 0; i < a.length; i++) {
sum = sum + a[i];
if (sum >= r) return i;
}
return -1;
}
/**
* Return a real number from an exponential distribution with rate lambda.
*/
public static double exp(double lambda) {
return -Math.log(1 - uniform()) / lambda;
}
/**
* Rearrange the elements of an array in random order.
*/
public static void shuffle(Object[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of a double array in random order.
*/
public static void shuffle(double[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of an int array in random order.
*/
public static void shuffle(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int r = i + uniform(N-i); // between i and N-1
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(Object[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
Object temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(double[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
double temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Rearrange the elements of the subarray a[lo..hi] in random order.
*/
public static void shuffle(int[] a, int lo, int hi) {
if (lo < 0 || lo > hi || hi >= a.length)
throw new RuntimeException("Illegal subarray range");
for (int i = lo; i <= hi; i++) {
int r = i + uniform(hi-i+1); // between i and hi
int temp = a[i];
a[i] = a[r];
a[r] = temp;
}
}
/**
* Uniformly sample (without replacement) M of the N items from the array a[].
* To make it work with an Object[] argument and return an array of the
* underlying argument type requires some Java minutiae, e.g., using static
* generics and Arrays.copyOf().
*/
public static String[] sample(String[] a, int M) {
int N = a.length;
if (M < 0 || M > N)
throw new RuntimeException("Illegal number of samples");
String[] b = new String[M];
for (int i = 0; i < N; i++) {
int r = uniform(i+1); // between 0 and i
if (r < M) {
if (i < M) b[i] = b[r];
b[r] = a[i];
}
}
return b;
}
/**
* Unit test.
*/
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
if (args.length == 2) StdRandom.setSeed(Long.parseLong(args[1]));
double[] t = { .5, .3, .1, .1 };
StdOut.println("seed = " + StdRandom.getSeed());
for (int i = 0; i < N; i++) {
StdOut.printf("%2d " , uniform(100));
StdOut.printf("%8.5f ", uniform(10.0, 99.0));
StdOut.printf("%5b " , bernoulli(.5));
StdOut.printf("%7.5f ", gaussian(9.0, .2));
StdOut.printf("%2d " , discrete(t));
StdOut.println();
}
String[] a = "A B C D E F G".split(" ");
for (String s : a)
StdOut.print(s + " ");
StdOut.println();
String[] b = StdRandom.sample(a, 3);
for (String s : b)
StdOut.print(s + " ");
StdOut.println();
}
}
All methods are static, you don't need to create an instance of that class to use it. To use e.g. the random() method, use StdRandom.random()
You don't instantiate it, you call the methods statically:
StdRandom.setSeed(42L);
double n = StdRandom.uniform(66);
etc.
All the methods in this class are static, you don't need to and can't instantiate as it has private constructor, you can use methods directly for eg StdRandom.unifrom(...)
This is 'util' class with hidden constructor. Instead of create new instance call methods directly: StdRandom.uniform(100), StdRandom.random(), etc..

Categories

Resources