How to remove element with a dynamic array? - java

I am currently working my assignment which is to make simulation of queue code, one of the methods is
Dequeue() to return the head of queue and then removes it, my teacher advised me with my dequeue is similar to my enqueue() method, as you can observe I already wrote a code and hoping someone could advise me how to terminate it.
import java.util.NoSuchElementException;
public class MyQueue implements IntQueue {
int[] heltal;
public MyQueue() {
heltal = new int[0];
}
public void enqueue(int tal) {
int[] temp = new int[heltal.length + 1];
for (int x = 0; x < heltal.length; x++) {
heltal[x] = temp[x] + tal;
}
heltal = temp;
for (int i = 0; i < heltal.length; i++) {
heltal[i] = tal;
}
}
public int dequeue() throws NoSuchElementException {
if (empty()) {
throw new NoSuchElementException("The Queue is empty, there is nothing to dequeue");
} else {
int[] temp = new int[heltal.length - 1];
for (int i = 0; i < heltal.length; i++) {
heltal[i] = temp[i];
}
heltal = temp;
for (int i = 0; i < heltal.length; i++) {
}
}
return heltal[0];
}
#Override
public int peek() throws NoSuchElementException {
if (empty()) {
throw new NoSuchElementException("The Queue is empty");
} else {
return heltal[0];
}
}
#Override
public boolean empty() {
return heltal.length == 0;
}
}
My dequeue should function like this
[4] [3] [5] [7] before dequeue 4 indexes
[3] [5] [7] after dequeue 3 indexes

I looked at your enqueue and commented:
public void enqueue(int tal) {
int[] temp = new int[heltal.length + 1];
for (int x = 0; x < heltal.length; x++) { //this goes through all the elemeents of heltal
heltal[x] = temp[x] + tal; //this would set 0 from the new temp + tal to all values
}
heltal = temp; // here you write the temp array over the heltal, which was zero
for (int i = 0; i < heltal.length; i++) {
heltal[i] = tal; //here you write heltal all over it once again
}
}

Related

Can anyone please explain how can I implement my code to add an element to the back of a circular arraydeque? [duplicate]

