Created
September 20, 2019 00:09
-
-
Save seyijava/a7fc21e2104d5934b5c2771b5e02e5d0 to your computer and use it in GitHub Desktop.
Theorem Software Engineer Screener Test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.bigdataconcept.algo.util; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
import java.util.stream.Stream; | |
import static java.util.Arrays.asList; | |
/** | |
* @author Oluwaseyi otun | |
* | |
*/ | |
public class FlattenArrayUtil | |
{ | |
public static void main( String[] args ) | |
{ | |
List<Object> numberArrayList = array(array(1,2,array(3)),array(4)); | |
List<Object> flattenArrayList = flattenArray(numberArrayList); | |
System.out.println(numberArrayList); | |
System.out.println("flatten Array: " + flattenArrayList); | |
} | |
private static List<Object> array(Object... number) { | |
return asList(number); | |
} | |
private static Stream<Object> flattenArrayToStream(List<?> list) { | |
return list.stream().flatMap(item -> | |
item instanceof List<?> ? | |
flattenArrayToStream((List<?>)item) : | |
Stream.of(item)); | |
} | |
private static List<Object> flattenArray(List<?> list) { | |
return flattenArrayToStream(list).collect(Collectors.toList()); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import "fmt" | |
// Function that return array of list of values | |
func array(s ...interface{}) []interface{} { | |
return s | |
} | |
func main() { | |
s := array(array(1, | |
2, | |
array(3)), | |
array(4), | |
) | |
fmt.Println(s) | |
fmt.Println(flattenArray(s)) | |
} | |
// Function that flatten the array of intergers and retrun flatten array | |
func flattenArray(s []interface{}) (r []int) { | |
for _, e := range s { | |
switch i := e.(type) { | |
case int: | |
r = append(r, i) | |
case []interface{}: | |
r = append(r, flattenArray(i)...) | |
} | |
} | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment