Tuesday, May 26, 2015

Programming excerise - Alternating loops

This is a fairly easy challenge.  I could see this as a warm up question in a job interview.  The solution I provided assumes the lists are the same length.  In an interview it would often start this way and then be asked to expand upon the solution to account for the variation in list sizes.

Write a function that combines two lists by alternatingly taking elements. For example: given the two lists [a, b, c] and [1, 2, 3], the function should return [a, 1, b, 2, c, 3].




List<String> result = new ArrayList<>();
List<String> letters = new ArrayList<>(Arrays.asList("a","b","c"));
List<String> numbers = new ArrayList<>(Arrays.asList("1","2","3"));

Iterator<String> letterIterator = letters.iterator();
Iterator<String> numberIterator = numbers.iterator();

while (letterIterator.hasNext() || numberIterator.hasNext()) { 
 if (result.size() % 2 == 0) {
  result.add(letterIterator.next());
 } else {
  result.add(numberIterator.next());
 }
}
System.out.println(Arrays.toString(result.toArray()));


Related Content:

3 comments:

  1. I prefer (also deals with variations in list sizes)

    while (letterIterator.hasNext() || numberIterator.hasNext()) {
    if (letterIterator.hasNext()) {result.add(letterIterator.next());}
    if (numberIterator.hasNext())) {result.add(numberIterator.next());}
    }

    ReplyDelete
    Replies
    1. I like it. That is a straightforward solution and very readable

      Delete
  2. Software development is all about thinking, planning, laying out the design. In simple design terms test, patch and dispatch post bug fixing. Marketing the software too can an important role for the success of the project as a whole.winzip activation code

    ReplyDelete