Syntax error when using "DynaArray<int>" in Java? - java

I am trying to write my own version of a C++ STL vector<> I want it to make a dynamically growing and shrinking list...I want to have methods for push_back, push_front, pop_back, pop_front, remove, removeAt, clear, and size...I wrote all of these with little problem and am getting no build errors or warnings, when I try to instantiate the class Eclipse tells me that its looking for Dimensions after token...so it thinks any type I send in wants to be an array of that type, for instance...
DynaArray<int> Bob;
Here it wants the [] operator after the int.
Here is what my class presently looks like
public class DynaArray<T>
{
int Size = 0;
int CurrentCount = 0;
int LastSpot = 0;
T[] Array;
DynaArray(int _size)
{
Size = _size;
}
#SuppressWarnings("unchecked")
void push_back(T _element)
{
CurrentCount++;
if(CurrentCount > Size)
{
//make a new array for double the size;
if( Size == 0 )
{
Size = 2;
Array = (T[]) new Object[Size];
}
else
{
int OldSize = Size;
Size = Size*2;
T[] TempArray;
TempArray = (T[]) new Object[Size];
int i = 0;
for( ; i < OldSize; i++ )
{
//Copy over info from Array to TempArray
TempArray[i] = Array[i];
}
Array = TempArray;
}
}
//Now add the new element onto the array
Array[LastSpot] = _element;
LastSpot++;
}
#SuppressWarnings("unchecked")
void push_front(T _element)
{
CurrentCount++;
if( Size == 0)
{
Size = 2;
Array = (T[]) new Object[Size];
Array[0] = _element;
return;
}
else
{
int OldSize = Size;
Size = Size+1;
T[] TempArray;
TempArray = (T[]) new Object[Size];
int i = 1;
for( ; i < OldSize; i++ )
{
//Copy over info from Array to TempArray
TempArray[i] = Array[i-1];
Array = TempArray;
Array[0] = _element;
}
}
}
T pop_back()
{
if( CurrentCount <= 0)
return null;
else
{
return Array[CurrentCount-1];
}
}
T pop_front()
{
if( CurrentCount <= 0)
return null;
else
{
return Array[0];
}
}
int size()
{
return CurrentCount;
}
#SuppressWarnings("unchecked")
void clear()
{
Size = 0;
CurrentCount = 0;
LastSpot = 0;
Array = (T[]) new Object[2];
}
#SuppressWarnings("unchecked")
void removeAt(int index)
{
T[] TempArray = (T[]) new Object[Size];
int ArrayIndex = 0;
for( int i = 0; i < CurrentCount; i++)
{
if( i == index )
continue;
TempArray[ArrayIndex] = Array[i];
ArrayIndex++;
}
}
void remove(T _element)
{
for(int i = 0; i < CurrentCount; i++)
{
//look for the element
if( Array[i] == _element)
removeAt(i);
}
}
}
Thanks for any help provided or if my code somehow helped you are welcome

int is a primitive, and as such cannot be used with Java generics. The reason for this is to maintain the bytecode's backwards compatibility (which was important when generics were first introduced). You must use an Integer instead.
N.B. unless you're doing this as an academic exercise, you can/should just use a List<T> instead of your custom-implemented class.
Alternatively: use Trove.

You cannot use Java primitives as a generic type because they are not instances of Object. The reason why int[] works is because a Java array is an object. Use the boxed Integer instead.

Related

Find Common Elements between two Arrays

