You can find ArrayLinearLists from here in EPROGS Trying to sort a datas from .txt file into three different ArrayLinearLists. But the problem is about their capacity. Whenever the .add function is called the capacity is doubled.
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String line;
int indexOfCode = 0;
int indexOfName = 1;
int indexOfCredit = 2;
int count = 0;
ArrayLinearList codeR = new ArrayLinearList();
ArrayLinearList nameR = new ArrayLinearList();
ArrayLinearList creditR = new ArrayLinearList();
try (BufferedReader br = new BufferedReader(new FileReader("Subjects.txt"))) {
while ((line = br.readLine()) != null) {
String values[] = line.split("/");
codeR.add(0, values[indexOfCode]);
nameR.add(0, values[indexOfName]);
creditR.add(0, values[indexOfCredit]);
}
System.out.println(codeR);
System.out.println(nameR);
System.out.println(creditR);
}
}
}
Here is the ArrayLinearList codes
protected Object[] element; // array of elements
protected static int size; // number of elements in array
protected static ArrayLinearList theObject;
// constructors
/**
* create a list with initial capacity initialCapacity
*
* #throws IllegalArgumentException
* when initialCapacity < 1
*/
public ArrayLinearList(int initialCapacity) {
if (initialCapacity < 1)
throw new IllegalArgumentException("initialCapacity must be >= 1");
// size has the default initial value of 0
element = new Object[initialCapacity];
}
/** create a list with initial capacity 10 */
public ArrayLinearList() {// use default capacity of 10
this(10);
}
// methods
/** #return true iff list is empty */
public boolean isEmpty() {
return size == 0;
}
/** #return current number of elements in list */
public int size() {
return size;
}
/**
* #throws IndexOutOfBoundsException
* when index is not between 0 and size - 1
*/
void checkIndex(int index) {
if (index < 0 || index >= size)
throw new IndexOutOfBoundsException("index = " + index + " size = " + size);
}
/**
* #return element with specified index
* #throws IndexOutOfBoundsException
* when index is not between 0 and size - 1
*/
public Object get(int index) {
checkIndex(index);
return element[index];
}
/**
* #return index of first occurrence of theElement, return -1 if theElement
* not in list
*/
public int indexOf(Object theElement) {
// search element[] for theElement
for (int i = 0; i < size; i++)
if (element[i].equals(theElement))
return i;
// theElement not found
return -1;
}
/**
* Remove the element with specified index. All elements with higher index
* have their index reduced by 1.
*
* #throws IndexOutOfBoundsException
* when index is not between 0 and size - 1
* #return removed element
*/
public Object remove(int index) {
checkIndex(index);
// valid index, shift elements with higher index
Object removedElement = element[index];
for (int i = index + 1; i < size; i++)
element[i - 1] = element[i];
element[--size] = null; // enable garbage collection
return removedElement;
}
/**
* Insert an element with specified index. All elements with equal or higher
* index have their index increased by 1.
*
* #throws IndexOutOfBoundsException
* when index is not between 0 and size
*/
public void add(int index, Object theElement) {
if (index < 0 || index > size)
// invalid list position
throw new IndexOutOfBoundsException("index = " + index + " size = " + size);
// valid index, make sure we have space
if (size == element.length)
// no space, double capacity
element = ChangeArrayLength.changeLength1D(element,2* size);
// shift elements right one position
for (int i = size - 1; i >= index; i--)
element[i + 1] = element[i];
element[index] = theElement;
size++;
}
/** convert to a string */
public String toString() {
StringBuffer s = new StringBuffer("[");
// put elements into the buffer
for (int i = 0; i < size; i++)
if (element[i] == null)
s.append("null, ");
else
s.append(element[i].toString() + ", ");
if (size > 0)
s.delete(s.length() - 2, s.length()); // remove last ", "
s.append("]");
// create equivalent String
return new String(s);
}
/** create and return an iterator */
public Iterator iterator() {
return new ArrayLinearListIterator((MyArrayList) this);
}
/** test program */
public static void main(String[] args) {
// test default constructor
LinearList x = new ArrayLinearList();
// test size
System.out.println("Initial size is " + x.size());
// test isEmpty
if (x.isEmpty())
System.out.println("The list is empty");
else
System.out.println("The list is not empty");
// test put
x.add(0, new Integer(2));
x.add(1, new Integer(6));
x.add(0, new Integer(1));
x.add(2, new Integer(4));
System.out.println("List size is " + x.size());
// test toString
System.out.println("The list is " + x);
// test indexOf
int index = x.indexOf(new Integer(4));
if (index < 0)
System.out.println("4 not found");
else
System.out.println("The index of 4 is " + index);
index = x.indexOf(new Integer(3));
if (index < 0)
System.out.println("3 not found");
else
System.out.println("The index of 3 is " + index);
// test get
System.out.println("Element at 0 is " + x.get(0));
System.out.println("Element at 3 is " + x.get(3));
// test remove
System.out.println(x.remove(1) + " removed");
System.out.println("The list is " + x);
System.out.println(x.remove(2) + " removed");
System.out.println("The list is " + x);
if (x.isEmpty())
System.out.println("The list is empty");
else
System.out.println("The list is not empty");
System.out.println("List size is " + x.size());
}
}
And thanks in advance ,great senior developers :D
For a developer using ArrayLinearList this means giving a larger initial capacity, to prevent too many increases.
Using an estimate:
Path path = Paths.get("Subjects.txt");
int initialCapacity = (int)(Files.size(path) / 3);
For a developer implementing ArrayLinearList heshe could pick a larger default initial capacity, or something like increasing the array size by 1000 + array.length/4, to not waiste as much space, and initially have not so many repeated increases.
Related
I need to write a function that takes an array and prints '*' for each index by the value of the index
for example for 1,2,3,4 the output will look like this:
enter image description here
but my output is vertical
1
2
3
4
this is my printing code :
public static void printStars(int[] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 1; j <= a[i]; j++)
System.out.print("*");
System.out.println(" " + a[i]);
}
}
[edit] try the following:
public static void printStars(int[] a) {
int maxValue = Collections.max(Arrays.stream(a).boxed().toList());
String[] line = new String[a.length]; //this also works
for (int i = maxValue; i >=0 ; i--) {
//String[] line = new String[a.length]; //this will keep allocating new memory
for (int j = 0; j < a.length; j++) {
if (i == 0) {
line[j] = String.valueOf(j+1); //<change j+1 to a[j] in order to print out the value at each index of the array if you are not looking to print indexes
}else if (a[j] >= i) {
line[j] = "*";
}else {
line[j] = " ";
}
}
System.out.println(String.join(" ", line));
}
}
it takes the maximum value in the array and stores in a variable. This is used to iterate each line. After that, it checks if at this current iteration, does an index of your array contain an asterisk in this location? if yes, assign asterisk to the specific index of the string array corresponding to index of original array, else assign whitespace.
Finally, when it goes to 0, you assign the either the values of your array or the indexes of the array to the string[]. Then you print the array by using String.join() with a delimiter of whitespace. This allows you to focus on white index contains a whitespace or not, and not need to focus on the formatting of whitespaces in between each item.
for the input [1,2,3,4] output is:
*
* *
* * *
* * * *
1 2 3 4
for the input [1,7,3,4]:
*
*
*
* *
* * *
* * *
* * * *
1 2 3 4
The solution from the previous answer works but I provided a slightly more compact version printStars and renamed the old one to printStarsOld. Here is the code:
import org.junit.jupiter.api.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class IntTest {
public static void printStarsOld(int[] a) {
int maxValue = Collections.max(Arrays.stream(a).boxed().toList());
String[] line = new String[a.length]; //this also works
for (int i = maxValue; i >= 0; i--) {
for (int j = 0; j < a.length; j++) {
if (i == 0) {
line[j] = String.valueOf(j + 1);
} else if (a[j] >= i) {
line[j] = "*";
} else {
line[j] = " ";
}
}
System.out.println(String.join(" ", line));
}
}
public static void printStars(int[] a) {
List<Integer> list = Arrays.stream(a).boxed().toList();
StringBuffer string = new StringBuffer();
Integer max = list.stream().max(Integer::compare).get();
for (int i = max; i > 0; i--) {
int finalI = i;
list.forEach(integer -> string.append(integer - finalI < 0 ? ' ' : '*').append(' '));
System.out.println(string.toString());
string.setLength(0);
}
for (Integer i=1; i<=list.size();i++) System.out.print(i.toString() + ' ');
}
#Test
public void test() {
System.out.println("Old output: ");
printStarsOld(new int[]{2, 4, 5, 1, 3});
System.out.println("New output: ");
printStars(new int[]{2, 4, 5, 1, 3});
}
}
The output is:
Old output:
*
* *
* * *
* * * *
* * * * *
1 2 3 4 5
New output:
*
* *
* * *
* * * *
* * * * *
1 2 3 4 5
My program doesn't show each of the correct list it's being sorted, number of comparison and number of assignment except bubble sorting method. I think I missed to reset the input string but could not figure out the way to reset input.
Is there any way to sort one input in different sorting method.
Here is my code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
/**
* Create a program that does head-to-head comparisons between four sorting
* methods: improved bubble sort; selection sort; insertion sort; and Shell
* sort.
*
*/
public class SortAlgorithms {
private static char tracing;
private static char list;
private static int numAsgn = 0;
private static int numComp = 0;
private static int size;
private static int min;
private static int max;
private static final Scanner KBD = new Scanner(System.in);
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("How many elements do you want in the list? ");
size = KBD.nextInt();
System.out.print("What are the smallest and largest values for lsit elements? ");
min = KBD.nextInt();
max = KBD.nextInt();
KBD.nextLine();
pause();
System.out.print("Would you like to see the list before it's sorted? ");
list = Character.toUpperCase(br.readLine().charAt(0));
System.out.print("Would you like to see the list as it's being sorted? ");
tracing = Character.toUpperCase(br.readLine().charAt(0));
pause();
sortNumbers();
}
// prompt the user and wait for them to press enter
private static void pause() {
System.out.print("\n...Press enter...");
KBD.nextLine();
System.out.println();
}
/**
* Sort a list of integer values, generated randomly.
*/
public static void sortNumbers() {
resetCounts();
Integer[] numbers = randomNumbers(size, min, max);
if (list == 'Y') {
System.out.println("Here is the list: " + Arrays.toString(numbers));
pause();
}
System.out.printf("\n%1s%25s%20s%20s\n", "Method", "#COMP", "#ASGN", "#OPS");
bubbleSort(numbers);
System.out.printf("%1s%25d%20d%20d\n", "Bubble", numComp, numAsgn, numAsgn + numComp);
selectionSort(numbers);
System.out.printf("%1s%22d%20d%20d\n", "Selection", numComp, numAsgn, numAsgn + numComp);
insertionSort(numbers);
System.out.printf("%1s%22d%20d%20d\n", "Insertion", numComp, numAsgn, numAsgn + numComp);
shellSort(numbers);
System.out.printf("%1s%26d%20d%20d\n", "Shell", numComp, numAsgn, numAsgn + numComp);
}
/**
* Reset the operation counts to zero.
*/
public static void resetCounts() {
numAsgn = 0;
numComp = 0;
}
/**
* Generate an array of random values.
*
* #param howMany the length of the list to be generated.
* #param lo the smallest value allowed in the list
* #param hi the largest value allowed in the list
*/
public static Integer[] randomNumbers(int size, int min, int max) {
int range = max - min + 1;
Integer[] result = new Integer[size];
for (int i = 0; i < size; ++i) {
result[i] = (int) (min + range * Math.random());
}
return result;
}
/**
* Perform bubble sort on the given array.
*
* #param a the array to sort.
*/
public static <T extends Comparable<? super T>>
void bubbleSort(T[] a) {
for (int i = a.length - 1; i > 0; --i) {
boolean elementSwapped = false;
//numComp++;
for (int j = 0; j < i; ++j) {
numComp++;
if (a[j].compareTo(a[j + 1]) > 0) {
numAsgn += 3;
T temp = a[j + 1];
a[j + 1] = a[j];
a[j] = temp;
elementSwapped = true;
}
}
if (!elementSwapped) {
break;
}
//if (tracing == 'Y') {
System.out.println("one more bubbled up: "
+ Arrays.toString(a));
//}
}
}
/**
* Perform insertion sort on the given array.
*
* #param a the array to sort.
*/
public static <T extends Comparable<? super T>>
void insertionSort(T[] a) {
for (int i = 0; i < a.length - 1; ++i) {
int p = i + 1;
T temp = a[p];
++numAsgn;
while (p > 0 && a[p - 1].compareTo(temp) > 0) {
++numComp;
a[p] = a[p - 1];
++numAsgn;
--p;
}
if (p > 0) {
++numComp; // count the last a[p-1] comparison
}
a[p] = temp;
++numAsgn;
//if (tracing == 'Y') {
System.out.println("one more inserted: " + Arrays.toString(a));
//}
}
}
/**
* Perform selection sort on the given array. if tracing, show the array
* after each selection round.
*
* #param a the array to sort
*/
public static <T extends Comparable<? super T>>
void selectionSort(T[] a) {
for (int i = 0; i < a.length - 1; ++i) {
int p = i;
++numAsgn;
for (int j = i + 1; j < a.length; ++j) {
++numComp;
if (a[j].compareTo(a[p]) < 0) {
p = j;
++numAsgn;
}
}
T temp = a[i];
a[i] = a[p];
a[p] = temp;
++numAsgn;
//if (tracing == 'Y') {
System.out.println("one more selected: " + Arrays.toString(a));
//}
}
}
/**
* Perform shell sort on the given array.
*
* #param a the array to sort.
*/
public static <T extends Comparable<? super T>>
void shellSort(T[] a) {
int gap = a.length / 2;
++numComp;
while (gap >= 1) {
if (gap % 2 == 0) {
++gap;
}
++numComp;
for (int i = gap; i < a.length; ++i) {
++numAsgn;
int p = i;
T temp = a[p];
++numComp;
while (p >= gap && a[p - gap].compareTo(temp) > 0) {
a[p] = a[p - gap];
p -= gap;
++numAsgn;
}
a[p] = temp;
++numAsgn;
}
//if (tracing == 'Y') {
System.out.println("...gap=" + gap + ": " + Arrays.toString(a));
// }
gap /= 2;
}
}
/**
* Calculate how many operations a list of the given length should take.
*
* #param numItems the number of elements in a list.
* #return the number of operations expected (on average) to sort that list
*/
private static int expect(int numItems) {
return (numItems * numItems + numItems) * 5 / 4;
}
}
You are overriding array numbers each time you sort, so since bubbleSort is the first sorting method, you only get to see that one. Each consecutive sorting method just operates on a sorted array. Also since you've defined your counts as member variables, you need to call resetCounts() right before each method to get a fresh count. Making a copy of the array before you pass it to each sorting method, and resetting the counts should fix this.
System.out.printf("\n%1s%25s%20s%20s\n", "Method", "#COMP", "#ASGN", "#OPS");
resetCounts();
bubbleSort(Arrays.copyOf(numbers, numbers.length));
System.out.printf("%1s%25d%20d%20d\n", "Bubble", numComp, numAsgn, numAsgn + numComp);
resetCounts();
selectionSort(Arrays.copyOf(numbers, numbers.length));
System.out.printf("%1s%22d%20d%20d\n", "Selection", numComp, numAsgn, numAsgn + numComp);
resetCounts();
insertionSort(Arrays.copyOf(numbers, numbers.length));
System.out.printf("%1s%22d%20d%20d\n", "Insertion", numComp, numAsgn, numAsgn + numComp);
resetCounts();
shellSort(numbers);
System.out.printf("%1s%26d%20d%20d\n", "Shell", numComp, numAsgn, numAsgn + numComp);
The problem is as follows:
You have an array of integers, such as [2,3,1,4,0]. You want to find a path to the last index. You can either move left or right, starting from index 0. The amount of steps you can move along the array depends on the value at the index position. In the end you want to print all the paths.
In my example, you start at index 0, which contains 2. You cannot move left, therefore you move right. Now you are at index 2, which contains 1. You can then move left 1 to reach index 1 which contains 3, then move right 3 to reach the last index.
I am having issues with both the implementation and an idea of how to print out all possible solutions.
My code is as follows:
public static boolean solveH(int index){
if(index == data.size()-1){
printSol(stages);
return true;
}
boolean success = false;
if(!success && (index + Integer.parseInt(data.get(index)) < data.size())){
String temp = data.get(index);
data.set(index, temp + "R");
stages.add(copy(data));
data.set(index, temp);
success = solveH(index + Integer.parseInt(data.get(index)));
stages.remove(stages.size()-1);
}
if(!success && (index - Integer.parseInt(data.get(index)) > 0)){
String temp = data.get(index);
data.set(index, temp + "L");
stages.add(copy(data));
data.set(index, temp);
success = solveH(index - Integer.parseInt(data.get(index)));
stages.remove(stages.size()-1);
}
return false;
}
My approach would be: At every field visit left, visit right (in fact - branch at every step).
Ok - first, like you did: look if we reached the target.
Then, save the value at that index for stepping left and right and then set the value to 0 as mark for 'visited'. You're anyhow frozen on a zero field and the check for reaching the target is based on the index = last index.
Instead of strings and parsing, just store plain numbers in an array.
Code:
public class StepArray {
// using static fields/methods is a bit ugly. Maybe improve main,
// to allow passing an array to visit dynamically.
static int[] data = new int [] {2, 3, 1, 4, 0};
static int len = data.length;
public static boolean solveH (int index){
if (index == len - 1) {
System.out.println ("found at index " + index + "!");
return true;
}
// save the value before overwriting:
int step = data[index];
// already visited?
if (step == 0) return false;
// mark for later visitors as visited by setting to 0:
data[index] = 0;
if (index + step < len) {
System.out.print (" R:" + step);
solveH (index + step);
}
// no need to visit 0 again, which is always the starting point
if (index - step > 0) {
System.out.print (" L:" + step);
solveH (index - step);
}
return false;
}
public static void main (String args[]) {
solveH (0);
}
}
Here is the improved version for more fun and flexibility (the core algorithm only has cosmetic changes):
import java.util.Random;
public class ArraySteps {
int[] data;
int len;
public ArraySteps (int [] values) {
data = values;
len = data.length;
solveH (0);
System.out.println ();
}
boolean solveH (int index) {
if (index == len - 1) {
System.out.println (" found at index " + index + "!");
return true;
}
int step = data[index];
// already visited
if (step == 0) return false;
// mark for later visitors as visited by setting to 0:
data[index] = 0;
boolean r = false, l = false;
if (index + step < len) {
System.out.print (" R:" + step);
r = solveH (index + step);
}
if (index - step > 0) {
System.out.print (" L:" + step);
l = solveH (index - step);
}
if (r || l) return true;
System.out.println (" dead end.");
return false;
}
public static void main (String args[]) {
// default, no args:
int [] param;
System.out.println ("args.length: " + args.length);
if (args.length == 0)
{
System.out.println ("default: ");
param = new int [] {2, 3, 1, 4, 0};
}
// one arg: Generate count N random values
else if (args.length == 1)
{
System.out.println ("Random: ");
int anz = Integer.parseInt (args[0]);
Random r = new Random ();
param = new int [anz];
for (int i = 0; i < anz - 1; ++i) {
param [i] = r.nextInt (Math.min (anz/2, 9)) + 1;
}
param[anz-1] = 0;
}
else {
System.out.println ("User defined: ");
param = new int [args.length + 1];
for (int i = 0; i < args.length; ++i)
{
param[i] = Integer.parseInt (args[i]);
}
param [args.length] = 0;
}
show (param);
new ArraySteps (param);
}
private static void show (int[] ls)
{
for (int i: ls)
System.out.print (i + " ");
System.out.println ();
}
}
I'm trying to implement a Deque utilizing a circular array that extends when the array gets full. However, I am getting an IndexOutOfBoundsException. I think my issue is with the insertLast method. I've analyzed my code thoroughly and I cannot see what I am doing wrong. Any assistance would be greatly appreciated.
public class CircularExtendedArrayDeque
{
public static final int INIT_CAPACITY = 4; // initial array capacity
protected int capacity; // current capacity of the array
protected int front; // index of the front element
protected int rear; // index of the rear element
protected int[] A; // array deque
public CircularExtendedArrayDeque( ) // constructor method
{
A = new int[ INIT_CAPACITY ];
capacity = INIT_CAPACITY;
front = rear = 0;
}
/**
* Print the content of the deque
*
*/
public void printDeque( )
{
for ( int i = front; i != rear; i = (i+1) % capacity )
System.out.print( A[i] + " " );
System.out.println();
}
/**
* Print the content of the whole array
*
*/
public void printArray( )
{
for ( int i = 0; i < capacity; i++ )
System.out.print( A[i] + " " );
System.out.println();
}
// ***************************************
// DO NOT MODIFY THE CODE ABOVE THIS LINE.
// ADD YOUR CODE BELOW THIS LINE.
//
// ***************************************
/**
* Returns the number of items in this collection.
* #return the number of items in this collection.
*/
public int size()
{
// COMPLETE THIS METHOD
return (capacity - front + rear) % capacity;
}
/**
* Returns true if this collection is empty.
* #return true if this collection is empty.
*/
public boolean isEmpty()
{
// COMPLETE THIS METHOD
return front == rear;
}
/**
* Returns the first element of the deque
*
*/
public int getFirst() throws EmptyDequeException
{
// COMPLETE THIS METHOD
if(isEmpty()){
throw new EmptyDequeException("Deque is empty.");
}
return A[front % capacity];
}
/**
* Returns the last element of the deque
*
*/
public int getLast() throws EmptyDequeException
{
// COMPLETE THIS METHOD
if(isEmpty()){
throw new EmptyDequeException("Deque is empty.");
}
return A[(front + rear - 1) % capacity];
}
/**
* Inserts e at the beginning (as the first element) of the deque
*
*/
public void insertFirst( int e )
{
// COMPLETE THIS METHOD
rear++;
if(size() == capacity - 1){
capacity *= 2;
}
int[] B = new int[capacity];
for(int i = 0; i < size(); i++){
B[i] = A[i];
}
A = B;
for(int i = size(); i >= front; i--){
A[i+1] = A[i];
}
A[front] = e;
front = front % capacity;
System.out.println("Front: " + front + " & Rear:" + rear);
}
/**
* Inserts e at the end (as the last element) of the deque
*
*/
public void insertLast( int e )
{
// COMPLETE THIS METHOD
if(size() == capacity - 1){
capacity *= 2;
int[] B = new int[capacity];
for ( int i = front; i != rear; i = (i+1) % capacity )
B[i] = A[i];
/*
for(int i = 0; i < size(); i++){
B[i] = A[i];
}
*/
A = B;
A[rear++] = e;
}
else{
//System.out.println("Array Size = " + A.length);
A[rear++] = e;
}
System.out.println("Front: " + front + " & Rear:" + rear);
System.out.println("msg...size=" + size());
}
/**
* Removes and returns the first element of the deque
*
*/
public int removeFirst( ) throws EmptyDequeException
{
// COMPLETE THIS METHOD
int result = A[front];
A[front] = 0;
front = (front+1)%capacity;
if(isEmpty()){
throw new EmptyDequeException("Deque is empty.");
}
else if(capacity >= 4){
if(size() < capacity/2){
//System.out.println("msg...size = " + size());
capacity /= 2;
int[] B = new int[capacity];
int counter=0;
for(int i = front; i < front+size(); i++){
B[counter] = A[i%(capacity*2)];
counter++;
}
A = B;
front = 0;
rear = size()-1;
}
}
return result;
}
/**
* Removes and returns the last element of the deque
*
*/
public int removeLast( ) throws EmptyDequeException
{
// COMPLETE THIS METHOD
if(isEmpty()){
throw new EmptyDequeException("Deque is empty.");
}
else if(capacity >= 4){
if(size() < capacity/2){
System.out.println("Capacity shrinking...");
int[] B = new int[capacity/2];
for(int i = 0; i < capacity/2; i++){
B[i] = A[i];
}
A = B;
}
}
int temp = A[rear - 1];
A[rear] = 0;
rear = (rear - 1) % capacity;
return temp;
}
} // end class
Here's the main class:
public class CircularExtendedArrayMain {
public static void main(String[] args) {
CircularExtendedArrayDeque q = new CircularExtendedArrayDeque();
q.insertFirst(112);
q.insertFirst(105);
q.printDeque();
System.out.println("last element is = " + q.getLast());
System.out.println("first element is = " + q.getFirst());
q.insertLast(5501);
q.printDeque();
q.insertLast(778);
q.insertLast(37);
q.printDeque();
System.out.println("first element is = " + q.getFirst());
System.out.println("last element is = " + q.getLast());
System.out.println("remove last = " + q.removeLast());
q.printDeque();
System.out.println("remove last = " + q.removeLast());
System.out.println("remove first = " + q.removeFirst());
q.printDeque();
System.out.println("remove first = " + q.removeFirst());
System.out.println("remove first = " + q.removeFirst());
// q is now empty.
int i, k;
for( i = 1; i <= 60; i ++ )
q.insertLast(i*i);
q.printDeque(); // 60 elements in q
for( i = 1; i <= 58; i++ )
k = q.removeFirst();
q.printDeque(); // two elements are left
}
}
Here's my output:
Front: 0 & Rear:1
Front: 0 & Rear:2
105 112
last element is = 112
first element is = 105
Front: 0 & Rear:3
msg...size=3
105 112 5501
Front: 0 & Rear:4
msg...size=4
Front: 0 & Rear:5
msg...size=5
105 112 5501 778 37
first element is = 105
last element is = 37
remove last = 37
105 112 5501 778
remove last = 778
remove first = 105
112 5501
remove first = 112
remove first = 5501
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at CircularExtendedArrayDeque.insertLast(CircularExtendedArrayDeque.java:161)
at CircularExtendedArrayMain.main(CircularExtendedArrayMain.java:34)
public void insertLast(int e) {
if(size() == capacity - 1) {
capacity= capacity*2;
}
int[] B = new int[capacity];
for(int i = 0; i < size(); i++) {
B[i] = A[i];
}
A = B;
A[rear] = e;
rear = (rear + 1) % capacity;
}
This is my insertLast(). Guess this works. Good luck with cse2011.. !!
This is for a data structures class in java, and I need to create a graph that reads text input, converts this information into a graph, and from there print the adjacency list and print a max spanning tree, which I have done. However, the final aspect is to
The full routing table that your program must produce will have for every pair [i,j] (i != j) of computers in the network, the first computer on an optimum route from i to j. If i and j have a direct connection, then j will be the result (table entry) for that route (pair [i,j]). If the optimum route from i to j is i -> a -> b -> j, then a will be the result (table entry) for that route. One could then construct the route by looking at the value from [i,j] (=a), then [a,j] (=b), then [b,j] (=j).
So basically Dijksta's algorithm. However, I cannot use any Java APIs that deal with graphs (all others are allowed). So far I have
import java.util.ArrayList;
//import java.util.Stack;
public class Graph2 {
ArrayList<Vertex> vert = new ArrayList<Vertex>();
private static int counter = 0;
private int edges;
private Edge[] allEdges = new Edge[50];
private class Vertex{
String ip;
private int id;
ArrayList<Edge> nb = new ArrayList<Edge>();
/**
* Constructor for Vertex
* #param String of IP
*/
public Vertex(String s){
ip = s;
id = counter;
counter++;
}
/**
* Gets the ID of a vertex
* #return unique ID
*/
public int getId(){
return id;
}
/*
public boolean isSame(Vertex v){
if(this.ip.equals(v.getIp()))
return true;
else
return false;
}
*/
/**
* Gets the IP of a vertex
* #return the IP of the vertex
*/
public String getIp(){
return this.ip;
}
/**
* Adds an edge to nb
* #param edge to be added
*/
public void addList(Edge e){
nb.add(e);
}
/**
* Determines if an edge exists
* #param edge to be checked
* #return true if exists, false if not
*/
public boolean exists(Edge e){
if(nb.indexOf(e) != -1){
return true;
}
else
return false;
}
/**
* Gets the size of an edge
* #return size of edge
*/
public int edgeSize(){
return nb.size();
}
/**
* Gets the edges
* #return String of edges
*/
public String getEdges(){
String all = "";
Edge e;
for(int i = 0; i < nb.size(); i++){
e = nb.get(i);
int ti = this.getId();
int fin = e.getFinish().getId();
if(ti == fin)
all += e.getStart().getId() + " ";
else
all += e.getFinish().getId() + " ";
}
return all;
}
/**
* Overrides toString method
* #return ID and IP of vertex
*/
public String toString(){
return id + " " + " " + ip;
}
}
private class Edge{
int weight;
Vertex finish;
Vertex start;
/**
* Constructor of Edge
* #param vertex 1, start vertex
* #param vertex 2, endpoint vertex
* #param weight of edge
*/
public Edge(Vertex v, Vertex v2, int w){
start = v;
finish = v2;
weight = w;
}
/**
* Gets the start of an edge
* #return edge start
*/
public Vertex getStart(){
return start;
}
/**
* Gets the endpoint of an edge
* #return endpoint of edge
*/
public Vertex getFinish(){
return finish;
}
/**
* Gets the weight of an edge
* #return weight of edge
*/
public int getWeight(){
return weight;
}
/**
* Overrides toString
* #return start of edge and endpoint of edge
*/
public String toString(){
return start + " " + finish;
}
}
/**
* Adds an edge to 2 verticies
* #param s, starting vertex IP
* #param t, enpoint vertex IP
* #param w, weight of edge
*/
public void add(String s, String t, int w){
Vertex v3, v4;
v3 = exists(new Vertex(s));
v4 = exists(new Vertex(t));
Edge e;
if(v3 == null && v4 == null){
v3 = new Vertex(s);
v4 = new Vertex(t);
vert.add(v3);
vert.add(v4);
e = new Edge(v3, v4, w);
v3.addList(e);
v4.addList(e);
}
else if(v3 != null && v4 == null){
counter--;
v4 = new Vertex(t);
vert.add(v4);
e = new Edge(v3, v4, w);
v3.addList(e);
v4.addList(e);
}
else if(v3 == null && v4 !=null){
counter--;
v3 = new Vertex(s);
vert.add(v3);
e = new Edge(v3, v4, w);
v3.addList(e);
v4.addList(e);
}
else{
counter -= 2;
e = new Edge(v3, v4, w);
if(!v3.exists(e)){
v3.addList(e);
v4.addList(e);
}
}
allEdges[edges] = e;
edges++;
}
/**
* Determines if an edge already exists
* #param vertex to be checked
* #return vertex if exists, null if not
*/
public Vertex exists(Vertex v){
for(int i = 0; i < vert.size(); i++){
if(v.getIp().equals(vert.get(i).getIp()))
return vert.get(i);
}
counter--;
return null;
}
/**
* Puts vert ArrayList into an array
* #return String array of vert
*/
public String[] toArray(){
String[] all = new String[vert.size()];
for(int i = 0; i < vert.size(); i++){
all[i] = vert.get(i).toString();
}
return all;
}
/**
* Determines if a vertex is adjacent to another vertex
* #return String array of adjacent verticies
*/
public String[] adjaceny(){
String[] all = new String[vert.size()];
Vertex v1;
for(int i = 0; i < vert.size(); i++){
v1 = vert.get(i);
all[i] = v1.getEdges();
}
return all;
}
/**
* Determines which vertex is in which cluster
* #return String array of clusters
*/
/*
public String[] cluster(){
Vertex[] temp = (Vertex[]) vert.toArray();
Sorter sort = new Sorter();
sort.heapsort(temp);
String[] cluster = new String[vert.size()];
int[] verts = new int[vert.size()];
for(int i = 0; i < vert.size();i++)
verts[i] = i;
return null;
}
*/
/**
* Gets the max spanning tree of the graph
* #return spanning tree of graph
*/
public String[] maxTree(){
sortEdges();
String[] max = new String[vert.size() -1];
Edge e;
for(int i = 0; i < vert.size()-1; i++){
e = allEdges[i];
max[i] = e.getStart().getId() + ", " + e.getFinish().getId() + ", " + e.getWeight();
}
return max;
}
/**
* Sorts edges by max weight
*/
private void sortEdges(){
Sorter sort = new Sorter();
sort.heapsort(allEdges);
}
public class Sorter{
/**
* Heapsorts the Object array
* #param Object array to be sorted
*/
public void heapsort(Object[] a)
{
for(int i = edges / 2; i >= 0; i-- ) /* buildHeap */
percDown(a, i, edges);
for( int i = edges - 1; i > 0; i-- )
{
swapReferences( a, 0, i ); /* deleteMax */
percDown( a, 0, i );
}
}
/**
* Performs swapping of elements
* #param Object array
* #param index1
* #param index2
*/
public void swapReferences(Object[] a, int index1, int index2 )
{
if(a[0] instanceof Edge){
Edge tmp = (Edge)a[index1];
a[index1] = a[index2];
a[index2] = tmp;
}
else if(a[0] instanceof Vertex){
Vertex temp = (Vertex)a[index1];
a[index1] = a[index2];
a[index2] = temp;
}
}
/**
* Internal method for heapsort.
* #param i the index of an item in the heap.
* #return the index of the left child.
*/
private int leftChild(int i)
{
return 2 * i + 1;
}
/**
* Internal method for heapsort that is used in
* deleteMax and buildHeap.
* #param a an array of Comparable items.
* #int i the position from which to percolate down.
* #int n the logical size of the binary heap.
*/
private void percDown(Object[] a, int i, int n)
{
int child;
if(a[0] instanceof Edge){
Edge tmp;
for( tmp = (Edge) a[i]; leftChild(i) < n; i = child )
{
child = leftChild(i);
if( child != n - 1 && ((Edge)a[child]).getWeight() - ((Edge)(a[child + 1])).getWeight() > 0 )
child++;
if(tmp.getWeight() - ((Edge)a[child]).getWeight() > 0 )
a[i] = a[child];
else
break;
}
a[i] = tmp;
}
else if(a[0] instanceof Vertex){
Vertex temp;
for(temp = (Vertex) a[i]; leftChild(i) < n; i = child){
child = leftChild(i);
if(child != n-1 && ((Vertex)a[child]).edgeSize() - ((Vertex)a[child+1]).edgeSize() > 0)
child++;
if(temp.edgeSize() - ((Vertex)a[child]).edgeSize() > 0)
a[i] = a[child];
else
break;
}
a[i] = temp;
}
}
}
}
}
With a main consisting of:
import java.util.*;
import java.io.*;
public class pg6main {
public static void main(String[] args) throws IOException{
String filename;
String first, second;
int weight;
Graph2 graph = new Graph2();
Scanner kb = new Scanner(System.in);
boolean go = false;
Scanner infile = null;
PrintWriter outfile = new PrintWriter(new FileWriter("results.txt"));
do{
try{
System.out.print("Enter a file to read from: ");
filename = kb.nextLine();
infile = new Scanner(new FileReader(filename));
}catch(Exception e){
go = true;
System.out.println("file doesn't exist");
}
}while(go);
while(infile.hasNext()){
first = infile.next().trim();
second = infile.next().trim();
weight = Integer.parseInt(infile.nextLine().trim());
graph.add(first, second, weight);
}
outfile.println("IP and their unique IDs: ");
String[] a = graph.toArray();
for(int i = 0; i < a.length; i++)
outfile.println(a[i]);
outfile.println("Adjaceny List: ");
String[] adj = graph.adjaceny();
for(int j = 0; j < adj.length; j++)
outfile.println(j + ": " + adj[j]);
outfile.println("Max spanning tree: ");
String[] max = graph.maxTree();
for(int k = 0; k < max.length; k++)
outfile.println("(" + max[k] + ") ");
/*
//Attempting to do clusters based on length of string of neighbors, does not work
for(int x = 0; x < adj.length; x++){
if(adj[x].length() > adj[x+1].length()){
outfile.println("WHAT I DID: " + adj[x]);
}
else if(adj[x].length() == adj[x+1].length()){
adj[x] = adj[x+1];
outfile.println("WHAT I DID: " + adj[x]);
}
else if(adj[x].length() < adj[x+1].length()){
adj[x] = adj[x+1];
outfile.println("WHAT I DID: " + adj[x]);
}
*/
/*//Attempted to do neighbors slighly different way
String[] cluster = graph.cluster();
for(int x = 0; x < cluster.length; x++){
if(cluster[x] != null)
outfile.println(cluster[x]);
*/
outfile.close();
}//end main
}//end pg6main
I was wondering if anyone could help, I've never worked with graphs until today. So far, I believe my code works as intended, but there could potentially be some errors with my logic. Basically my issue is most of the implementations of Dijkstra's have parameters as a graph, and I am unsure if this is actually how I should be doing this. Thanks for any help.
You should use the Floyd algorithm instead, it gives you a full table of shortest routes, exactly as you described in the requirements.
As you can see from the pseudocode, it's really simple and all you need is to create a two-dimensional array and initialise it with the edges. (So basically it's your weighted adjacency table.)