I am following an online example and learning "Circular Deque implementation in Java using array". Here is the online resource that I am following:
Circular Queue Implementation
I have an array based deque class which has final capacity of 5. Now if the array is full then I can have the methods create a temporary array of all the objects and then copy all the objects of temporary array back to "object[] arr". I have been at it for some time now but have not been able to get it going. I would appreciate if someone can help me understand the process here please. I have following class methods:
insertAtFront()
insertAtLast()
size()
isEmpty()
toString()
Here is my code:
public class ArrayDeque {
private static final int INIT_CAPACITY = 5;
private int front;
private int rear;
private Object[] arr;
public ArrayDeque(){
arr = new Object[ INIT_CAPACITY ];
front = 0;
rear = 0;
}
public void insertAtFirst(Object item){
if(size() >= arr.length){
Object[] tmp = new Object[arr.length + INIT_CAPACITY];
for(int i = 0; i < size(); ++i)
tmp[i] = arr[i];
arr = tmp;
}
arr[front] = item;
++front;
}
public void insertAtLast(Object item){
if(size() >= arr.length){
Object[] tmp = new Object[arr.length + INIT_CAPACITY];
for(int i = 0; i < size(); ++i)
tmp[i] = arr[i];
arr = tmp;
}
arr[rear] = item;
++rear;
}
public int size(){
return (rear - front);
}
public boolean isEmpty(){
return (front == rear);
}
public String toString(){
String s = "";
for(int i = 0; i < size(); ++i)
s += arr[i] + "\n";
return s;
}
}//CLASS
Try the below code, i changed the logic a bit by keeping track of how much the array is filled up. Your main problem is with the size() function, which is giving wrong indications. Some optimization is pending for i see some nulls in the results.
public class ArrayDeque {
public static void main(String[] args) {
ArrayDeque t = new ArrayDeque ();
t.insertAtFirst("1");
t.insertAtFirst("2");
t.insertAtFirst("3");
t.insertAtFirst("4");
t.insertAtFirst("5");
t.insertAtFirst("6");
t.insertAtFirst("7");
t.insertAtFirst("8");
t.insertAtFirst("9");
t.insertAtFirst("10");
t.insertAtFirst("11");
t.insertAtFirst("12");
t.insertAtFirst("13");
t.insertAtFirst("14");
System.out.println("After first--"+t.toString());
t.insertAtLast("1");
t.insertAtLast("2");
t.insertAtLast("3");
t.insertAtLast("4");
t.insertAtLast("5");
t.insertAtLast("6");
t.insertAtLast("7");
t.insertAtLast("8");
t.insertAtLast("9");
t.insertAtLast("10");
t.insertAtLast("11");
t.insertAtLast("12");
t.insertAtLast("13");
t.insertAtLast("14");
System.out.println("After last--"+t.toString());
}
private static final int INIT_CAPACITY = 5;
private int NEW_CAPACITY;
private int ARRAY_SIZE;
private Object[] arr;
public TestClass(){
arr = new Object[ INIT_CAPACITY ];
NEW_CAPACITY = INIT_CAPACITY;
ARRAY_SIZE = 0;
}
public void insertAtFirst(Object item){
if(ARRAY_SIZE == 0)
{
arr[0] = item;
ARRAY_SIZE++;
}
else if(ARRAY_SIZE+1 < arr.length)
{
Object[] tmp = new Object[NEW_CAPACITY];
for(int i = 1; i < arr.length; ++i)
tmp[i] = (String)arr[i-1];
arr = tmp;
arr[0] = item;
ARRAY_SIZE++;
}
else if(ARRAY_SIZE+1 >= arr.length)
{
NEW_CAPACITY = NEW_CAPACITY+INIT_CAPACITY;
Object[] tmp = new Object[NEW_CAPACITY];
for(int i = 1; i < arr.length; ++i)
tmp[i] = (String)arr[i-1];
arr = tmp;
arr[0] = item;
ARRAY_SIZE++;
}
}
public void insertAtLast(Object item){
if(ARRAY_SIZE == 0)
{
arr[0] = item;
ARRAY_SIZE++;
}
else if(ARRAY_SIZE+1 < arr.length)
{
arr[ARRAY_SIZE] = item;
ARRAY_SIZE++;
}
else if(ARRAY_SIZE+1 >= arr.length)
{
NEW_CAPACITY = NEW_CAPACITY+INIT_CAPACITY;
Object[] tmp = new Object[NEW_CAPACITY];
for(int i = 0; i < arr.length; ++i)
tmp[i] = (String)arr[i];
arr = tmp;
arr[ARRAY_SIZE] = item;
ARRAY_SIZE++;
}
}
public int size(){
return ARRAY_SIZE;
}
public boolean isEmpty(){
return (ARRAY_SIZE == 0);
}
public String toString(){
String s = "";
for(int i = 0; i < arr.length; ++i)
s += arr[i] + "\t";
return s;
}
}

Jumping Frogs (Frog Puzzle) using DFS

