I have been trying to construct a linked list where there are 3 different ways to view the code, either the current double value or the previous or next node. The problem I seem to be running into is that in essecense I have been creating a new linked list whenever storing the next or previous node of the current node rather than linking it.
This creates 2 problems:
It takes up a ridicolous amount of space
It creates makes bugs and errors common and hard to spot
I want to know if there is a better way to construct linked lists than this method or if I am running into these 2 problems for reasons different than I believe. My code is down below if you want to see what I have been trying to do.
package algs662;
import java.util.*;
//This whole file is about assembling and sorting data
public class BigSort
{
//The Node is an element that represents the current position
//of a linked list and what is immediately to its left or right static class Node
{
//this represents the Node itself
public Node() { }
//this represents its current element
public double item;
//this represents the node to its right
public Node next;
//this represents the node to its left
public Node prev;
}
//this represents the size of the Linked List
int N;
//this is the main node
Node first;
//this is a variable that will be false when the function
//using this hasn't ran once and will be true when it has
public boolean once = false;
//This will create an empty node where new elements can be added
public BigSort()
{
first = null;
N = 0;
checkInvariants ();
}
//This represents the max value
static double max;
private void myassert( String s, boolean b )
{
if( !b ) throw new AssertionError( "Assertion failed: " + s );
}
private void checkInvariants()
{
myassert( "Empty <==> first==null", (N == 0) == (first == null) );
Node x = first;
for( int i = 0; i < N; ++i )
{
if( x==null )
{
throw new Error( "List too short!" );
}
x = x.next;
}
myassert("EndOfList == null", x == null);
}
private Node reset( Node n )
{
Node saved;
while( n.prev != null )
{
saved = n;
n = n.prev;
}
return n;
}
//This function will delete a specific number from a list
private void delete( double num )
{
if( once == false )
{
Node curr = first;
if( N == 0 ) { throw new Error( "There is no list" ); }
else if( N == 1 )
{
if( curr.item == num )
{
first = null;
return;
}
else
{
throw new Error( "Number inputted doesn't exist" );
}
}
else if( curr != null )
{
if( curr.item == num )
{
first = curr.next;
--N;
return;
}
while( curr.next != null )
{
if( curr.next.item != num )
{
curr.prev = curr;
curr = curr.next;
}
else if( curr.next.item == num )
{
curr.next = curr.next.next;
--N;
reset( curr );
return;
}
}
if( curr.item == num )
{
first = curr.prev;
curr.next = null;
--N;
reset( curr );
return;
}
else if( curr.next == null )
{
throw new Error( "Number inputted doesn't exist" );
}
}
}
else
{
return;
}
}
private void push( double i )
{
Node temp = new Node();
temp.item = i;
Node saved;
Node curr = first;
if( this.first == null )
{
first = temp;
return;
}
else
{
while( curr.next != null )
{
saved = curr;
curr = curr.next;
curr.prev = saved;
}
saved = curr;
curr.next = temp;
curr = curr.next;
curr.prev = saved;
}
this.N++;
first = reset( curr );
}
private void pushFront( double i )
{
Node temp = new Node();
Node saved;
temp.item = i;
temp.next = first;
saved = temp;
temp = temp.next;
temp.prev = saved;
temp = temp.prev;
++N;
first = temp;
}
private void pushPos( int pos, double i )
{
Node temp = new Node();
Node store = new Node();
Node last = new Node();
store.item = i;
temp = first;
Node saved;
double pastval;
double savedval;
if( pos > N || pos < 0 )
{
throw new Error( "The position inputted doesn't exist" );
}
else
{
if( pos == 0 )
{
store.item = i;
store.next = first;
++N;
first = store;
return;
}
for( int x = 0; x < pos; ++x )
{
saved = temp;
temp = temp.next;
temp.prev = saved;
}
pastval = temp.item;
temp.item = i;
temp = temp.next;
savedval = temp.item;
temp.item = pastval;
while( temp.next != null )
{
// Does nothing??
}
first=reset( temp );
return;
}
}
private double pop()
{
Node popped;
Node temp = first;
while( temp.next.next !=null )
{
temp = temp.next;
}
popped = temp.next;
temp.next = null;
--N;
System.out.print( popped );
first = temp;
return popped.item;
}
private void incurSort()
{
double swap = 0;
int u = 0;
for( int y = 1; y < N - 1; ++y )
{
//this compares the current item to the next item
if( first.item > first.next.item )
{
u = y;
while( u > 0 && first.prev != null )
{
if( first.item > first.next.item )
{
swap = first.item;
first.item = first.next.item;
first.next.item = swap;
}
first = first.prev;
--u;
}
}
while( u < y && first.next != null )
{
first = first.next;
++u;
}
}
reset(first);
}
public static void main( String args[] )
{
double swap = 0;
BigSort b = new BigSort();
int u = 0;
// Adding elements in the list
// using add() method
b.push( 1.0 );
b.push( 3.0 );
b.push( 5.0 );
b.push( 2.0 );
b.push( 20.0 );
b.push( 11.0 );
b.push( 13.0 );
b.push( 17.0 );
Node two = b.first;
b.incurSort();
b.delete( 11.0 );
b.delete( 1.0);
b.delete( 20.0);
b.delete( 5.0);
b.delete( 3.0);
b.delete( 13.0);
b.pushFront( 10.0);
b.pushFront( 2.0 );
b.pushFront( 16.0 );
b.pushFront( 50.0 );
b.pushFront( 100.0 );
b.pushPos( 2, 20.0 );
System.out.println( b.pop() );
System.out.println( b.pop() );
System.out.println( b.pop() );
System.out.println( b.pop() );
System.out.println( b.pop() );
System.out.println( b.pop() );
System.out.println( "stuff left over" );
for( int k = 0; k <= b.N - 1; ++k )
{
if( b.first != null )
{
System.out.println( b.first.item );
b.first = b.first.prev;
}
else
{
System.out.println( "it broke at " + k );
break;
}
}
}
}
Related
I am having a problem when i assign objects, the object produces a reference duplicate that changes the value in original object.
This is my original object
Node root = new Node();
root.filingState("input.txt");
After pushing my root in deque data structure, i retrieve it in a tmp variable
Node tmp = deque.pop();
After that, i want my tmp variable to apply all the operators(up, down, left, right, which ever ones are possible) and check for the best result.
if ( !tmp.goalTest(goal) ) {
if ( tmp.ifDown() ) {
if ( !visited[tmp.getX()+1][tmp.getY()] ) {
newDown = new Node(tmp);
newDown.moveDown();
} else newDown = null;
} // #EndOfDown!
if ( tmp.ifUp() ) {
if ( !visited[tmp.getX()-1][tmp.getY()] ) {
newUp = new Node(tmp);
newUp.moveUp();
} else newUp = null;
} // #EndOfUp!
if ( tmp.ifLeft() ) {
if ( !visited[tmp.getX()][tmp.getY()-1] ) {
newLeft = new Node(tmp);
newLeft.moveLeft();
} else newLeft = null;
} // #EndOfMoveLeft!
if ( tmp.ifRight() ) {
if ( !visited[tmp.getX()][tmp.getY()+1] ) {
newRight = new Node(tmp);
newRight.moveRight();
} else newRight = null;
} // #EndOfMoveRight!
} else break;
Operator functions
public boolean ifUp ( ) { return y_blank-1 >= 0; }
public boolean ifDown ( ) { return y_blank+1 <= 4; }
public boolean ifLeft ( ) { return x_blank-1 >= 0; }
public boolean ifRight ( ) { return x_blank+1 <= 4; }
/* Movement functions
Allows a user to move his blank on board
*/
public void moveUp ( ) {
board[y_blank][x_blank] = board[y_blank-1][x_blank];
board[y_blank-1][x_blank] = 'B';
y_blank -= 1;
} // #EndOfMoveUp!
public void moveLeft ( ) {
board[y_blank][x_blank] = board[y_blank][x_blank-1];
board[y_blank][x_blank-1] = 'B';
x_blank -= 1;
} // #EndOfMoveLeft!
public void moveRight ( ) {
board[y_blank][x_blank] = board[y_blank][x_blank+1];
board[y_blank][x_blank+1] = 'B';
x_blank += 1;
} // #EndOfMoveRight!
public void moveDown ( ) {
board[y_blank][x_blank] = board[y_blank+1][x_blank];
board[y_blank+1][x_blank] = 'B';
y_blank += 1;
} // #EndOfMoveDown!
newDown fails of 1st iteration since it doesn't fulfill the condition by my other Nodes pass the condition.
after my 1st newUp applies its operator, it changes the tmp Node aswell. Allowing newLeft, newRight to apply operators to the newly tmp Node values.
class Node.java
private char[][] board;
private int x_blank = -1;
private int y_blank = -1;
private Node parent = null;
private Node up = null;
private Node left = null;
private Node right = null;
private Node down = null;
/* Constructor
Allocates board to a 5x5 2D Array
*/
public Node ( ) { board = new char[5][5]; }
i tried creating a copy constructor but doesn't solve the problem.
Copy constructor
public Node ( Node tmp ) {
this.board = new char[5][5];
for ( int i=0; i<5; ++i ) {
for ( int j=0; j<5; ++j ) this.board[i][j] = tmp.board[i][j];
}
this.x_blank = tmp.x_blank;
this.y_blank = tmp.y_blank;
if ( tmp.parent != null ) this.parent = tmp.parent;
if ( tmp.up != null ) this.up = tmp.up;
if ( tmp.left != null ) this.left = tmp.left;
if ( tmp.right != null ) this.right = tmp.right;
if ( tmp.down != null ) this.down = tmp.down;
}
so my question is that, how can i create an Object that can hold the values of some other Object, but when i apply the operator on the newly created object, it doesn't change the value of the original Object.
Your copy constructor won't automatically be used on assignment of an instance of that object to a new variable. It is intended in Java that object assignments are by reference. You need to explicitly use your copy constructor in the assignment:
Node tmp = new Node(deque.pop());
I think the best way is to implement a clone function that will create a new object with the same value, then you will not change the value of the original Object.
for example:
clone(Node mynode){
return new Node(mynode.getValue());
}
For this assignment I need to recursively print a linked list in reverse with a linked list as the parameter, not a node.
I also have to use this SinglyLinkedList class that my professor provided:
public class SinglyLinkedList<E> {
private int length; // # elements in the linked list
private SLNode<E> head; // access point to the linked list
private SLNode<E> tail;
public SinglyLinkedList() {
this.length = 0;
this.tail = new SLNode<E> (); // the tail dummy node
this.head = new SLNode<E> ( null, this.tail ); // the head dummy node
}
public int getLength() {
return this.length;
}
public void add( E e ) {
SLNode<E> newnode = new SLNode<E> ( e, null );
newnode.setSuccessor( this.head.getSuccessor() );
this.head.setSuccessor( newnode );
this.length++;
}
public void add( E e, int p ) {
// verify that index p is valid
if ( ( p < 0 ) || ( p > this.length ) ) {
throw new IndexOutOfBoundsException( "index " + p
+ " is out of range: 0 to " +
this.length );
}
SLNode<E> newnode = new SLNode<E> ( e, null );
SLNode<E> cursor = this.head;
for ( int i = 0; i < p; i++ ) {
cursor = cursor.getSuccessor();
}
addAfter( cursor, newnode );
this.length++;
}
public E remove( int p ) {
if ( ( p < 0 ) || ( p >= this.length ) ) {
throw new IndexOutOfBoundsException( "index " + p
+ " is out of range: 0 to " +
( this.length - 1 ) );
}
SLNode<E> cursor = head; // good for p == 0
if ( p > 0 ) {
cursor = find( p - 1 ); // get target's predecessor
}
SLNode<E> target = cursor.getSuccessor(); // get the node to remove
// link target to cursor's successor
cursor.setSuccessor( target.getSuccessor() );
target.setSuccessor( null );
cursor.setElement( null );
this.length--;
return target.getElement();
}
public E getElementAt( int p ) {
SLNode<E> node = this.find( p );
return node.getElement();
}
private void addAfter( SLNode<E> p, SLNode<E> newnode ) {
newnode.setSuccessor( p.getSuccessor() );
p.setSuccessor( newnode );
}
private SLNode<E> find( E target ) {
SLNode<E> cursor = head.getSuccessor();
while ( cursor != tail ) {
if ( cursor.getElement().equals( target ) ) {
return cursor; // success
}
else {
cursor = cursor.getSuccessor();
}
}
return null; // failure
}
private SLNode<E> find( int p ) {
if ( ( p < 0 ) || ( p >= this.length ) ) {
throw new IndexOutOfBoundsException();
}
SLNode<E> cursor = head.getSuccessor();
int i = 0;
while ( i != p ) {
cursor = cursor.getSuccessor();
i++;
}
return cursor;
}
}
I can't figure out how to write that method with passing in a reference to a singly-linked list instead of a node. Thanks in advance for the help!
The base case is the list being empty, nothing left to print. So that's what we check for first. If base case is met, we return without printing anything. Otherwise the list has elements remaining, so we take the last element from the list (since we are printing in reverse) and pop it off the list. The remove method returns the removed element so that should do the trick. Now we recurse with our modified list (minus the last element). Eventually the list will be empty and all elements will have been printed in reverse.
public static <E> void printReverse(final SinglyLinkedList<E> list) {
if(list.getLength() > 0) {
System.out.println(list.remove(list.getLength()-1));
printReverse(list);
}
}
Haven't looked into your code deeply, but simply printing should be quite trivial:
in psuedo code:
printLinkedListInReverse(node) {
if (node has no next) {
print out node itself
} else {
printLinkedListInReverse(node's next)
print out node itself
}
}
In brief, to print in reverse, you want to print out the remaining list excluding itself first, and the print the node itself
If you cannot get hold of the internal node, and the linked list is subjected to modification, then the way is still similar:
printLinkedListInReverse(list) {
if (list is empty) {
//do nothing
} else {
firstElement = list.remove(0)
printLinkedListInReverse(list) // print the remaining list first
print firstElement
}
}
hey guys i am having trouble trying to implement the appened method for singly linked list.
here is the code:
public void append ( int item ) {
//inserts item to the end of the list
if ( head == null){
head = new LinkInt();
curr = head;
curr.elem = item;
}
else{
LinkInt temp = head;
while ( temp.next != null){
temp = temp.next;}
temp.elem = item;
}
}
and here is my print method ( not sure if its correct as well ):
public void print () {
//outprint the array
//ie. <1, 2, |3, 4>
if ( head == null) {
System.out.print("<");
System.out.print(">");
}
else{
LinkInt temp = head;
System.out.print("<");
while ( temp != null) {
if ( temp == curr){
System.out.print( "|" + temp.elem + ","); }
else{
System.out.print( temp.elem );
System.out.print(",");}
temp = temp.next;
}
System.out.print(">");
}
}
}
heres the problem:
let say appened 3 ->>> i get <|3>
but if i do appened 5 after ->>>> i get <|5> which delete my first item.
Help me out please :(
after these statement :
while ( temp.next != null)
{
temp = temp.next;
}
do this:
tmp1= new LinkInt();
tmp1.elem = item;
tmp1.next = null
tmp.next = tmp1
instead of this:
temp.elem = item;
try this for print method:
public void print ()
{
//outprint the array
//ie. <1, 2, |3, 4>
if ( head == null)
{
System.out.print("<");
System.out.print(">");
}
else
{
LinkInt temp = head;
System.out.print("<");
while ( temp->next != null)
{
System.out.print( "|" + temp.elem + ",");
temp = temp.next;
}
System.out.print("|" + temp.elem);}
System.out.print(">");
}
}
LinkInt temp = head;
while ( temp.next != null){
temp = temp.next;
}
temp.elem = item;
What this does is - temp.next is null when 3 is already inserted. Hence, it goes to temp.elem = item and overwrites your existing value. Do something like this:-
LinkInt temp = head;
while ( temp.next != null){
temp = temp.next;
}
//temp.elem = item; -Not needed.
temp1= new LinkInt();
temp1.elem = item;
temp1.next = null;
temp.next = temp1;
Have the method this way
public void append(int item)
{
LinkInt l = new LinkInt();
l.elem = item;
if ( head == null )
head = l;
else {
LinkInt tmp = head;
while ( tmp.next != null)
tmp = tmp.next;
tmp.next = l;
}
I am not sure if I am implementing the insert or append correctly but I get this error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
-1 at AListInt.insert(AListInt.java:81) // listArray[i+1] = listArray[i]; at ListTest.main(ListTest.java:52) // list.insert(i);
Also I cannot use java.util.ArrayList
Here is the code and classes for it:
class:
public class AListInt {
int [] listArray;
int listSize;
int curr; // current position
AListInt() {
listSize = 0;
// note that curr = -1 when listSize = 0
curr = -1;
listArray = new int [2];
}
public int getValue () throws DSException {
return listArray[curr];
//returns the value of current position
//throw exception when there are no elements in the list
}
public int length() {
return listSize;
//return # of elements in the list
}
public int currPos() {
return curr;
//return current position.
}
public void moveToPos ( int pos ) throws DSException {
curr = pos;
//move the current position to pos
//throw exception if pos is not a valid position
}
public void moveToStart () throws DSException {
curr = 0;
//move the current position to the start of the list
//throw exception if no elements are in the list
}
public void moveToEnd () throws DSException {
curr = listSize;
//move the current position to the end of the list
//throw exception if no elements are in the list
}
public void prev () throws DSException {
if(curr != 0)
{
curr--;
}
//move current position to the previous element
//throws exception if the previous position is not legal or
// if there are no elements in the list
}
public void next () throws DSException {
if(curr < listSize)
{
curr++;
}
//move current position to the next element
//throws exception if the next position is not legal or
// if there are no elements in the list
}
public void insert ( int item ) {
for(int i = listSize-1; i >= curr; i++)
{
listArray[i+1] = listArray[i];
}
listArray[curr] = item;
listSize ++;
int[]temp = new int[listArray.length*2];
for(int i = 0; i< listSize; i++)
{
temp[i] = listArray[i];
}
listArray = temp;
// inserts item to the current position
// if not enough memory, double the size of listArray
}
public void append ( int item ) {
listArray[listSize++] = item;
int[]temp = new int[listArray.length*2];
for(int i = 0; i< listSize; i++)
{
temp[i] = listArray[i];
listArray = temp;
}
// inserts item to the end of the list
// if not enough memory, double the size of listArray
}
public int remove () throws DSException {
if((curr < 0)||(curr > listSize))
{
return -1;
}
int item;
item = listArray[curr];
for(int i = curr; i < listSize - 1; i++)
{
listArray[i] = listArray[i+1];
}
listSize --;
return item;
//removes the element at the current position
//returns the removed element
}
public void clear() {
listSize = 0;
curr = -1;
//reset size. Set current position to be -1
}
public boolean find ( int val ) {
for(int i = 0; i > listSize; i ++)
{
if(listArray[i] == val)
{
return true;
}
}
return false;
//searches for val in the list
//returns true if found and false if not found
}
public void print () {
System.out.print("<");
for(int i = 0; i < listSize; i++)
{
System.out.print(listArray[i]);
if(listSize == -1)
{
System.out.print("-1");
}
}
System.out.print(">");
//outprint the list
}
}
exception:
public class DSException extends Exception {
public DSException() {
}
public DSException(String msg) {
super(msg);
}
}
main:
public class ListTest {
public static void main ( String[] args ) {
try {
AListInt list = new AListInt();
list.print();
// test length()
System.out.println ( list.length() );
// test currPos()
System.out.println ( list.currPos() );
// insert some numbers
for ( int i = 0; i < 4; i++ ) {
list.append(i);
list.print();
}
list.moveToPos(0);
list.print();
list.moveToEnd();
list.print();
// test getValue()
System.out.println ( list.getValue() );
System.out.println ( "remove: " + list.remove() );
list.print();
list.moveToStart();
list.print();
System.out.println ( "remove: " + list.remove() );
list.print();
list.clear();
list.print();
list.clear();
list.print();
System.out.println ( "find 0 : " + list.find ( 0 ) );
for ( int i = 0; i < 4; i++ ) {
list.insert(i);
list.print();
}
for ( int i = 0; i < 5; i++ ) {
System.out.println ( "find " + i + " : " + list.find ( i ) );
list.print();
}
list.next();
list.print();
list.insert ( -9 );
list.print();
list.append ( -2 );
list.print();
list.moveToEnd();
list.insert ( -1 );
list.print();
System.out.println ( "remove: " + list.remove() );
list.print();
} catch ( DSException e ) {
e.printStackTrace();
}
}
}
You reading outside the Array. in
for(int i = listSize-1; i >= curr; i++)
{
listArray[i+1] = listArray[i];
}
if i = listSize -1, then listArray[i+1] is listArray[listSize], which is out of bounds, since arrays go from 0 to length -1
EDIT:
But since listArray has an initial size of 2, and you double the size at each insert you get away with that. However, at the first insert curr is -1, and since the termination is i >= curr, the loop will be entered and you will read listArray[-1] (Out of bounds)
it's gotta be listArray[i]=listArray[i-1]
because you are shifting the position of listArray[i-1] to the position of listArray[i]
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have binary search tree code (It is hard code) doing ( insert , delete , max , min , sort and lookup ) and I want study efficancy for BST . I want create a random method to generate 1000 numbers rather than I enter number .
How can I create this method ?
public class BinarySearchTree {
private Node root;
private static class Node {
Node parent;
Node left;
Node right;
int data;
Node( int data ) {
this.data = data;
}
#Override
public String toString( ) {
return "" + data;
}
}
public void insert( int data ) {
root = insert( root, data );
}
public Node insert( Node node, int data ) {
if( node == null ) {
node = new Node( data );
} else if( data < node.data ) {
node.left = insert( node.left, data );
node.left.parent = node;
} else {
node.right = insert( node.right, data );
node.right.parent = node;
}
return node;
}
private void swap( Node a, Node b ) {
if( a.parent == null ) {
root = b;
} else if( a == a.parent.left ) {
a.parent.left = b;
} else {
a.parent.right = b;
}
if( b != null ) {
b.parent = a.parent;
}
}
public void delete( int data ) {
delete( root, data );
}
public void delete( Node node, int data ) {
if( node == null ) {
return;
}
else if ( data == node.data) {
if( node.left == null ) {
swap( node, node.right );
}
else if( node.right == null ) {
swap( node, node.left );
}
else {
Node minNode = node.right;
while( minNode.left != null ) {
minNode = minNode.left;
}
if( minNode.parent != node ) {
swap( minNode, minNode.right );
minNode.right = node.right;
minNode.right.parent = minNode;
}
swap( node, minNode );
minNode.left = node.left;
minNode.left.parent = minNode;
}
}
// Continue searching in the left subtree.
else if( data < node.data) {
delete( node.left, data );
}
// Continue searching in the right subtree.
else {
delete( node.right, data );
}
}
public boolean lookup( int data ) {
return lookup( root, data );
}
public boolean lookup( Node node, int data ) {
if( node == null ) {
// Can't find it.
return false;
} else if( data == node.data) {
// Found it.
return true;
} else if( data < node.data) {
// Search left subtree.
return lookup( node.left, data );
} else {
// Search right subtree.
return lookup( node.right, data );
}
}
public int minValue( ) {
return minValue( root );
}
public int minValue( Node node ) {
Node cursor = node;
while( cursor.left != null ) {
cursor = cursor.left;
}
return cursor.data;
}
public int maxValue( ) {
return maxValue( root );
}
public int maxValue( Node node ) {
Node cursor = node;
while( cursor.right != null ) {
cursor = cursor.right;
}
return cursor.data;
}
public void inorderTraversal( ) {
inorderTraversal( root );
}
private void inorderTraversal( Node node ) {
if( node != null ) {
inorderTraversal( node.left );
System.out.print( node.data + " " );
inorderTraversal( node.right );
}
}
public static void main( String[ ] args ) {
BinarySearchTree bst = new BinarySearchTree( );
int[ ] input = new int[ ] { 5, 10, 3, 9, 7, 8 , 1 , 4 , 6 , 10};
for( int i : input ) {
bst.insert( i );
}
bst.delete( 5 );
bst.delete( 10 );
bst.delete( 3 );
bst.delete( 7 );
System.out.println( "\n Sorted :" );
bst.inorderTraversal( );
System.out.println( "\nMax Value:" );
System.out.println(bst.maxValue());
System.out.println( "\n Min Value:" );
System.out.println(bst.minValue());
System.out.println(bst.lookup(1));
}
}
You might be interested in java.util.Random:
import java.util.Random;
...
Random random = new Random(System.currentTimeMillis());
random.nextInt();
Note that Random only creates pseudorandom numbers, so you'll have to use a sufficiently unique seed.
I second the java.util.Random suggestion. Do you really want to store an array of them or do you want to just ask the Random generator for a random number between 0 and 999, 1000 times? Here's a function to get an array of them, but I would just forgo the array and loop through the Random 1000 times.
public static int[] generateRandomNumbers( int size ) {
if ( size <= 0 ) {
throw new IllegalArgumentException( "size must be greater than 0" );
}
Random random = new Random( System.currentTimeMillis() );
int[] results = new int[ size ];
for ( int i = 0; i < size; i++ ) {
results[ i ] = random.nextInt( size );
}
return results;
}
...all other things equal, make your main like this and you've got a working program. I don't know whether it is correct or not, it works...
public static void main( String[] args ) {
BinarySearchTree bst = new BinarySearchTree();
int[] randoms = generateRandomNumbers( 1000 );
for ( int i : randoms ) {
bst.insert( i );
}
bst.delete( randoms[ 5 ] );
bst.delete( randoms[ 10 ] );
bst.delete( randoms[ 3 ] );
bst.delete( randoms[ 7 ] );
System.out.println( "\n Sorted :" );
bst.inorderTraversal();
System.out.println( "\nMax Value:" );
System.out.println( bst.maxValue() );
System.out.println( "\n Min Value:" );
System.out.println( bst.minValue() );
System.out.println( bst.lookup( randoms[ 1 ] ) );
System.out.println( bst.lookup( randoms[ 999 ] ) );
}
This will give you 1000 random integers between MIN and MAX, including MIN but not including MAX.
int MIN;
int MAX;
int[] randoms = new int[1000];
Random randGen = new Random();
for(int i = 0; i < randoms.length; i++)
{
randoms[i] = MIN + randGen.nextInt(MAX - MIN));
}