0% found this document useful (0 votes)
10 views

Lab2 1DArrays

Uploaded by

eire.euan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Lab2 1DArrays

Uploaded by

eire.euan
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

CS4222: Lab 1: Arrays

The System.arraycopy method & the Arrays.copyOf method can help you with these
operations. Look these up in the JavaDoc webpages to clarify the parameter details.

1. Write the code for a method with the following header

public boolean contains(int[] a, int x)

The method is passed a collection of integers and a single integer value. The method
returns true if the collection contains the integer value. Otherwise, it returns false.

// Select this and the next line to unhide a possible solution

public boolean contains(int[] a, int x) {


// determine whether the array 'a' has the value 'x' as one of its values.
// If 'a' does contain 'x' then return true. Otherwise return false.
//NOTE: This version will search the ENTIRE array 'a' for the value 'x'
// Initial assumption - 'x' is not in 'a'
boolean found = false;

// Now step through the array until one of two things happens.
// (i) We exhaust all the items in the array (i.e. we reach the end
// and have not found the 'x'
// (ii) We find 'x' at some position in the array (i.e. we refute the
// initial assumption.

// Because we need the value if 'i' outside the loop it has been
// declared separately.
int i;
// Step through the array from beginning to end (or first to last)
for(i = 0 ; i < a.length && a[i] != x ; i++);
// We have stopped stepping through the array. Did we find 'x'?
// If we reached the end of the array then WE DID NOT.
// If we stopped BEFORE we reached then end then WE DID.
// Check which one it is
if(i < a.length){
// We DIDN'T reach the end of the array - So we found 'x' at
position 'i'
// Change our initial assumption
found = true;
}
// Return the FINAL assumption
return found ;
}
//
CS4222: Lab 1: Arrays

2. Write the code for a method with the following header

public boolean contains(int[] a, int x, int N)

The method is passed a collection of integers, an integer value that we want to search
for and an integer value specifying the maximum number of array positions to be
searched. This method is like the method in exercise 1 except that exercise 1 searches
the entire array whereas this method searches only the first N positions (i.e., positions 0
to N-1) of the array. The size of the section that is searched is specified by the third
parameter N.
If the collection contains the integer value in any of the first N positions the method
returns true. Otherwise it returns false.

// Select this and the next line to unhide a possible solution