I have been trying to implement the Jumping Frogs puzzle (here is a good link to what I mean http://britton.disted.camosun.bc.ca/frog_puzzle.htm) in Java with the goal being to print out the steps from the beginning to the right ending (successfull solution).
I am using an Arraylist to write the nodes I have already visited and a stack to get back to parent nodes if necessary.
However, the program prints odd things, although the algorithm seems to be working fine...any ideas why is this happening and how can I fix this?
public class JumpingFrogs {
public static int indexOfZero(int arr[]){
int index=0;
for (int i=0; i <arr.length; i++){
if (arr[i]==0) index = i;
}
return index;
}
public static int[] swap(int[] arr, int ind1, int ind2){
int temp = arr[ind1];
arr[ind1] = arr[ind2];
arr[ind2] = temp;
return arr;
}
public static int[] makeCopy(int[] arr){
int[] copy = new int[arr.length];
for (int i = 0; i < copy.length; i++){
copy[i] = arr[i];
}
return copy;
}
public static boolean isContained(int[] arr, ArrayList arrayList){
if(arrayList.isEmpty()) return false;
for (Object arrayList1 : arrayList) {
if (Arrays.equals(arr, (int[]) arrayList1)) {
return true;
}
}
return false;
}
public static void main(String[] args) {
System.out.print("Input number of frogs on each side: ");
Scanner input = new Scanner(System.in);
int frogNumber = input.nextInt();
int[] root = new int[2*frogNumber + 1];
int[] solution = new int[2*frogNumber + 1];
for (int i = 0; i < 2*frogNumber + 1; i++){
if (i < frogNumber){
root[i] = 1;
solution[i]=2;
}
else{
if (i == frogNumber){
root[i] = 0;
solution[i] = 0;
}
else{
root[i] = 2;
solution[i] = 1;
}
}
}
Stack stack = new Stack();
ArrayList visitedNodes = new ArrayList();
stack.push(makeCopy(root));
do{
int i0=indexOfZero(root);
if((i0 >= 2)&&(root[i0-2] == 1)&&(!isContained((swap(makeCopy(root), i0 - 2, i0)), visitedNodes))){
swap(root, i0 - 2, i0);
stack.push(makeCopy(root));
visitedNodes.add(makeCopy(root));
continue;
}
if((i0 >= 1)&&(root[i0-1] == 1)&&(!isContained((swap(makeCopy(root), i0 - 1, i0)), visitedNodes))){
swap(root, i0 - 1, i0);
stack.push(makeCopy(root));
visitedNodes.add(makeCopy(root));
continue;
}
if((i0 < root.length - 1)&&(root[i0+1] == 2)&&(!isContained((swap(makeCopy(root), i0+1, i0)), visitedNodes))){
swap(root, i0 + 1, i0);
stack.push(makeCopy(root));
visitedNodes.add(makeCopy(root));
continue;
}
if((i0 < root.length - 2)&&(root[i0+2] == 2)&&(!isContained((swap(makeCopy(root), i0+2, i0)), visitedNodes))){
swap(root, i0 + 2, i0);
stack.push(makeCopy(root));
visitedNodes.add(makeCopy(root));
continue;
}
stack.pop();
root=(int[]) stack.peek();
}
while(!Arrays.equals(root, solution));
Stack path = new Stack();
while(!stack.empty()){
path.push(stack.pop());
}
while(!path.empty()){
int[] step = (int[]) path.pop();
for (int p = 0; p < step.length; p++){
System.out.print(step[p]);
}
System.out.println();
}
System.out.println("The program has ended successfully!");
}
}
try clone root like,
do{
proccessing
.
.
.
.
.
.
stack.pop();
root=(int[]) stack.peek();
//add
root = root.clone();
}

Problems with deepCopy/cloning of 4D array

I am trying to deep copy a 4d int array as the solution of my algorithm. Unfortunately, when I call that solution at the end of my program, it is not the one that was supposed to be deepcopied. It is also neither the first nor the last created solution. I figure the problem must lie in deepCopy as cloning the same solution in a 1d array works fine.
I am trying to deepcopy w[][][][]:
public Object clone()
{
MySolution copy = (MySolution)super.clone();
copy.w = deepCopyOf(w);
copy.wtour = (int[])this.wtour.clone();
return copy;
} // end clone
#SuppressWarnings("unchecked")
public static <T> T[] deepCopyOf(T[] array) {
if (0 >= array.length) return array;
return (T[]) deepCopyOf(
array,
Array.newInstance(array[0].getClass(), array.length),
0);
}
private static Object deepCopyOf(Object array, Object copiedArray, int index) {
if (index >= Array.getLength(array)) return copiedArray;
Object element = Array.get(array, index);
if (element.getClass().isArray()) {
Array.set(copiedArray, index, deepCopyOf(
element,
Array.newInstance(
element.getClass().getComponentType(),
Array.getLength(element)),
0));
}
else {
Array.set(copiedArray, index, element);
}
return deepCopyOf(array, copiedArray, ++index);
}
I am using the openTS Tabu Search framework by Harder and the fact that the wtour array gets copied just fine shows me that there must be something wrong with the deepcopy method for w[][][][]
EDIT: novic3 assumed that I have to iterate over the different array levels. I tried doing the following which is a little bit different in its approach. Unfortunately, it still doesn't work.
public static int[][][][] deepCopy2(int[][][][] original) {
if (original == null) {
return null;
}
final int[][][][] result = new int[original.length][original[0].length][original.length+1][];
for (int i = 0; i < original.length; i++) {
for (int j = 0; j < original.length; j++) {
for (int q= 0; q <= original.length; q++) {
result[i][j][q] = Arrays.copyOf(original[i][j][q], original[i][j][q].length);
// For Java versions prior to Java 6 use the next:
//System.arraycopy(original[i], 0, result[i], 0, original[i].length);
}
}
}
return result;
}
This should work:
public int[] deepCopy(int[] w) {
int[] ans = new int[w.length];
for (int i = 0; i < w.length; i++) {
ans[i] = w[i];
}
return ans;
}
public int[][] deepCopy2(int[][] w) {
int[][] ans = new int[w.length][];
for (int i = 0; i < w.length; i++) {
ans[i] = deepCopy(w[i]);
}
return ans;
}
public int[][][] deepCopy3(int[][][] w) {
int[][][] ans = new int[w.length][][];
for (int i = 0; i < w.length; i++) {
ans[i] = deepCopy2(w[i]);
}
return ans;
}
public int[][][][] deepCopy4(int[][][][] w) {
int[][][][] ans = new int[w.length][][][];
for (int i = 0; i < w.length; i++) {
ans[i] = deepCopy3(w[i]);
}
return ans;
}
To use, call deepCopy4(w)

Shifting an array after removing a value (Java)

I made a program that makes an array of random ints and doubles in size if the user tries to add an int. Example: 1|2|3|4 if they were to add another int it would look like 1|2|3|4|5|0|0|0. I have made a method to add an int which works but now I am trying to make methods that remove one of a certain int and another that removes all of a certain int. for example removeInt(3) would give me 1|2|0|4|5|0|0|0. I have the first part working so that it shifts the zero to the end like this 1|2|4|5|0|0|0|0 but cannot get it to work for more than one of the same value. Any suggestions?
// ****************************************************************
// IntegerList.java
//
// Define an IntegerList class with methods to create & fill
// a list of integers.
//
// ****************************************************************
public class IntegerList
{
int[] list; //values in the list
//-------------------------------------------------------
//create a list of the given size
//-------------------------------------------------------
public IntegerList(int size)
{
list = new int[size];
}
//-------------------------------------------------------
//fill array with integers between 1 and 100, inclusive
//-------------------------------------------------------
public void randomize()
{
for (int i=0; i<list.length; i++)
list[i] = (int)(Math.random() * 100) + 1;
}
//-------------------------------------------==----------
//print array elements with indices
//-------------------------------------------------------
public void print()
{
for (int i=0; i<list.length; i++)
System.out.println(i + ":\t" + list[i]);
}
public void addElement(int newVal){
boolean full = true;
System.out.println(list.length);
int position = 0;
int place;
while(position < list.length){
System.out.println("HERE");
if(list[position]==0){
System.out.println("here");
full = false;
place = position;
System.out.println(place);
}
position = position+1;
}
if(full == true){
list = increaseSize(list);
System.out.println("L"+list.length);
full = false;
}
for(int i = 0;i<list.length;i++){
if(list[i]==0){
if(i<position){
position = i;
System.out.println(list.length);
}
}
}
list[position] = newVal;
}
public void removeFirst(int newVal){
int position = 0;
boolean removed = false;
for(int i = 0; i<list.length;i++){
if(list[i] == newVal){
list[i]=0;
position = i;
removed = true;
break;
}
}
if(removed==true){
for(int i = position;i<list.length;i++){
if(i!=list.length-1){
list[i]=list[i+1];
}
}
list[list.length-1]= 0;
}
}
public void removeAll(int newVal){
int position = 0;
boolean removed = false;
for(int i = 0; i<list.length;i++){
if(list[i] == newVal){
list[i]=0;
position = i;
removed = true;
}
}
if(removed==true){
for(int i = 0;i<list.length;i++){
if(i!=list.length-1 && list[i+1]==newVal){
list[i]=0;
}
if(list[i]==newVal){
list[i]=0;
}
}
}
}
public static int[] increaseSize(int[] x){
int newLength = x.length *2;
int[] newx = new int[newLength];
for(int i = 0; i<x.length; i++){
newx[i] = x[i];
}
return newx;
}
public static int[] halfSize(int[] x){
int[] newx = new int[x.length / 2];
for(int i = 0; i<x.length; i++){
newx[i] = x[i];
}
return newx;
}
}
I believe there's an easier way to implement your removeAll method. Move 2 (rather than 1) indices through your array constantly shifting the values over the items you are removing;
int dest = 0;
int source = 0;
while (source < array.length) {
if (array[dest] != valueToRemove)
dest++;
array[dest] = array[source++];
}
while (dest < array.length) {
array[dest++] = 0;
}
I executed your code and found out that the problem is in this piece, under removeAll()...
if(removed){
for(int i = 0;i<list.length;i++){
if(i!=list.length-1 && list[i+1]==newVal){
list[i]=0;
}
if(list[i]==newVal){
list[i]=0;
}
}
}
If you comment out and try once, you will see the removeAll() is working and your desired number is replaced with 0s. Now why you don't simply check your numbers and shift(sorting), if they are greater than 0 to the left?

I need help linking my stack Class into my TestBed class

import java.util.Random;
public class TestBed {
public static void main(String a[]) {
// creating the array
int[] array = new int[100];
Random random = new Random();
// changing the variable of my clone array for reference
int[] arr = cloneArray(array);
for (int i1 = 0; i1 < 100; i1++)
array[i1] = random.nextInt(100) + 1;
// print out of bubble sort before and after the sort
System.out
.println("***********************Bubble Sort ****************************");
arr = cloneArray(array);
System.out.println("Values Before the sort:\n");
printArray(arr);
System.out.println();
bubble_srt(arr);
System.out.print("Values after the sort:\n");
printArray(arr);
// print out of selection sort before and after the sort
System.out.println();
System.out
.println("********************Selection Sort*****************************");
System.out.println(" Selection Sort\n\n");
arr = cloneArray(array);
System.out.println("Values Before the sort:\n");
printArray(arr);
System.out.println();
selection_srt(arr);
System.out.print("Values after the sort:\n");
printArray(arr);
System.out.println();
Stack stack = new Stack();
}
public static int[] buildArray(int bound) {
return null;
}
// clone array as a data type
public static int[] cloneArray(int[] data) {
return (int[]) data.clone();
}
// print array as a data type
public static void printArray(int[] data) {
// while there are still numbers left in the array print out the next
// value
for (int i = 0; i < data.length; i++)
System.out.print(data[i] + " ");
}
// bubble syntax
public static void bubble_srt(int a[]) {
int t = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 1; j < (a.length - i); j++) {
if (a[j - 1] > a[j]) {
t = a[j - 1];
a[j - 1] = a[j];
a[j] = t;
}
}
}
}
// selection syntax
public static void selection_srt(int array[]) {
for (int x = 0; x < array.length; x++) {
int index_of_min = x;
for (int y = x; y < array.length; y++) {
if (array[index_of_min] > array[y]) {
index_of_min = y;
}
}
int temp = array[x];
array[x] = array[index_of_min];
array[index_of_min] = temp;
}
}
}
From here i have to link my stack class but i don't know how to get the 2 classes together correctly im new to programming and my school threw me into a java class that was to high for me and now im stuck 5 weeks in.
public class Stack {
Node top;
int size;
public Stack() {
top = null;
size = 0;
}
public int pop() {
if (top != null) {
int item = top.data;
top = top.next;
size--;
return item;
}
return -1;
}
public void push(int data) {
Node t = new Node(data);
t.next = this.top;
this.top = t;
size++;
}
public boolean isEmpty() {
return size <= 0;
}
public int getSize() {
return size;
}
public int peek() {
return top.data;
}
public void printStack() {
Node n = this.top;
int pos = this.getSize();
while (pos > 0) {
System.out.println("Position: " + pos + " Element: " + n.data);
if (pos > 0) {
n = n.next;
}
pos--;
}
}
}
class Node {
public int data;
public Node next;
Node(int d) {
data = d;
next = null;
}
public int getData() {
return data;`enter code here`
}`enter code here`
{
Stack s = new Stack();
s.push(9);
s.push(2);
s.push(7);
s.push(3);
s.push(6);
s.push(4);
s.push(5);
System.out.println("Size is: " + s.getSize());
// s.printStack();
int size = s.getSize();
for (int i = 0; i < size; i++) {
System.out.print(s.pop() + " ");
}
}
}
At the beginning of Stack class file, create a package name, eg:
package com.example.testcode;
Then in your TestBed class file, import your Stack class from the package, eg:
import com.example.testcode.Stack;

Categories