I am creating a class that has an array, and I want to implement methods add, remove, and replace.
But I don't want to use any built-in internals.
public class MySet {
public int set[];
private int size = 0;
public MySet(int size) {
this.set = new int[size];
}
public boolean add(int item) {
for (int i = 0; i < this.size(); i++) {
if (this.set[i] != 0) {
// add to array
}
}
this.size++;
return true;
}
public int size()
{
return this.size;
}
}
When you initialize an array with a fixed size in Java, each item is equal to 0. The part with if this.set[i] != 0 is where I am stuck to add an item.
Should I use a while loop with pointers? Such as:
public boolean add(int item) {
int index = 0;
while (index <= this.size()) {
if (this.set[index] != 0 || index <= ) {
// increase pointer
index++;
}
this.set[index] = item;
}
But if I have an array such as [7, 2, 0 , 1] in the list, it won't get the last item in the loop, which I need.
So, how is this usually done?
You should keep the current index for the size of populated elements which looks like you do. When you add the set[size]= item and increment size. Once size hits the preallocated size of your array you need to create a new array with increased size (can pick double the size for example) and copy old array to the new one.
Related
I am learning java right now.
I have a class.
public static final int INIT_CAPACITY = 8; // 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 ArrayDeque( )
{
A = new int[ INIT_CAPACITY ];
capacity = INIT_CAPACITY;
front = rear = 0;
}
public int size( )
{
int countSize = 0;
for(int i = 0; i < capacity; i++)
{
if(A[i] != front && A[i] != rear)
{
countSize++;
}
}
// COMPLETE THIS METHOD
// Hint: size can be computed from capacity, front and rear.
return count; // replace this line with your code
}
I am trying to finish the method size. Does this make sense? Also, are there any good tips to check if I am on the right track?
My question might be too naive, my apology if it is. I just don't have lots of knowledge of programming.
Thank you
return count;
what is count? Do you mean countSize?
In either case your size method runs in O(N), if you had a million elements, you'd have to traverse the array a million times just to get the size. That isn't a good idea.
Instead, use the capacity private instance variable to denote the current size, like this:
public int size() {
return capacity;
}
and whenever you add an element, presumably in add(int x), increment capacity like: capacity++;
and whenever you delete an element, presumably in a remove(int x) or removeFirst()/removeLast(), decrement capacity like: capacity--;
and finally start capacity at 0 like: capacity = 0; inside your constructor, ArrayDeque().
I want to shift the elements in the array in a queue style.
I did this code:
public class Queue {
private int[] elements;
private int size;
public static final int DefCap = 8;
public Queue() {
this(DefCap);
}
public Queue(int capacity) {
elements = new int[capacity];
}
public int[] enqueue(int v) {
if (size >= elements.length) {
int[] a = new int[elements.length * 2];
System.arraycopy(elements, 0, a, 0, elements.length);
elements = a;
}
elements[size++] = v;
return elements;
}
public int dequeue() {
return elements[--size];
}
public boolean empty() {
return size == 0;
}
public int getSize() {
return size;
}
}
How can I shift the numbers in the array where the next number added pushes the last one?
because all it does now is removes the last one added (Stacking).
First, remember that it doesn't matter at all how you add or retrieve the elements as long as it appears that the operation reflects that of a queue (i.e. FIFO). The internals of your implementation are of no concern to the user(s). The easiest method (imo) is to add them normally to the end and "remove" them from the beginning.
When you add the new element, do it like you are already doing it.
When you remove the first element, do it virtually by using an index.
int nextIdx = 0; // initialize start of queue
...
...
public int next() {
if (nextIdx < elements.length) {
return elements[nextIdx--];
}
// indicate an error by throwing an exception
}
At some point you are going to want to reclaim the "non-existent" elements at the beginning of the queue and then reset nextIdx. You can do this when you need to resize the array. You can use System.arraycopy and make use of both the value of nextIdx and the new desired new size to resize the array and copy the remaining elements.
Note: In your enqueue method I'm not certain why you want to return the entire element array when you add an element. I would expect something like returning the element just added, a boolean indicating success, or not return anything.
I'm attempting to create a function that allows you to pass in a ArrayList and return the max element. I have been unable to figure out a correct solution because of the data type being passed in is not primitive. I've also tried converting the ArrayList to ArrayList without success. Here is my (incorrect) code thus far:
public static void maxArrayListValue(ArrayList<int[]> arrayList) {
int maxArrayListValue = arrayList.get(0); // set first arrayList element as highest
for (int index=1; index < arrayList.size(); index++) { // cycle through each arrayList element
if (maxArrayListValue < arrayList.get(index)){ // if new element is > than old element
maxArrayListValue = arrayList.get(index); // replace with new maxValue
maxArrayListIndex = index; // record index of max element
}
}
return maxArrayListValue;
}
Any input would be apprecieated.
Your method isn't returning anything, and I think you want to iterate the values in each array. Something like,
public static int maxArrayListValue(List<int[]> arrayList) {
int maxVal = Integer.MIN_VALUE;
for (int[] arr : arrayList) {
for (int v : arr) {
if (v > maxVal) {
maxVal = v;
}
}
}
return maxVal;
}
You don't need a loop. Just use java.util.Collections.max(arrayList);
I have an array of objects and i want to add elements in this array and simultaneously sort them in ascending order.Although I tried many compinations , I always take a java.lang.ArrayIndexOutOfBoundsException. Here is a part of my code :
public boolean insert(Person p)
{
for(int i=0;i<=size();i++)
{
if (c==0)
{
array[0] = p;
c++;
return true;
}
else
{
if (p.compareTo(array[i])==-1)
{
array[i]=p;
c++;
for(int j = size(); j>i; j--)
{
array[j]=array[j-1];
}
}
else if((p.compareTo(array[i])==1))
{
array[i+1]=p;
c++;
for (int j=(size()-1);j>= i+1; j--)
{
array[j+1]=array[j];
}
}
else
{
return false;
}
return true;
}
}
return false;
}
private int c;
private Person array[];
public SortedPersonList()
{
this.array = new Person[c];
}
public int size()
{
return c;
}
Remove the equal sign in for(int i=0;i<=size();i++). That is, change to
for(int i=0;i<size();i++)
Array indices go from 0 to size-1. So array[size()] is outside the array. Hence the error.
1) You are initializing your array to a size 0, and you never resize it. An array has a fixed size, so in order to populate it with items beyond its range, you should first create a larger array and copy the contents to it (This is how ArrayList works).
2) When you find the insertion point, you shouldn't override this position before keeping its value in a temp variable. (Also, I don't understand the third case in your code. Why do you insert if p is greater than array[i]? you should rethink your logic.)
3) you may want to use binary search to find the insertion point. It has a better performance than linear search.
Your code :
for(int i=0;i<=size();i++)
Write like
for(int i=0;i<size();i++) or for(int i=0;i<=size()-1;i++)
Is there an Iterator to loop over data structure in cycles?
Let's say there is an array:
int[] arr = {-1,5,7,-1,-1,-1}
I want to find index of first non -1 value from this array and starting to search from the random position (idx = random.nextInt(arr.length)). For example idx = 4;
So first check if arr[4] == -1, then if arr[5] == -1 and so on. If the end of the array reached then start from 0 position and continue until non -1 found. It is guaranteed that there will be at least one value not equal to -1 in the array.
This can be done so:
int idx = -1;
for (int i = random.nextInt(arr.length); ; i++) {
if (i == arr.length) {
/** start over */
i = 0;
}
if (-1 != arr[i]) {
idx = i;
break;
}
}
Or so:
int idx = -1;
int i = random.nextInt(arr.length);
do {
if (-1 != arr[i]) {
idx = i;
}
i == arr.length ? i=0 : i++;
} while (-1 == idx);
Is there an Iterator, that supports cycling (call next() , if the end of array reached then automatically start from 0)?
Limitations: 1) efficiency is not considered; 2) standard Java API is preferred.
in java API there is no such api which satisfy your problem but you can made it by your own.
what you can do is use List to create LinkedList. to solve your problem.
you can extend List to your class (CircularLinkedList extends List) & then override method hasNext() & getNext() thats all you need.
I don't think there are any iterators that let you know the index of the element as you call next(), so you'd have to keep track of the current index separately. You might be able to build up a "wrap-around" iterator using Guava's Iterators.concat (or some other third-party class) to concatenate an iterator over the trailing part of the array with an iterator over the leading part. However, I think the code is likely to be more complex than a simple for loop or two.
I believe there is no such circular Iterator that will automatically go to the beginning of the array once the end has been reached. I have created one below (not tested, and design is flawed), which requires an entirely new class of code, and is much longer than your short for/while loops.
public class MyCircularIterator<E> implements Iterator<E> {
private List<E> list;
private int pos;
public MyCircularIterator(List<E> list) {
this(list, 0);
}
public MyCircularIterator(List<E> list, int start) {
this.list = list;
pos = start;
}
public boolean hasNext() {
if(list.get(pos) != -1) return false;
return true;
}
public E next() {
if(hasNext()) {
E obj = list.get(pos);
pos = (pos + 1) % list.size();
return obj;
}
}
public void remove() {
list.remove(this.nextIndex);
}
}