public boolean contains(int[] a, int x, int N) {


// Determine whether the the array 'a' has the value 'x' as one of its
values
// in THE FIRST N POSITIONS (i.e. positions 0 TO N-1 ONLY).
// If 'a' does contain 'x' then return true. Otherwise return false.
// NOTE: This is an OVERLOADED version of Exercise 1 that will search a
PORTION
// of the array 'a' for the value 'x'

// Initial assumption - 'x' is not in 'a'


boolean found = false;

// Now step through the array until one of two things happens.
// (i) We exhaust all the items in the array at positions 0 to N-1
(i.e. we reach
// position N and we have not found the value 'x'
// (ii) We find 'x' at one of the positions 0 to N-1 (i.e. we refute
the
// initial assumption.

// Because we need the value if 'i' outside the loop it has been
// declared separately.
int i;
// Step through the array from beginning to end (or first to last)
for(i = 0 ; i < N && a[i] != x ; i++);
// We have stopped stepping through the array. Did we find 'x'?
// If we reached the end of the array then WE DID NOT.
// If we stopped BEFORE we reached then end then WE DID.
// Check which one it is
if(i < N){
// We DIDN'T reach position N - So we found 'x' at position 'i'
// Change our initial assumption
found = true;
}
CS4222: Lab 1: Arrays
// Return the FINAL assumption
return found ;
}
//

3. Write the code for a method with the following header

public int[] indexesOf(int[] a, int x)

The method is passed a collection of integers and an integer value. The method returns
a collection that contains the positions of all occurrences of the value.
The collection returned cannot be longer than the length of the collection passed to the
method. Start with a new collection that is large enough and, if necessary, resize it after
you have established how many occurrences of x are in the collection.

// Select this and the next line to unhide a possible solution

public int[] indexesOf(int[] a, int x) {


// GENERAL COMMENT
// This exercise is another example of how we can RETURN arrays
// from methods. REMEMBER, we DON'T actually return ALL of the values
// in the array. We simply return a SINGLE value that REFERENCEs the
// collection of values in the array. So, like ALL other methods
// we are returning a single value.
// END OF GENERAL COMMENT

// We don't yet know how many times the value 'x' appears in the
// array 'a' so initially we assume that it appears in EVERY one of
// the positions. We will (if necessary) change this later.

// Create space equivalent to the existing array 'a'.


int[] indices = new int[a.length];

// Initialise a counter of the number of occurrences of 'x' found so


far
int xOccurrenceCount = 0 ;

// Step through the array looking for values of 'x'. Each time we find
// one we record the position, or index, in the indices array. We also
// increment the 'xOccurrenceCount' to note how many we have found BUT
ALSO
// to inform us where the next index should be recorded in the
'indices' array.
// Think carefully about that last sentence. A very, very, very useful
side effect
// of counting the occurrences is that we also know where the next
index
// should be stored in the 'indices' array.
//
for(int i=0 ; i < a.length ; i++) {
if(a[i] == x) {
indices[xOccurrenceCount] = i;
CS4222: Lab 1: Arrays
xOccurrenceCount++;
}
}
// Our initial assumption about the space requirements for the
'indices' array
// MAY have been too generous. We need to check if the utilisation of
the
// array is less than the capacity. If it is we will remove the excess
capacity
// and return a "trimmed" array that is exactly the correct size for
the number
// of 'indices'.
if(xOccurrenceCount < indices.length) {
// To 'resize' or 'trim' the 'indices' array we use the
Arrays.copyOf method which
// creates a new array of the correct size, copies the data to it,
and returns the
// reference to the new (smaller) array
indices = Arrays.copyOf(indices,xOccurrenceCount);
}
//
// Alternatively, we could have written the code ourselves as follows
// if(xOccurrenceCount < indices.length) {
// int[] trimmedArray = new int[xOccurrenceCount];
// // Copy ONLY the required entries (i.e. from position 0 to
the position
// // identified by the variable 'xOccurrenceCount') from the
'indices' array
// // to the corresponding positions in the new
'trimmedArray'.
// for(int i=0 ; i < utilisation ; i++) {
// trimmedArray[i] = indices[i];
// }
// // NOTE, now 'trimmedArray' is FULL, or viewed
// // another way, there is no unused/wasted space in it.
// }
// // Now set 'indices' to refer to the 'trimmedArray' space
// indices = trimmedArray;
//
// Now return the 'indices' array the contains the indices of x
return indices;
}
//

4. Write the code for a method with the following header

public int[] append(int[] a, int[] b)

The method is passed TWO collections of integers. It returns a SINGLE collection which
contains all of the values in the first collection (i.e. collection a) followed by all of the
values in the second collection (i.e. collection b).

// Select this and the next line to unhide a possible solution


CS4222: Lab 1: Arrays
public int[] append(int[] a, int[] b) {
// This exercise creates a new array that is the amalgamation of the
two
// parameter arrays. The new, amalgamated array will be the size of the
// two arrays combined so we create sufficient space to store that
number
// of values. NOTE: DUPLICATES ARE ALLOWED.
int[] c = new int[a.length + b.length];
// Now copy ALL the values in array 'a' to the new space, starting from
// the first position.
// To save US having to code this we use the "arraycopy" method
provided by the System class
System.arraycopy(a,0,c,0,a.length);
// This operation copies
// - values in array 'a' starting at position 0 (i.e. first 2
parameters specify the source starting point)
// - to the 'c' array starting from position 0 (i.e. second 2
parameters specify destination starting point)
// - 'a.length' values in 'a' are copied to 'c' (i.e. final
parameter specifies how many values should be copied)
// So ALL the values in 'a' get copied in to 'c' starting at position 0
in 'c'
// Alternatively we could write the code ourselves using a standard
'for' loop as follows
// for(int i = 0 ; i < a.length ; i++) {
// c[i] = a[i];
// }
//
// Now copy ALL the values in array 'b' to the new space, starting from
// the next available position. That HAS TO BE the position identified
by
// the length of the array 'a' since ALL of the values in 'a' have
already
// been put in the new array. So, the 'b' array values are added
RELATIVE
// to the position of the last 'a' value. Thus the first 'b' value is
put in
// position [a.length + 0], the next one in [a.length + 1], then
[a.length + 2]
// and so on until they are all added.
// Again we can use the System class 'arraycopy' method to do the work
for us
System.arraycopy(b,0,c,a.length,b.length);
// This operation copies
// - values in array 'b' starting at position 0 (i.e. first 2
parameters specify the source starting point)
// - to the 'c' array starting from position a.length (i.e.
second 2 parameters specify destination starting point)
// - 'b.length' values in 'b' are copied to 'c' (i.e. final
parameter specifies how many values should be copied)
// So ALL the values in 'b' get copied in to 'c' starting at position
a.length in 'c'
// Alternatively we could write the code ourselves using a standard
'for' loop as follows
// for(int i = 0 ; i < b.length ; i++) {
// c[a.length + i] = b[i];
CS4222: Lab 1: Arrays
// }
// Now c contains the amalgamated data from the two parameter arrays
// so we return a reference to the c array as the result.
return c;
}
//

