Java: Interleaving multiple arrays into a single array

后端 未结 5 582
误落风尘
误落风尘 2020-12-19 06:13

I found similar question about interleaving two arraylists into one, but its in PHP. I was asked this question in interview as well but could\'nt solve it, came back to SO t

5条回答
  •  执念已碎
    2020-12-19 06:28

    The lists don't have to be the same size:

    public class InterleaveTwoLists {
    
        public List interleaveLists(final List first, final List second) {
    
            return new AbstractList() {
                private int minSize;
                private int combinedMinSize;
                private int size;
                private ListlargerList;
                {{
                    minSize = Math.min(first.size(), second.size());
                    combinedMinSize = minSize*2;
                    size = first.size() + second.size();
                    largerList = first.size() > minSize ? first : second;
                }}
    
                public int size() {
                    return size;
                }
    
                public X get(int index) {
                    if (index < combinedMinSize) {
                        return index % 2 == 0 
                            ? first.get(index / 2) 
                            : second.get(index / 2);
                    }
                    else { 
                        return largerList.get(index-minSize);
                    }
                }
            };
        }
    }
    

    To test this:

    public class InterleaveTwoListsTest {
    
        private static final Logger log = 
            LoggerFactory.getLogger(InterleaveTwoListsTest.class);
    
        List first = new ArrayList() {
        { 
            add("one"); add("three"); add("five"); 
            add("seven"); add("eight"); add("nine");
        }};
    
        List second = new ArrayList() {
        { 
            add("two"); add("four"); add("six"); 
        }};
    
    
        private InterleaveTwoLists interleaveTwoLists;
    
        @Before
        public void setUp() throws Exception {
            interleaveTwoLists = new InterleaveTwoLists<>();
        }
    
        @Test
        public void test() {
            List combinedList = interleaveTwoLists.interleaveLists(first, second);
            for( int i = 0; i < first.size() + second.size(); i++) { 
                log.debug("{}: {}", i, combinedList.get(i));
            }
        }
    }
    

提交回复
热议问题