Avatar of artemkorsakov

artemkorsakov's solution

to Flatten Array in the Java Track

Published at Jun 18 2019 · 0 comments
Instructions
Test suite
Solution

Take a nested list and return a single flattened list with all values except nil/null.

The challenge is to write a function that accepts an arbitrarily-deep nested list-like structure and returns a flattened structure without any nil/null values.

For Example

input: [1,[2,3,null,4],[null],5]

output: [1,2,3,4,5]

Tips

Since this exercise has difficulty 5 it doesn't come with any starter implementation. This is so that you get to practice creating classes and methods which is an important part of programming in Java. It does mean that when you first try to run the tests, they won't compile. They will give you an error similar to:

 path-to-exercism-dir\exercism\java\name-of-exercise\src\test\java\ExerciseClassNameTest.java:14: error: cannot find symbol
        ExerciseClassName exerciseClassName = new ExerciseClassName();
        ^
 symbol:   class ExerciseClassName
 location: class ExerciseClassNameTest

This error occurs because the test refers to a class that hasn't been created yet (ExerciseClassName). To resolve the error you need to add a file matching the class name in the error to the src/main/java directory. For example, for the error above you would add a file called ExerciseClassName.java.

When you try to run the tests again you will get slightly different errors. You might get an error similar to:

  constructor ExerciseClassName in class ExerciseClassName cannot be applied to given types;
        ExerciseClassName exerciseClassName = new ExerciseClassName("some argument");
                                              ^
  required: no arguments
  found: String
  reason: actual and formal argument lists differ in length

This error means that you need to add a constructor to your new class. If you don't add a constructor, Java will add a default one for you. This default constructor takes no arguments. So if the tests expect your class to have a constructor which takes arguments, then you need to create this constructor yourself. In the example above you could add:

ExerciseClassName(String input) {

}

That should make the error go away, though you might need to add some more code to your constructor to make the test pass!

You might also get an error similar to:

  error: cannot find symbol
        assertEquals(expectedOutput, exerciseClassName.someMethod());
                                                       ^
  symbol:   method someMethod()
  location: variable exerciseClassName of type ExerciseClassName

This error means that you need to add a method called someMethod to your new class. In the example above you would add:

String someMethod() {
  return "";
}

Make sure the return type matches what the test is expecting. You can find out which return type it should have by looking at the type of object it's being compared to in the tests. Or you could set your method to return some random type (e.g. void), and run the tests again. The new error should tell you which type it's expecting.

After having resolved these errors you should be ready to start making the tests pass!

Setup

Go through the setup instructions for Java to install the necessary dependencies:

https://exercism.io/tracks/java/installation

Running the tests

You can run all the tests for an exercise by entering the following in your terminal:

$ gradle test

Use gradlew.bat if you're on Windows

In the test suites all tests but the first have been skipped.

Once you get a test passing, you can enable the next one by removing the @Ignore("Remove to run test") annotation.

Source

Interview Question https://reference.wolfram.com/language/ref/Flatten.html

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

FlattenerTest.java

import org.junit.Before;
import org.junit.Test;
import org.junit.Ignore;

import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.junit.Assert.assertEquals;

public class FlattenerTest {

    private Flattener flattener;

    @Before
    public void setUp() {
        flattener = new Flattener();
    }

    @Test
    public void testFlatListIsPreserved() {
        assertEquals(asList(0, '1', "two"), flattener.flatten(asList(0, '1', "two")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testASingleLevelOfNestingWithNoNulls() {
        assertEquals(
            asList(1, '2', 3, 4, 5, "six", "7", 8),
            flattener.flatten(asList(1, asList('2', 3, 4, 5, "six", "7"), 8)));
    }

    @Ignore("Remove to run test")
    @Test
    public void testFiveLevelsOfNestingWithNoNulls() {
        assertEquals(
            asList(0, '2', 2, "three", '8', 100, "four", 50, "-2"),
            flattener.flatten(asList(0, 
                              '2', 
                              asList(asList(2, "three"), 
                                     '8', 
                                     100, 
                                     "four",
                                     singletonList(singletonList(singletonList(50)))), "-2")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testSixLevelsOfNestingWithNoNulls() {
        assertEquals(
            asList("one", '2', 3, '4', 5, "six", 7, "8"),
            flattener.flatten(asList("one", 
                                     asList('2', 
                                            singletonList(singletonList(3)),
                                                          asList('4', 
                                                                 singletonList(singletonList(5))), "six", 7), "8")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testSixLevelsOfNestingWithNulls() {
        assertEquals(
            asList("0", 2, "two", '3', "8", "one hundred", "negative two"),
            flattener.flatten(asList("0",
                                     2,
                                     asList(asList("two", '3'),
                                            "8",
                                            singletonList(singletonList("one hundred")),
                                            null, 
                                            singletonList(singletonList(null))), 
                                                          "negative two")));
    }

    @Ignore("Remove to run test")
    @Test
    public void testNestedListsFullOfNullsOnly() {
        assertEquals(emptyList(),
                     flattener.flatten(asList(null, 
                                              singletonList(singletonList(singletonList(null))),
                                                            null, 
                                                            null, 
                                                            asList(asList(null, null), null), null)));
    }

}
import java.util.ArrayList;
import java.util.List;

class Flattener {
    List<Object> flatten(List<Object> asList) {
        List<Object> list = new ArrayList<>();

        for (Object obj : asList) {
            if (obj != null) {
                if (obj instanceof List) {
                    List<Object> inner = flatten((List<Object>) obj);
                    list.addAll(inner);
                } else {
                    list.add(obj);
                }
            }
        }

        return list;
    }
}

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?