5. Write the code for a method with the following header

public int[] union(int[] a, int[] b)

The method is passed TWO collections of integers and returns the union of the two
collections (i.e. the values from both collections but with duplicates removed).

HINT: The union of the two collections cannot be longer than the combined lengths of
the two collections. You could start with a collection that is the size of the combined
lengths and, if necessary, resize it after you have established the values that are in the
union.

// Select this and the next line to unhide a possible solution

public int[] union(int[] a, int[] b) {


// Create an array that will hold the union of the two arrays.
// We do not know if the arrays contain any duplicates or how many
// values they have in common so initially we will assume that all
// of the values are unique and set aside enough space to store
// the combined lengths of the arrays.
int[] unionArray = new int[a.length + b.length];
// As we add individual values to the union we will count them. This
// will provide two pieces of information. First, it will tell us how
// many values are in the union (i.e. what the utilisation of the union
// array is). Second, it will identify where in the union array we
should
// put the next value to be added.
int unionCount = 0 ;
// Because the two arrays could be of different lengths it would be a
// good idea to use the longest array as the driver of the process.
// The following code will ensure that array 'a' is the longest by
// (if necessary) swapping the array references. NOTE (VIP): We are
// NOT swapping the collections of values that are in the arrays we
// are only swapping the references to the arrays.
if(b.length > a.length) {
// The 'b' array is longer. Swap the array references to ensure
// that the 'a' array is the longest.
int[] temp = a; // temp is a reference to an array of integers
a = b;
b = temp;
}
// Now we can be certain that the 'a' array is the longest.
CS4222: Lab 1: Arrays
// Step through it and insert each value into the union array ONLY if
// the value is NOT one of the values we have put in the union array
already (i.e. eliminate duplicates).
// At any time the varaible unionCount will store the number of values
currently in the union array.
// We can use this information with the "contains" method in Exercise 2
above to search a portion of
// the union array when we are looking for duplicates.
for(int i = 0 ; i < a.length ; i++) {
if(!contains(unionArray,a[i],unionCount)) { // The contains method
of Exercise 2
unionArray[unionCount] = a[i];
unionCount++;
}
}
// Now we can step through the 'b' array and repeat the process
for(int i = 0 ; i < b.length ; i++) {
if(!contains(unionArray,b[i])) {
unionArray[unionCount] = b[i];
unionCount++;
}
}
// Our initial assumption about the space requirements for the union
array
// may have been too generous. We need to check is the utilisation of
the
// array is less than the capacity. If it is we will remove the excess
capacity
// and return a "trimmed" array that is exactly the correct size for
the union.
// As in the previous exercises, the Arrays.copyOf method can trim the
array for us.
if(unionCount < unionArray.length) {
unionArray = Arrays.copyOf(unionArray,unionCount);
}
return unionArray;
}
//

6. Write the code for a method with the following header

public int[] intersection(int[] a, int[] b)

The method is passed TWO collections of integers and returns the intersection of the
two collections (i.e. the values that appear in BOTH collections).

HINT: The intersection of the two collections cannot be longer than the length of the
shortest collection. You could start with a collection that size and, if necessary, resize it
after you have established the number of values that are in the intersection.
CS4222: Lab 1: Arrays

// Select this and the next line to unhide a possible solution

public int[] intersection(int[] a, int[] b) {


// The intersection of two lists/arrays CANNOT be larger than the
shortest array.
// So, we initially create an array that is large enough for the worst
case
// scenario and we will 'trim' it later if necessary.
//
// Initially we will assume that the 'a' array is smaller than the 'b'
array
int shortestLength = a.length;
// Now check if we were right. If we were NOT right then just change
our minds
// and use the length of the 'b' array
if(b.length < a.length) {
shortestLength = b.length;
}
int[] intersectionArray = new int[shortestLength];

// The rest of this solution is very similar to the previous exercises.


//
// CAN YOU COMPLETE THE COMMENTS FOR THIS EXERCISE?
//
int count = 0 ;
for(int i = 0 ; i < a.length ; i++) {
if(contains(b,a[i])) {
intersectionArray[count] = a[i];
count++;
}
}
if(count < intersectionArray.length) {
intersectionArray = Arrays.copyOf(intersectionArray,count);
}
return intersectionArray;
}
//

You might also like