I want to find the common elements between two arrays with different sizes and put them in another array.
Can you tell what's wrong with my code?
public static int[] numratEQelluar(int[] vargu, int[]varguPer)
{
int count = 0;
int [] nrQelluar = new int[count];
for(int i = 0; i<vargu.length; i++)
{
for(int idx = 1;idx<varguPer.length ; idx++)
{
if(vargu[i] == (varguPer[idx]))
{
count++;
for(int index = 0; index<nrQelluar.length; index++)
{
nrQelluar[index] = vargu[i];
}
}
}
}
return nrQelluar;
The reason it doesn't work is indeed due to incorrect memory allocation to nrEqualler as been said in the comments.
However, there are a few thing i'd change in your code:
using a LinkedList instead of primitive int [] for dynamic sized
array is much more efficient (add in O(1)).
less indentations and confusing indexes by extracting methods.
So this should do:
public static int[] numratEQelluar(int[] vargu, int[]varguPer){
List<Integer> nrQelluar = new LinkedList<Integer> ();
for(int i = 0; i < vargu.length; i++) {
if (contains(varguPer, vargu[i])) nrQelluar.add(vargu[i]);
}
return toPrimitive(nrQelluar);
}
private static boolean contains(int [] array, int num){
for(int i = 0; i < array.length; i++){
if(array[i] == num) return true;
}
return false;
}
private static int[] toPrimitive(List<Integer> list) {
int[] primitiveArray = new int[list.size()];
for(int i = 0; i < list.size(); i++){
primitiveArray[i] = list.get(i);
}
return primitiveArray;
}
The problem is between these lines of code
int count = 0;
int [] nrQelluar = new int[count];
The size of your new array will be zero. try changing this to the sum of the length of both the arrays.
Updated with a working code.
Try this code :
public static Integer[] findCommonElements(int[] arr1, int[] arr2){
HashSet set = new HashSet<>();
for(int i=0;i<arr1.length;i++){
for(int j=0;j<arr2.length;j++){
if(arr1[i] == arr2[j]){
set.add(arr1[i]);
}
}
}
Integer[] resultArray = (Integer[]) set.toArray(new Integer[set.size()]);
return resultArray;
}
Using a set will ensure that you won't get any duplicates in the resulting array. If duplicates are fine, then you can use ArrayList to store the common elements and then convert them into Array.

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)

java.lang.NullPointerException when I try to add value to Array

