3

I'm pretty new to Java and not from a programming background. I am doing a course and am stuck on a piece I hope this is appropriate to ask a question here). The question ask to create a method that takes an array of integers as an argumetn and returns a sorted set containing the elements of the that array. I am not including the code as I don't want the answer but I would like a clue. It's driving me nuts!

Yours in anticipation

JC

4
  • I 've never though StackOverflow or any other site would have become a "do my homework for me" kind of site. As a consequence, I flag this question as requiring moderator attention. Commented Feb 18, 2010 at 9:42
  • 1
    It's not a "do my homework for me" question. He/She asks to give a hint, not an answer. Commented Feb 18, 2010 at 9:54
  • 1
    I think it was kind of interesting. And judging from the answers the question wasn't thought of as provoking... It's not rocket science, but the again quality isn't always higher in advanced questions. Commented Feb 18, 2010 at 10:18
  • Wow guys thanks a million. However I think that writing the problem down really helped and i solved it myself like a proper grown up!! Really appreciated your conributions - JC Commented Feb 18, 2010 at 10:44

6 Answers 6

5

Ok, let's go through this together. Follow me:

The question ask to create a method that takes an array of integers as an argumetn and returns a sorted set containing the elements of the that array.

We have three steps here:

  1. we need to figure out how to pass an array to a function
  2. we need to figure out how to sort elements
  3. we need to figure out how to return an array (of sorted elements)

What I'm doing here is taking the main problem and dividing it into smaller, more approachable sub-problems. It's called divide et impera. You'll encounter this approach very often if you pursue a programming career.

  1. pass an array to a function: write a simple program that prepares an array, passes it to a function and have the function print it. Something like (in my own just-made up version of a pseudocode):
main() {     
    a[] = { "one", "two", "three"};
    f(a);
}

f(arr[]) {
    for ( int i = 0 ; i < arr.length ; i++ ) 
        print(arr[i]);
}

You with me so far? I hope so.

Now,

  1. sorting of elements: I'm pretty sure you already have a way of doing it in your textbook or your notes. Remember you must sort an array. Now our function f() would look something like:
f(arr[]) {
     /* insert here your sorting method */
}

Once this is done, you need to pass back this array to the main function. Now, if you were to pass back a single value from a function, you would do something like:

int g() {
    int i = 0;
    i++;
    return i;
}

since they want you to return an array, it would be something like:

int[] h() {
    /* initialize the array */
    int[] j = { 1, 2, 3 };
    /* your code goes here */
    return j;
}

At this point you have all elements you need for the question you were asked. Just make them work in java first, then put everything together.

Welcome to the magic world of programming :)

Sign up to request clarification or add additional context in comments.

2 Comments

Wow guys thanks a million. However I think that writing the problem down really helped and i solved it myself like a proper grown up!! Really appreciated your conributions - JC
Some people say "explaining the problem is half the solution". I think it applies here as well :)
1
import org.junit.Test;

import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;

/**
 * @version $Id$
 */
public class MainTest {

    public SortedSet sortIntegers(Integer[] ints) {
        return new TreeSet(Arrays.asList(ints));
    }

    @Test
    public void it_should_return_a_sorted_set() throws Exception {
        assertThat(sortIntegers(new Integer[]{5, 7, 1, 6}), is(instanceOf(SortedSet.class)));
    }

    @Test
    public void it_should_return_four_elements() throws Exception {
        assertThat(sortIntegers(new Integer[]{5, 7, 1, 6}).size(), is(4));
    }

    @Test
    public void it_should_return_in_the_right_order() throws Exception {
        Integer previous = 0;

        for (Integer current : sortIntegers(new Integer[]{5, 7, 1, 6})) {
            assertThat(current , is(greaterThan(previous)));
            previous = current;
        }        
    }

}

2 Comments

I know it sounds like an excuse, but... weird! I had generics before the cut and paste from Idea to the textbox here! :) :) :)
public SortedSet<Integer> sortIntegers(Integer[] ints) { return new TreeSet<Integer>(Arrays.asList(ints)); }
1

Tips:

  1. How do you create an element that takes an int as an argument?
  2. How do you declare an array of type int?
  3. Put those together.

For the SortedSet:

  1. Convert the array to a List. Hint: look for an asList() method
  2. Add all the elements of the resulting List to a SortedSet. Hint: addAll().

EDIT: Aaargh! Didn't see the SortedSet in the question

Comments

0

There are plenty of tutorials on the net, check out this example, its not exactly what you want but may point you in the right direction.

Good Luck!

Comments

0

There are some points you should remember:

SortedSet is an interface, so you must find a suitable implementation (Hint: the API contains "All Known Implementing Classes")

The "int"s are native datatypes, no objects. So you need to encapsulate them in wrappers (see Integer.valueOf()) before you can use them in a Set.

The rest should be a simple iteration over the source array, and putting each element to the new Set.

HTH

Comments

0

You can create a new array, and iterate over your given array as long as there are still ints in your array. You can search for the highest or lowest int and put this one in the new array, and remove it from the given array. You can do this as long as there are items in the given array. If the given array is empty return the new array.

I thought this is what you meant.


I did not read properly, sorry.

You can create a new SortedSet, see here for more information: SortedSet, and use add or addAll to add items to this sortedSet. See for more information about Set

2 Comments

Except the question asked to return a SortedSet not an array ;)
@Paolo You where right. I did not read properly, sorry. I have added some links about SortedSets and Set.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.