I'm trying to perform a linear search on an array where it finds the last occurrence of a target. I'm stuck because my search is only finding the first occurrence of the target not the last.
/** Recursive linear search that finds last occurrence of a target in the array not the first
*
* #param items The array
* #param target the item being searched for
* #param cur current index
* #param currentLength The current length of the array
* #return The position of the last occurrence
*/
public static int lineSearchLast(Object[] items, Object target, int cur, int currentLength){
if(currentLength == items.length+1)
return -1;
else if (target.equals(items[cur])&& cur < currentLength)
return cur;
else
return lineSearchLast(items, target, cur +1, currentLength);
}
public static void main (String[] args){
Integer[] numbers5 = {1,2,4,4,4};
int myResult = lineSearchLast(numbers5, 4, 0, 5);
System.out.println(myResult);
You shouldn't need two index arguments - one (a current index) should do the trick. Moreover, to make sure that you find the last equivalent element first, it's prudent to start at the back and work forward.
/** Returns the index of the last occurance of target in items */
public static int findLastOccurance(Object[] items, Object target){
return findLastOccurance(items, target, items.length - 1);
}
/** Helper method for findLastOccurance(items, target). Recursively finds
* the index of the last occurance of target in items[0...cur]
*/
private static int findLastOccurance(Object[] items, Object target, int cur){
if(curr == -1) //We went past the start - missed it.
return -1;
else if (target.equals(items[cur])) //Found it
return cur;
else
return lineSearchLast(items, target, curr-1); //Work backwards
}
Related
I am trying to find the "maximum" value in a linked list recursively using a helper function. I am just starting to learn about these in my class and am pretty confused. We have a custom class that defines the type Node and another function to calculate the size of the Node or linkedlist. I solved this problem when I was comparing integers, but with characters I am lost. Here is my code:
'''
static class Node {
public Node (char item, Node next) { this.item = item; this.next = next; }
public char item;
public Node next;
}
Node first; // this is the only instance variable,
// the access point to the list
// size
//
// a function to compute the size of the list, using a loop
// an empty list has size 0
public int size () {
int count = 0;
for (Node tmp = first; tmp != null; tmp = tmp.next)
count++;
return count;
}
/*
* maxCharacter
*
* a function to compute the 'maximum' character in the list using recursion
* You will want to create a helper function to
* do the recursion
*
* precondition: list is not empty
*
* Examples:
* ["ababcdefb"].maxCharacter() == 'f'
* ["eezzg"].maxCharacter() == 'z'
* ["a"].maxCharacter() == 'a'
*/
public char maxCharacter () {
return maxCharacterHelper(first, first.size());
}
public char maxCharacterHelper(Node first, int index) {
char[] alpha = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
int max = 0;
while(index > 0 )
max = alpha.indexOf(first.item) > max ? first.item : max;
maxCharacterHelper(first, index-1);
return max;
}
'''
If you could explain how I would loop through the list recursively while maintaining the greatest char I would greatly appreciate it.
The golden rule with recursion is "Think of the base case first, then write the recurrence".
In this case, the base is the empty list. In this case, the maximum is the last value you've seen.
The recurrence is just a call to the rest of the list with the highest value you've called.
public static MaxNode(Node n, char currentMax) {
if (n == null) // base case, we're at the end.
return currentMax;
// recurrence
return MaxNode(n.next, currentMax > n.item ? currentMax : n.item);
}
For simple ASCII values, you can treat the maximum using the > operator.
Your while loop is confusing because of indentation and because you never change index. However, I don't think you need it if your intent is to use recursion. Generally with recursion you need to establish a base case from which you cannot recurse. For a linked list the natural base case is where there is no next node, rather than index-based.
if (current.next == null)
return alpha.indexOf(current.item);
Otherwise combine the recursion return with the current value
int remainingMax = maxCharacterHelper(current);
int currentValue = alpha.indexOf(current.item);
return (remainingMax > currentValue) ? remainingMax : currentValue;
Here is how I would put it together
//I made it static because it is not a method of a specific Node
public static int maxCharacterHelper(Node currentNode){
// remaining list includes only current node, so this one has max value
if (current.next == null)
return alpha.indexOf(current.item);
//otherwise take the larger of remaining list and current node
int remainingMax = maxCharacterHelper(current.next);
int currentValue = alpha.indexOf(current.item);
return (remainingMax > currentValue) ? remainingMax : currentValue;
}
I'm trying to use these quick sort methods to figure out how many comparison are happening. We are given a global variable that does the counting but we aren't able to use the global variable when we hand it in. Instead we need to recursively count the comparisons. Now I am trying to figure out how to do that and I'm not looking for the answer, I'm trying to get on the right steps on how to solve this problem. I've been trying things for a couple hours now and no luck.
static int qSortCompares = 0; // GLOBAL var declaration
/**
* The swap method swaps the contents of two elements in an int array.
*
* #param The array containing the two elements.
* #param a The subscript of the first element.
* #param b The subscript of the second element.
*/
private static void swap(int[] array, int a, int b) {
int temp;
temp = array[a];
array[a] = array[b];
array[b] = temp;
}
public static void quickSort(int array[]) {
qSortCompares = 0;
int qSCount = 0;
doQuickSort(array, 0, array.length - 1);
}
/**
* The doQuickSort method uses the QuickSort algorithm to sort an int array.
*
* #param array The array to sort.
* #param start The starting subscript of the list to sort
* #param end The ending subscript of the list to sort
*/
private static int doQuickSort(int array[], int start, int end) {
int pivotPoint;
int qSTotal = 0;
if (start < end) {
// Get the pivot point.
pivotPoint = partition(array, start, end);
// Note - only one +/=
// Sort the first sub list.
doQuickSort(array, start, pivotPoint - 1);
// Sort the second sub list.
doQuickSort(array, pivotPoint + 1, end);
}
return qSTotal;
}
/**
* The partition method selects a pivot value in an array and arranges the
* array into two sub lists. All the values less than the pivot will be
* stored in the left sub list and all the values greater than or equal to
* the pivot will be stored in the right sub list.
*
* #param array The array to partition.
* #param start The starting subscript of the area to partition.
* #param end The ending subscript of the area to partition.
* #return The subscript of the pivot value.
*/
private static int partition(int array[], int start, int end) {
int pivotValue; // To hold the pivot value
int endOfLeftList; // Last element in the left sub list.
int mid; // To hold the mid-point subscript
int qSCount = 0;
// see http://www.cs.cmu.edu/~fp/courses/15122-s11/lectures/08-qsort.pdf
// for discussion of middle point - This improves the almost sorted cases
// of using quicksort
// Find the subscript of the middle element.
// This will be our pivot value.
mid = (start + end) / 2;
// Swap the middle element with the first element.
// This moves the pivot value to the start of
// the list.
swap(array, start, mid);
// Save the pivot value for comparisons.
pivotValue = array[start];
// For now, the end of the left sub list is
// the first element.
endOfLeftList = start;
// Scan the entire list and move any values that
// are less than the pivot value to the left
// sub list.
for (int scan = start + 1; scan <= end; scan++) {
qSortCompares++;
qSCount++;
if (array[scan] < pivotValue) {
endOfLeftList++;
// System.out.println("Pivot=" + pivotValue + "=" + endOfLeftList + ":" + scan);
swap(array, endOfLeftList, scan);
}
}
// Move the pivot value to end of the
// left sub list.
swap(array, start, endOfLeftList);
// Return the subscript of the pivot value.
return endOfLeftList;
}
/**
* Print an array to the Console
*
* #param A
*/
public static void printArray(int[] A) {
for (int i = 0; i < A.length; i++) {
System.out.printf("%5d ", A[i]);
}
System.out.println();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
final int SIZE = 10;
int[] A = new int[SIZE];
// Create random array with elements in the range of 0 to SIZE - 1;
System.out.printf("Lab#2 Sorting Algorithm Performance Analysis\n\n");
for (int i = 0; i < SIZE; i++) {
A[i] = (int) (Math.random() * SIZE);
}
System.out.printf("Unsorted Data = %s\n", Arrays.toString(A));
int[] B;
// Measure comparisons and time each of the 4 sorts
B = Arrays.copyOf(A, A.length); // Need to do this before each sort
long startTime = System.nanoTime();
quickSort(B);
long timeRequired = (System.nanoTime() - startTime) / 1000;
System.out.printf("Sorted Data = %s\n", Arrays.toString(B));
System.out.printf("Number of compares for quicksort = %8d time = %8d us Ratio = %6.1f compares/us\n", qSortCompares, timeRequired, qSortCompares / (double) timeRequired);
// Add code for the other sorts here ...
}
The instructions give some hints but I am still lost:
The quicksort method currently counts the # of comparisons by using a global variable. This is not a good programming technique. Modify the quicksort method to count comparisons by passing a parameter. This is a little trickier as the comparisons are done in the partition method. You should be able to see that the number of comparisons can be determined before the call to the partition method. You will need to return this value from the Quicksort method and modify the quickSort header to pass this value into each recursive call. You will need to add the counts recursively.
As an alternative to the recursive counting, you can leave the code as is and complete the lab without the modification.
The way I have been looking at this assignment I made a variable in the partition method called qSCount which when it is called will count how many comparisons were made. However I can't use that variable because I am not returning it. And I'm not sure how I would use recursion in that state. My idea was after each time qSCount had a value I could somehow store it in doQuickSort method under qSTotal. But then again the hint is saying I need to make a parameter in quicksort so I am all sorts of confused.
In order to count something with a recursive method (without a global variable) we need to return it. You have:
private static int doQuickSort(int array[], int start, int end)
This is the right idea. But since the comparisons actually happen within
private static int partition(int array[], int start, int end)
you need to have partition return how many comparisons were made.
This leaves us with two options:
We can either create or use an existing Pair class to have this method return a pair of integers instead of just one (the pivot).
We can create a counter class and pass a counter object around and have the counting done there. This eliminates the need to return another value since the parameter could be used to increase the count.
1.) I'm having difficulty testing me heap class. When I try to print my heap, it's giving me code instead of the array. I tried using toString() and DeeptoString() and neither worked.
2.) In my updateValue method. I realize that it doesn't know what to do once it's reached a node that has no children. It shoots me an index out of bounds. I think an easy way to check for that is to see if the left and right child index is greater or equal to the size. If it is...I guess I want it to do nothing.
Code below:
import java.util.NoSuchElementException;
public class MaxHeap {
public int[] heap;
private int size;
public static void main(String args[]){
MaxHeap testHeap = new MaxHeap(5);
testHeap.add(5);
testHeap.add(4);
testHeap.add(3);
testHeap.add(2);
testHeap.add(1);
System.out.println((testHeap));
testHeap.maxHeapify(0);
System.out.println(testHeap);
testHeap.extractMax();
System.out.println(testHeap);
testHeap.updateValue(1, 6);
System.out.println(testHeap);
}
/**
* _Part 0: Implement this constructor._
*
* Creates a new Heap instance initially capable of storing the specified
* number of elements.
*
* #param initialsize the initial size of the heap array
*/
public MaxHeap(int initialsize) {
// TODO: implement this
heap = new int [initialsize];
}
/**
* Provides read-only access to the heap's size. Size here is the number
* of *valid* items in the heap
*
* #return the number of items in the heap
*/
public int size() {
return size;
}
/**
* _Part 1: Implement this method._
*
* Adds an item to the heap maintaining the heap condition.
*
* An item is added to the next available slot in the array, and then
* bubbled up to its parent until the heap condition is restored.
*
* #param item
* the new int to add to the heap
*/
public void add(int item) {
// TODO: implement this
int parentIndex = (size-1)/2;
int childIndex = size;
heap[size] = item; //put it at the end
while (heap[parentIndex] < heap[childIndex] && parentIndex >= 0){ //check to make sure it's a proper heap
int temp = heap[parentIndex]; //start percolating up
heap[parentIndex] = heap[childIndex];
heap[childIndex] = temp;
childIndex = parentIndex;
parentIndex = (parentIndex-1)/2;
}
size+=1;
}
/**
* _Part 2: Implement this method._
*
* Restore the heap condition to a tree rooted at the specified index when
* the left and right subtrees obey the heap condition, but the root may
* not. This is also known as "Bubble Down".
*
* That is, given the specified index, and the fact that the left and
* right subtrees are heaps (if they exist), ensure that the largest of
* these three nodes get's swapped with the root, and then recursively
* restore the heap condition for the subtree with the element that was
* moved from the root.
*
* In essence, this method bubbles a value down from the root until the
* heap condition is restored.
*
* #param index
* the root tree to restore
*/
public void maxHeapify(int index) {
// TODO: implement this
int left, right, large, tmp; // declare variables left child, right child, largest node, temp for swap
int i = index;
left = 2 * i + 1; // left child
right = 2 * i + 2; // right child
if(left <= heap.length-1 && heap[left] > heap[i]) // find smallest child
large = left; // save index of smaller child
else
large = i;
if(right <= heap.length-1 && heap[right] > heap[large])
large = right; // save index of smaller child
if(large != i) // swap and percolate, if necessary
{
tmp = heap[i]; // exchange values at two indices
heap[i] = heap[large];
heap[large] = tmp;
maxHeapify(large);}
}
/**
* _Part 3: Implement this method._
*
* Removes the maximum valued item from the heap and restores the heap
* condition. If the heap is empty, this method should throw
* a NoSuchElementException
*
* This function is performed by:
*
* 1. removing the root of the heap
* 2. placing element from the end of the heap at the root
* 3. calling maxHeapify to restore the heap condition
* 4. making sure the size is updated
*
* #return the highest valued item from the heap
* #throws NoSuchElementException if called on an empty heap
*/
public int extractMax() {
// TODO: implement this
if (size < 1){
//throw no such element
throw new NoSuchElementException();
}
int max = heap[0];
heap[0] = heap[size-1];
size = size-1;
maxHeapify(0);
return max;
}
/**
* _Part 4: Implement this method._
*
* Checks to make sure that the *max* heap condition is upheld on a
* given array of integers.
*
* HINT: Full credit will be given on this one if you implement this
* method as a *recursive* function. It will probably make sense to
* create a private method that takes another argument (e.g., the index
* of the heap's root) to indicate where the checking should begin.
*
* My private method has the following signature:
* private static boolean check(int [] arry, int rootindx, int sz)
*
*
* #param array
* the array of data to check
* #param size
* the number of elements 'in' the heap (starting at index 0)
* #return true if the *max* heap condition is upheld
*/
public static boolean checkHeapCondition(int[] array, int size) {
// TODO: implement this
if (array != null)
return helpCheck(array,0, size);
return false;
}
//Helper method
private static boolean helpCheck(int[] arr, int i, int size) {
//Base case
if (i == size-1)
return true;
//2nd base case
if (2*i+1 >= size){
return true;
}
// check if a parent's value is larger or equal to both of
// its left child and right child
else if (arr[i] >= arr[2*i + 1] && arr[i] >= arr[2*i + 2])
return (helpCheck(arr, 2*i + 1, size) && helpCheck(arr, 2*i + 2, size));
else
return false;
}
/**
* _Part 5: Implement this method._
*
* Changes the value of an element in the heap. And bubbles the value
*
* #param index
* the index of the item to be modified
* #param newValue
* the new value of the specified item
* #return the old value of that item
* #throws IndexOutOfBoundsException if the specified index is invalid
*/
public int updateValue(int index, int newValue) {
// TODO: implement this
int parent = (index-1)/2;
int leftChild = (2*index +1);
int rightChild = (2*index+2);
if (heap == null || index >= size ){
throw new IndexOutOfBoundsException();}
int oldValue = heap[index];
heap[index] = newValue;
while (heap[parent] < heap[index] && parent >= 0 ){
int temp = heap[parent];
heap[parent] = heap[index];
heap[index] = heap[temp];
index = parent;
parent = (parent-1)/2;
}
//We need to check to see if the children don't exist
if (heap[leftChild] > heap[index] || heap[rightChild] > heap[index]){
maxHeapify(index);
return oldValue;
}
else return oldValue;
}
}
The method System.out.print(Object o) uses the parameter Object's toString() method. If you have not overridden this method to provide custom behavior, it will use the parent method (in this case, the default Object.toString()).
To print the value of MaxHeap, override it's toString method, returning a String that you want to represent an instance of this class. For instance:
#Override
public String toString(){
return java.util.Arrays.toString(heap);
}
I have found what's wrong with my updateValue. I created another if statement to check if the index value of the left and right child were within bounds. Thanks for all your help.
I'm trying to make a string binary search program. Trouble is I don't remember a straight forward way to convert a string array into a Integer array.
I've written a long and complicated way to convert them. However Netsbeans is saying my string array identifier is expected.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication3;
/**
*
* #author Ivan Beazer
*/
import java.io.*;
/**
This program demonstrates the search method in
the IntBinarySearcher class.
*/
public class BinarySearchTest
{
private static String aString;
// Convert string array to string
public static String arrayToString2(String[] words, String aString)
{
StringBuilder result = new StringBuilder();
if (words.length > 0)
{
result.append(words[0]);
for (int i=1; i<words.length; i++)
{
result.append(aString);
result.append(words[i]);
}
}
return result.toString();
}
public static void main(String [] args) throws IOException
{
int result, searchValue;
String input;
// A String array of words to search.
// This is the error. netbeans says identifier is expected.
String[] words = {"Jake", "Jerry". "Bill", "Lousie", "Goku", "Ivan", "John", "sarah", "kim"};
// convert string to int array
int[] numbers = new int[aString.length()];
for(int i=0; i<aString.length(); i++)
numbers[i] = Character.getNumericValue(aString.charAt(i));
// Create the console input objects.
InputStreamReader reader =
new InputStreamReader(System.in);
BufferedReader keyboard =
new BufferedReader(reader);
// First we must sort the array in ascending order.
IntQuickSorter.quickSort(numbers);
do
{
// Get a value to search for.
System.out.print("Enter a value to search for: ");
input = keyboard.readLine();
searchValue = Integer.parseInt(input);
// Search for the value
result = IntBinarySearcher.search(numbers, searchValue);
// Display the results.
if (result == -1)
System.out.println(searchValue + " was not found.");
else
{
System.out.println(searchValue + " was found at " +
"element " + result);
}
// Does the user want to search again?
System.out.print("Do you want to search again? (Y or N): ");
input = keyboard.readLine();
} while (input.charAt(0) == 'y' || input.charAt(0) == 'Y');
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication3;
/**
*
* #author Devon B
*/
/**
The IntBinarySearcher class provides a public static
method for performing a binary search on an int array.
*/
public class IntBinarySearcher
{
/**
The search method performs a binary search on an int
array. The array is searched for the number passed to
value. If the number is found, its array subscript is
returned. Otherwise, -1 is returned indicating the
value was not found in the array.
#param array The array to search.
#param value The value to search for.
*/
public static int search(int[] array, int value)
{
int first; // First array element
int last; // Last array element
int middle; // Mid point of search
int position; // Position of search value
boolean found; // Flag
// Set the inital values.
first = 0;
last = array.length - 1;
position = -1;
found = false;
// Search for the value.
while (!found && first <= last)
{
// Calculate mid point
middle = (first + last) / 2;
// If value is found at midpoint...
if (array[middle] == value)
{
found = true;
position = middle;
}
// else if value is in lower half...
else if (array[middle] > value)
last = middle - 1;
// else if value is in upper half....
else
first = middle + 1;
}
// Return the position of the item, or -1
// if it was not found.
return position;
}
}
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication3;
/**
*
* #author Devon B
*/
/**
The IntQuickSorter class provides a public static
method for performing a QuickSort on an int array.
*/
public class IntQuickSorter
{
/**
The quickSort method calls the doQuickSort method
to sort an int array.
#param array The array to sort.
*/
public static void quickSort(int array[])
{
doQuickSort(array, 0, array.length - 1);
}
/**
The doQuickSort method uses the QuickSort algorithm
to sort an int array.
#param array The array to sort.
#param start The starting subscript of the list to sort
#param end The ending subscript of the list to sort
*/
private static void doQuickSort(int array[], int start, int end)
{
int pivotPoint;
if (start < end)
{
// Get the pivot point.
pivotPoint = partition(array, start, end);
// Sort the first sub list.
doQuickSort(array, start, pivotPoint - 1);
// Sort the second sub list.
doQuickSort(array, pivotPoint + 1, end);
}
}
/**
The partiton method selects a pivot value in an array
and arranges the array into two sub lists. All the
values less than the pivot will be stored in the left
sub list and all the values greater than or equal to
the pivot will be stored in the right sub list.
#param array The array to partition.
#param start The starting subscript of the area to partition.
#param end The ending subscript of the area to partition.
#return The subscript of the pivot value.
*/
private static int partition(int array[], int start, int end)
{
int pivotValue; // To hold the pivot value
int endOfLeftList; // Last element in the left sub list.
int mid; // To hold the mid-point subscript
// Find the subscript of the middle element.
// This will be our pivot value.
mid = (start + end) / 2;
// Swap the middle element with the first element.
// This moves the pivot value to the start of
// the list.
swap(array, start, mid);
// Save the pivot value for comparisons.
pivotValue = array[start];
// For now, the end of the left sub list is
// the first element.
endOfLeftList = start;
// Scan the entire list and move any values that
// are less than the pivot value to the left
// sub list.
for (int scan = start + 1; scan <= end; scan++)
{
if (array[scan] < pivotValue)
{
endOfLeftList++;
swap(array, endOfLeftList, scan);
}
}
// Move the pivot value to end of the
// left sub list.
swap(array, start, endOfLeftList);
// Return the subscript of the pivot value.
return endOfLeftList;
}
/**
The swap method swaps the contents of two elements
in an int array.
#param The array containing the two elements.
#param a The subscript of the first element.
#param b The subscript of the second element.
*/
private static void swap(int[] array, int a, int b)
{
int temp;
temp = array[a];
array[a] = array[b];
array[b] = temp;
}
}
Look after the string "Jerry":
String[] words = {"Jake", "Jerry". "Bill", "Lousie", "Goku", "Ivan", "John", "sarah", "kim"};
You have a dot ( . ) instead of a comma ( , )
I'm a first year computer science student having a problem with part of an assignment. The goal of the assignment was to store the coefficients for a polynomial and find its roots using both an array and a linked list. I was able to successfully complete the array version; however the linked list is giving me a headache.
I am able to successfully store the initial round of variables provided in polynomial.java; however, things go a bit crazy once the root calculations begin and the program ends up terminating without giving any roots. I have a feeling this might be being cause by the way the Polynomial.java calculates the roots causing problems with the linked list; however, I am not allowed to change polynomial.java, only LinkedIntList.java. I have been banging my head against the computer for the past 7 hours trying to find the bug and am about ready to just give up on the assignment as I can't reach the professor for help.
I'd greatly appreciate anyone who can spot the bug or are willing to look over the code to provide tips on what I may be doing wrong or how I can work around my problem.
File 1: Node.Java
package lists;
public class Node
{
int element;
Node next = null;
/**
* Constructor which creates a new node containing the value specified by item
*
*/
public Node (int item)
{
element = item;
}
/**
* Returns the current value of the data item contained inside this node
*/
public int getElement ()
{
return element;
}
/**
* Sets the current value of the data item contained inside this node to
* the value specified by newVal
*/
public void setElement (int newVal)
{
element = newVal;
}
/**
* Links this node to the node passed in as an argument
*/
public void setNext (Node n)
{
next = n;
}
/**
* Returns a reference to the node that follows this node in the
* linked list, or null if there is no such node
*/
public Node getNext ()
{
return next;
}
/**
* Returns a string based representation of the data item contained
* in this node.
*/
public String toString()
{
return Integer.toString(element);
}
}
File 2: LinkedIntList.Java
package lists;
public class LinkedIntList implements IntList
{
Node head = null;
int count = 0;
/**
* Standard Java toString method that returns a string
* equivalent of the IntList
*
* #return a string indicating the values contained in
* this IntList (ex: "[5 3 2 9 ]")
*/
public String toString()
{
String retVal = "";
String intermediary = "";
Node n;
for (n = head; n.getNext() != null; n = n.getNext())
{
intermediary = Integer.toString(n.getElement());
retVal = intermediary + " " + retVal;
}
retVal = n.getElement() + " " + retVal;
return retVal;
}
/**
* Adds the given value to the <b>end</b> of the list.
*
* #param value the value to add to the list
*/
public void add (int value)
{
Node newNode = new Node (value);
if (head == null)
head = newNode;
else
{
Node n = head;
while (n.getNext() != null)
{
n = n.getNext();
}
n.setNext(newNode);
}
count++;
}
/**
* Returns the number of elements currently in the list.
*
* #return the number of items currently in the list
*/
public int size()
{
return count;
}
/**
* Returns the element at the specified position in this list.
*
* #param index index of the element to return (zero-based)
* #return the element at the specified position in this list.
* #throws IndexOutOfBoundsException if the index is out of range
* (index < 0 || index >= size()).
*/
public int get(int index) throws IndexOutOfBoundsException
{
Node reference = head;
if (index < 0 || index >= count)
{
throw new IndexOutOfBoundsException("Index out of bounds.");
}
for (int i = 0; i != index; i++)
{
reference.getNext();
}
return reference.getElement();
}
/**
* Replaces the element at the specified position in this list with
* the specified element.
*
* #param index index of the element to return (zero-based)
* #param value element to be stored at the specified position.
* #throws IndexOutOfBoundsException if the index is out of range
* (index < 0 || index >= size()).
*/
public void set (int index, int value) throws IndexOutOfBoundsException
{
if (index < 0 || index >= count)
{
throw new IndexOutOfBoundsException("Index out of bounds.");
}
Node newNode = new Node (value);
Node trailingReference = head;
Node leadingReference = head.getNext();
for(int i = 1; i != index; i++)
{
trailingReference = leadingReference;
leadingReference = leadingReference.getNext();
}
trailingReference.setNext(newNode);
newNode.setNext(leadingReference);
count++;
}
}
File 3: IntList.Java
package lists;
public interface IntList
{
/**
* Standard Java toString method that returns a string
* equivalent of the IntList
*
* #return a string indicating the values contained in
* this IntList (ex: "[5 3 2 9 ]")
*/
public String toString();
/**
* Adds the given value to the <b>end</b> of the list.
*
* #param value the value to add to the list
*/
public void add (int value);
/**
* Returns the number of elements currently in the list.
*
* #return the number of items currently in the list
*/
public int size();
/**
* Returns the element at the specified position in this list.
*
* #param index index of the element to return (zero-based)
* #return the element at the specified position in this list.
* #throws IndexOutOfBoundsException if the index is out of range
* (index < 0 || index >= size()).
*/
public int get(int index);
/**
* Replaces the element at the specified position in this list with
* the specified element.
*
* #param index index of the element to return (zero-based)
* #param value element to be stored at the specified position.
* #throws IndexOutOfBoundsException if the index is out of range
* (index < 0 || index >= size()).
*/
public void set (int index, int value);
}
File 4: Polynomial.java
/**
* A program which finds the integer (whole number) roots of a
* polynomial with integer coeffecients. The method used is based
* upon the ideas presented at:
*
*/
import lists.*;
public class Polynomial
{
public static void main (String [] args)
{
// trick to get out of static context
new Polynomial().runMe();
}
public void runMe()
{
IntList poly = new LinkedIntList();
// Create the polynomial:
// 3x^10 + 12x^9 - 496x^8 - 211x^7 + 18343x^6 -43760x^5 +
// 11766x^4 + 26841x^3 - 126816x^2 + 37278x - 84240
poly.add (-84240);
poly.add (37278);
poly.add (-126816);
poly.add (26841);
poly.add (11766);
poly.add (-43760);
poly.add (18343);
poly.add (-211);
poly.add (-496);
poly.add (12);
poly.add (3);
System.out.print ("Finding the integer roots of the polynomial: ");
System.out.println (poly);
IntList roots = findRoots (poly);
for (int x = 0; x < roots.size(); x++)
System.out.println ("Root found: " + roots.get(x));
}
/**
* Find all *integer* roots of the polynomial represented by the IntList.
*
* #param poly a polynomial encoded as a list of coefficients
* #return a list of all roots of the given polynomial. Note that
* the returned list may have duplicate entries.
*/
public IntList findRoots (IntList poly)
{
IntList l = new LinkedIntList();
int q = poly.get(poly.size() - 1);
int p = poly.get(0);
IntList pVals = divTerms(Math.abs(p));
IntList qVals = divTerms(Math.abs(q));
IntList possibleZeros = findPotentialZeros(pVals, qVals);
//for (Integer i : possibleZeros)
for (int x = 0; x < possibleZeros.size(); x++)
if (eval (poly, possibleZeros.get(x)) == 0)
l.add (possibleZeros.get(x));
return l;
}
/**
* Evaluates the polynomial represented by the IntList with the given
* value.
*
* #param poly a
* #param val the value to evaluate the polynomial with.
* #return f(val), where f is the polynomial encoded as poly
*/
private int eval (IntList poly, int val)
{
int result = 0;
for (int x = poly.size() - 1; x >= 0; x--)
result += poly.get(x) * (int) Math.pow (val, x);
return result;
}
private IntList findPotentialZeros (IntList plist, IntList qlist)
{
IntList result = new LinkedIntList();
for (int p = 0; p < plist.size(); p++)
{
for (int q = 0; q < qlist.size(); q++)
{
// add it only if q evenly divides p (we're looking
// for integer roots only
if (plist.get(p) % qlist.get(q) == 0)
{
int x = plist.get(p) / qlist.get(q);
result.add (x);
result.add (-x);
}
}
}
return result;
}
/**
* Find all integers that evenly divide i.
*
* #param i the integer to find all divisors of
* #return a list of all integers that evenly divide i
*/
private IntList divTerms (int i)
{
IntList v = new LinkedIntList();
// 1 divides all numbers
v.add(1);
// find all divisors < i and >= 2
for (int x = 2; x < i; x++)
if (i % x == 0)
v.add(x);
// all numbers are evenly divisible by themselves
if (i > 1)
v.add(i);
return v;
}
}
I think, the mistake (or one of them) is in your LinkedList imlementation, exactly in get method:
public int get(int index) throws IndexOutOfBoundsException
{
Node reference = head;
if (index < 0 || index >= count)
{
throw new IndexOutOfBoundsException("Index out of bounds.");
}
for (int i = 0; i != index; i++)
{
reference.getNext(); // <--- the mistake is here
}
return reference.getElement();
}
Your reference always refers on the head of the list.
If you're allowed to use any java packages - use java.util.LinkedList. Otherwise, use java.util.LinkedList until all other parts of your programm would be finished and tested and work as you wish. After that carefully replace it with your LinkedList implementation.
The set method in the LinkedIntList isn't adhering to the contract specified in the Javadoc. It says replace the element at the given index but I see code that adds a new Node.
Have a look at what methods the Node class provides to help you make the set method a lot easier and correct.
Take a good look at your get implementation. It does not do what you think.