I have a task to make my own Dynamic Array without using any ArrayLists or other pre-made classes for Arrays in java.
I get an Exception in thread "main" java.lang.NullPointerException error when I try to add my object (for example it's Integer).
Dinaminis<Integer> array = new Dinaminis<>();
array.ideti(5);
And my Dinaminis class looks like this:
public class Dinaminis<T> implements DArray<T>
{
private Object[] array;
private int kiek;
private Object[] temp;
public Dinaminis() {
array = new Object[10];
kiek = 0;
}
#Override
public void ideti(Object o) {
if (array.length == kiek) {
temp = new Object[kiek*2];
}
for (int i=1; i < kiek; i++){
temp[i] = array[i];
}
array = temp;
array[kiek] = o;
kiek++;
}
}
The thing is when I want to use "ideti" method, I want to check if the array is full, and if it's full it should create a double sized array. But I get an error even before my array is full.
Your ideti method is wrong. This should work:
public void ideti(Object o) {
if (array.length == kiek) {
temp = new Object[kiek*2];
// only copy old array to new array when old one is full
for (int i=0; i < kiek; i++){ // index starts at 0, not 1
temp[i] = array[i];
}
array = temp;
}
array[kiek] = o;
kiek++;
}
Your problem was that the loop that copies the old array to the new one was executed even when the original array wasn't full, in which case temp wasn't initialized, which led to NullPointerException.
I would suggest you store your array as your it's generic type T. I would pass in to the Class<T> to the Dinaminis constructor, then you can use Array.newInstance(). Also, I'd prefer to use System.arraycopy() and override toString() like
public class Dinaminis<T> implements DArray<T> {
private T[] array;
private int kiek;
private Class<T> cls;
public Dinaminis(Class<T> cls) {
this.cls = cls;
array = (T[]) Array.newInstance(cls, 10);
kiek = 0;
}
#Override
public void ideti(T o) {
if (kiek == array.length) {
T[] temp = (T[]) Array.newInstance(cls, array.length * 2);
System.arraycopy(array, 0, temp, 0, array.length);
array = temp;
}
array[kiek++] = o;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(String.format("len = %d [", array.length));
for (int i = 0; i < kiek; i++) {
if (i != 0) {
sb.append(", ");
}
sb.append(array[i]);
}
sb.append("]");
return sb.toString();
}
}
Then you could test it with something like
public static void main(String[] args) {
DArray<Integer> t = new Dinaminis<Integer>(Integer.class);
for (int i = 0; i < 11; i++) {
t.ideti(i);
}
System.out.println(t);
}
Output is
len = 20 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Obviously len was added to this output for pedagogical reasons, and in real code I probably wouldn't display it (except perhaps in a log message).
You need to initialize your temp array before using it.
You do initialize it inside of the if but not outside the if
temp = new Object[kiek*2];
so allocation of the double sized array should only happen when the size of the array is complete
if (array.length == kiek) //check if array size is reached
{
temp = new Object[kiek*2]; //allocate a double sized array
for (int i=1; i < kiek; i++) //copy elements - are you sure you don't want to start with i=0? You won't copy the first element if you start at 1
{
temp[i] = array[i];
}
array = temp;
}

Find values in array and return index

I want to return an array with the index's where the getElem() is equal or higher a certain value.
This is my function:
public static int []findIndex(BufferedImage image,int value)
{
DataBuffer b = image.getRaster().getDataBuffer();
int array[] = new int[600];
for(int i=0;i<76400;i++)
{
if(b.getElem(i)>=value)
array[i]=i;
}
return array;
}
but i have an error
"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 27001
at arraytest.imageMan.findIndex(imageMan.java:139)
at arraytest.imageMan.main(imageMan.java:183)"
int array[] = new int[600];
The array you declare is of size 600.
for(int i=0;i<76400;i++)
Yet you attempt to reference the array at the 76400'th index.
Why doesn't this work?
Well, when you say new int[600], you are essentially saying, my array can store 600 things, and this means that it has 600 different "slots" to store values.
You access these values by their index, starting from 0.
array[0] // First item
array[599] // Last item.
Your error has occurred because you have exceeded 599.
How to fix this
Well, you can either make your array 76400 long, (which to me is suspicious), or you can change 76400 to array.length (or 600) in your for loop.
This is the solution i find..
I think that is the best..
public static int[] findIndex(BufferedImage image, int value) {
DataBuffer b = image.getRaster().getDataBuffer();
int array[] = new int[600];
int j = 0;
for (int i = 0; i < b.getSize(); i++) {
if (b.getElem(i) >= value) {
if (j < 600) {
array[j] = i;
j++;
}
}
}
return array;
}
That's because your loop from 0 to 76400, which much much greater than the size of your array.
public static int []findIndex(BufferedImage image,int value)
{
DataBuffer b = image.getRaster().getDataBuffer();
int array[] = new int[600];
for(int i=0;i<array.length;i++)
{
if(b.getElem(i)>=value)
array[i]=i;
}
return array;
}
This is my final function.
How should we choose a generic programming,i made some changes that made ​​a focused precisely on that.
Use now have a list instead of a static array.
public static int[] findIndex(BufferedImage image, int value) {
DataBuffer b = image.getRaster().getDataBuffer();
ArrayList<Integer> a = new ArrayList<>(20);
int j = 0;
for (int i = 0; i < b.getSize(); i++) {
if (b.getElem(i) >= value) {
a.add(i);
j++;
}
}
int array[] = new int[a.size()];
for (int k = 0; k < a.size(); k++) {
array[k] = a.get(k);
}
return array;
}

How can I find the smallest covering prefix of an array in Java?

Find the first covering prefix of a given array.
A non-empty zero-indexed array A consisting of N integers is given. The first covering
prefix of array A is the smallest integer P such that and such that every value that
occurs in array A also occurs in sequence.
For example, the first covering prefix of array A with
A[0]=2, A[1]=2, A[2]=1, A[3]=0, A[4]=1 is 3, because sequence A[0],
A[1], A[2], A[3] equal to 2, 2, 1, 0 contains all values that occur in
array A.
My solution is
int ps ( int[] A )
{
int largestvalue=0;
int index=0;
for(each element in Array){
if(A[i]>largestvalue)
{
largestvalue=A[i];
index=i;
}
}
for(each element in Array)
{
if(A[i]==index)
index=i;
}
return index;
}
But this only works for this input, this is not a generalized solution.
Got 100% with the below.
public int ps (int[] a)
{
var length = a.Length;
var temp = new HashSet<int>();
var result = 0;
for (int i=0; i<length; i++)
{
if (!temp.Contains(a[i]))
{
temp.Add(a[i]);
result = i;
}
}
return result;
}
I would do this
int coveringPrefixIndex(final int[] arr) {
Map<Integer,Integer> indexes = new HashMap<Integer,Integer>();
// start from the back
for(int i = arr.length - 1; i >= 0; i--) {
indexes.put(arr[i],i);
}
// now find the highest value in the map
int highestIndex = 0;
for(Integer i : indexes.values()) {
if(highestIndex < i.intValue()) highestIndex = i.intValue();
}
return highestIndex;
}
Your question is from Alpha 2010 Start Challenge of Codility platform. And here is my solution which got score of 100. The idea is simple, I track an array of counters for the input array. Traversing the input array backwards, decrement the respective counter, if that counter becomes zero it means we have found the first covering prefix.
public static int solution(int[] A) {
int size = A.length;
int[] counters = new int[size];
for (int a : A)
counters[a]++;
for (int i = size - 1; i >= 0; i--) {
if (--counters[A[i]] == 0)
return i;
}
return 0;
}
here's my solution in C#:
public static int CoveringPrefix(int[] Array1)
{
// Step 1. Get length of Array1
int Array1Length = 0;
foreach (int i in Array1) Array1Length++;
// Step 2. Create a second array with the highest value of the first array as its length
int highestNum = 0;
for (int i = 0; i < Array1Length; i++)
{
if (Array1[i] > highestNum) highestNum = Array1[i];
}
highestNum++; // Make array compatible for our operation
int[] Array2 = new int[highestNum];
for (int i = 0; i < highestNum; i++) Array2[i] = 0; // Fill values with zeros
// Step 3. Final operation will determine unique values in Array1 and return the index of the highest unique value
int highestIndex = 0;
for (int i = 0; i < Array1Length; i++)
{
if (Array2[Array1[i]] < 1)
{
Array2[Array1[i]]++;
highestIndex = i;
}
}
return highestIndex;
}
100p
public static int ps(int[] a) {
Set<Integer> temp = new HashSet<Integer>();
int p = 0;
for (int i = 0; i < a.length; i++) {
if (temp.add(a[i])) {
p = i+1;
}
}
return p;
}
You can try this solution as well
import java.util.HashSet;
import java.util.Set;
class Solution {
public int ps ( int[] A ) {
Set set = new HashSet();
int index =-1;
for(int i=0;i<A.length;i++){
if(set.contains(A[i])){
if(index==-1)
index = i;
}else{
index = i;
set.add(A[i]);
}
}
return index;
}
}
Without using any Collection:
search the index of the first occurrence of each element,
the prefix is the maximum of that index. Do it backwards to finish early:
private static int prefix(int[] array) {
int max = -1;
int i = array.length - 1;
while (i > max) {
for (int j = 0; j <= i; j++) { // include i
if (array[i] == array[j]) {
if (j > max) {
max = j;
}
break;
}
}
i--;
}
return max;
}
// TEST
private static void test(int... array) {
int prefix = prefix(array);
int[] segment = Arrays.copyOf(array, prefix+1);
System.out.printf("%s = %d = %s%n", Arrays.toString(array), prefix, Arrays.toString(segment));
}
public static void main(String[] args) {
test(2, 2, 1, 0, 1);
test(2, 2, 1, 0, 4);
test(2, 0, 1, 0, 1, 2);
test(1, 1, 1);
test(1, 2, 3);
test(4);
test(); // empty array
}
This is what I tried first. I got 24%
public int ps ( int[] A ) {
int n = A.length, i = 0, r = 0,j = 0;
for (i=0;i<n;i++) {
for (j=0;j<n;j++) {
if ((long) A[i] == (long) A[j]) {
r += 1;
}
if (r == n) return i;
}
}
return -1;
}
//method must be public for codility to access
public int solution(int A[]){
Set<Integer> set = new HashSet<Integer>(A.length);
int index= A[0];
for (int i = 0; i < A.length; i++) {
if( set.contains(A[i])) continue;
index = i;
set.add(A[i]);
}
return index;
}
this got 100%, however detected time was O(N * log N) due to the HashSet.
your solutions without hashsets i don't really follow...
shortest code possible in java:
public static int solution(int A[]){
Set<Integer> set = new HashSet<Integer>(A.length);//avoid resizing
int index= -1; //value does not matter;
for (int i = 0; i < A.length; i++)
if( !set.contains(A[i])) set.add(A[index = i]); //assignment + eval
return index;
}
I got 100% with this one:
public int solution (int A[]){
int index = -1;
boolean found[] = new boolean[A.length];
for (int i = 0; i < A.length; i++)
if (!found [A[i]] ){
index = i;
found [A[i]] = true;
}
return index;
}
I used a boolean array which keeps track of the read elements.
This is what I did in Java to achieve 100% correctness and 81% performance, using a list to store and compare the values with.
It wasn't quick enough to pass random_n_log_100000 random_n_10000 or random_n_100000 tests, but it is a correct answer.
public int solution(int[] A) {
int N = A.length;
ArrayList<Integer> temp = new ArrayList<Integer>();
for(int i=0; i<N; i++){
if(!temp.contains(A[i])){
temp.add(A[i]);
}
}
for(int j=0; j<N; j++){
if(temp.contains(A[j])){
temp.remove((Object)A[j]);
}
if(temp.isEmpty()){
return j;
}
}
return -1;
}
Correctness and Performance: 100%:
import java.util.HashMap;
class Solution {
public int solution(int[] inputArray)
{
int covering;
int[] A = inputArray;
int N = A.length;
HashMap<Integer, Integer> map = new HashMap<>();
covering = 0;
for (int i = 0; i < N; i++)
{
if (map.get(A[i]) == null)
{
map.put(A[i], A[i]);
covering = i;
}
}
return covering;
}
}
Here is my Objective-C Solution to PrefixSet from Codility. 100% correctness and performance.
What can be changed to make it even more efficient? (without out using c code).
HOW IT WORKS:
Everytime I come across a number in the array I check to see if I have added it to the dictionary yet.
If it is in the dictionary then I know it is not a new number so not important in relation to the problem. If it is a new number that we haven't come across already, then I need to update the indexOftheLastPrefix to this array position and add it to the dictionary as a key.
It only used one for loop so takes just one pass. Objective-c code is quiet heavy so would like to hear of any tweaks to make this go faster. It did get 100% for performance though.
int solution(NSMutableArray *A)
{
NSUInteger arraySize = [A count];
NSUInteger indexOflastPrefix=0;
NSMutableDictionary *myDict = [[NSMutableDictionary alloc] init];
for (int i=0; i<arraySize; i++)
{
if ([myDict objectForKey:[[A objectAtIndex:i]stringValue]])
{
}
else
{
[myDict setValue:#"YES" forKey:[[A objectAtIndex:i]stringValue]];
indexOflastPrefix = i;
}
}
return indexOflastPrefix;
}
int solution(vector &A) {
// write your code in C++11 (g++ 4.8.2)
int max = 0, min = -1;
int maxindex =0,minindex = 0;
min = max =A[0];
for(unsigned int i=1;i<A.size();i++)
{
if(max < A[i] )
{
max = A[i];
maxindex =i;
}
if(min > A[i])
{
min =A[i];
minindex = i;
}
}
if(maxindex > minindex)
return maxindex;
else
return minindex;
}
fwiw: Also gets 100% on codility and it's easy to understand with only one HashMap
public static int solution(int[] A) {
// write your code in Java SE 8
int firstCoveringPrefix = 0;
//HashMap stores unique keys
HashMap hm = new HashMap();
for(int i = 0; i < A.length; i++){
if(!hm.containsKey(A[i])){
hm.put( A[i] , i );
firstCoveringPrefix = i;
}
}
return firstCoveringPrefix;
}
I was looking for the this answer in JavaScript but didn't find it so I convert the Java answer to javascript and got 93%
function solution(A) {
result=0;
temp = [];
for(i=0;i<A.length;i++){
if (!temp.includes(A[i])){
temp.push(A[i]);
result=i;
}
}
return result;
}
// you can also use imports, for example:
import java.util.*;
// you can use System.out.println for debugging purposes, e.g.
// System.out.println("this is a debug message");
class Solution {
public int solution(int[] A) {
// write your code in Java SE 8
Set<Integer> s = new HashSet<Integer>();
int index = 0;
for (int i = 0; i < A.length; i++) {
if (!s.contains(A[i])) {
s.add(A[i]);
index = i;
}
}
return index;
}
}

Categories