Array practice

posted by: Ms. Martin 19 January 2010 No Comment

You are to write a series of static functions to gain experience working with arrays.  You can have one big ol’ ugly main for this one!  These are great computational thinking problems.  Feel free to jump around as you wish.

Remember to test each method thoroughly!

1) Write a static method that returns an int array of length 3 containing the first 3 digits of pi, {3, 1, 4}.

makePi() → {3, 1, 4}

2) Write a static method that, given an array of ints, returns true if the array is length 1 or more, and the first element and the last element are the same.

sameFirstLast({1, 2, 3}) → false
sameFirstLast({1, 2, 3, 1}) → true
sameFirstLast({1, 2, 1}) → true

3) Write a static method that, given an array of ints, swaps the first and last elements in the array. Return the modified array. The array length will be at least 1.

swapEnds({1, 2, 3, 4}) → {4, 2, 3, 1}
swapEnds({1, 2, 3}) → {3, 2, 1}
swapEnds({8, 6, 7, 9, 5}) → {5, 6, 7, 9, 8}

4) Write a static method that, given an array of ints, return the sum of all the elements.

sum({1, 2, 3}) → 6
sum({5, 11, 2, 3}) → 21
sum({7, 0, 0, 3, 5}) → 15

5) Write a static method that, given an array of ints, returns the index of the smallest value.

findSmallest({4, 5, 2, 1}) → 3
findSmallest({3, 6, 5}) → 0

6) Write a static method that, given a non-empty array of ints, return a new array containing the elements from the original array that come before the first 4 in the original array. The original array will contain at least one 4.

pre4({1, 2, 4, 1}) → {1, 2}
pre4({3, 1, 4}) → {3, 1}
pre4({1, 4, 4}) → {1}

7) Write a static method named stutter that accepts an array of integers as its parameter and returns a new array with two consecutive copies of each value from the original array. You may assume that the array passed is not null.

For example, if the following array is passed:

int[] a = {11, -4, 0, 777};
int[] stuttered = stutter(a);

After the call, the array stuttered should store the elements {11, 11, -4, -4, 0, 0, 777, 777}.

Impress me

1) Say that a “clump” in an array is a series of 2 or more adjacent elements of the same value. Return the number of clumps in the given array.

countClumps({1, 2, 2, 3, 4, 4}) → 2
countClumps({1, 1, 2, 1, 1}) → 2
countClumps({1, 1, 1, 1, 1}) → 1

2) Given a non-empty array, return true if there is a place to split the array so that the sum of the numbers on one side is equal to the sum of the numbers on the other side.

canBalance({1, 1, 1, 2, 1}) → true
canBalance({2, 1, 1, 2, 1}) → false
canBalance({10, 10}) → true

1 Star2 Stars3 Stars4 Stars5 Stars (17 votes, average: 2.88 out of 5)
Loading ... Loading ...

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>