Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #143 Iterate alternatively over two lists

Iterate alternatively over the elements of the lists items1 and items2. For each iteration, print the element.

Explain what happens if items1 and items2 have different size.

import java.util.Iterator;
Iterator<String> iter1 = items1.iterator();
Iterator<String> iter2 = items2.iterator();
while (iter1.hasNext() || iter2.hasNext()) {
	if (iter1.hasNext()) {
		System.out.println(iter1.next());
	}
	if (iter2.hasNext()) {
		System.out.println(iter2.next());
	}
}
import static java.lang.System.out;
import java.util.Iterator;
Iterator<T> A = a.iterator(), B = b.iterator();
boolean x = A.hasNext(), y = B.hasNext();
while (x || y) {
    if (x) out.println(A.next());
    if (y) out.println(B.next());
    x = A.hasNext();
    y = B.hasNext();
}
import static java.lang.Math.max;
import static java.lang.System.out;
int i, A, B, n = max(A = a.size(), B = b.size());
for (i = 0; i < n; ++i) {
    if (i < A) out.println(a.get(i));
    if (i < B) out.println(b.get(i));
}
import java.util.stream.IntStream;
import java.util.stream.Stream;
IntStream.range(0, Math.max(items1.size(), items2.size()))
	.boxed()
	.flatMap(idx -> Stream.of(
		items1.size() > idx ? items1.get(idx) : null,
		items2.size() > idx ? items2.get(idx) : null
	))
	.filter(Objects::nonNull)
	.forEach(System.out::println);
(doseq [i (interleave items1 items2)]
  (println i))
using System.Collections.Generic;
using System.Math;
for(int i = 0; i < Math.Max(items1.Count, items2.Count); i++)
{
  if (i < items1.Count) Console.WriteLine(items1[i]);
  if (i < items2.Count) Console.WriteLine(items2[i]);
}
import std.range;
import std.algorithm.iteration;
import std.stdio;
roundRobin(items1, items2).each!writeln;
do i=1, min(size(items1), size(items2))
  print *,items1(i), items2(i)
end do
for i := 0; i < len(items1) || i < len(items2); i++ {
	if i < len(items1) {
		fmt.Println(items1[i])
	}
	if i < len(items2) {
		fmt.Println(items2[i])
	}
}
import "fmt"
for i := range min(len(items1), len(items2)) {
	fmt.Println(items1[i])
	fmt.Println(items2[i])

}
interweave :: [a] -> [a] -> [a]   -- optional signature
interweave [] ys = ys
interweave xs [] = xs
interweave (x:xs) (y:ys) = x : y : interweave xs ys

main = mapM_ print $ interweave items1 items2
mapM_ print . concat 
	$ zipWith (\a b -> [a,b]) items1 items2
const iterator1 = items1[Symbol.iterator]()
const iterator2 = items2[Symbol.iterator]()

let result1 = iterator1.next()
let result2 = iterator2.next()

while(!(result1.done && result2.done)) {
  if (!result1.done) {
    console.log(result1.value)
    result1 = iterator1.next()
  }
  if (!result2.done) {
    console.log(result2.value)
    result2 = iterator2.next()
  }
}
const shorter = _items1.length > _items2.length ? _items2 : _items1;
const longer = _items1.length <= _items2.length ? _items2 : _items1;
shorter.map((m, i) => {
  console.log(m);
  console.log(longer[i]);
});
# php 5.3+
print array_reduce( array_map( null, $items1, $items2 ), function($c,$d){return $c.($c?"\n":'').implode("\n", $d); }, "")."\n" ;

#php 5.6+
print implode("\n", array_merge( ...array_map( null, $items1, $items2 )))."\n";
uses Math;
for i := 0 to Min(items1.Count-1,items2.Count-1) do 
  writeln(items1[i],', ',items2[i]);
use List::SomeUtils qw(zip);
print for zip @items1, @items2;
for pair in zip(item1, item2): print(pair)
from itertools import zip_longest as z
for x in z(items1, items2): print(x)
items1.zip(items2){|pair| puts pair}
extern crate itertools;
for pair in izip!(&items1, &items2) {
    println!("{}", pair.0);
    println!("{}", pair.1);
}
(map (lambda (x)
       (display x)
       (newline))
     (foldr append '()
            (map list items1 items2)))
items1 with: items2 do: [:item1 :item2 |
  Transcript 
	showln: item1;
	showln: item2].
stream1 := items1 readStream.
stream2 := items2 readStream.
[stream1 atEnd ifFalse: [Transcript showln: stream1 next].
 stream2 atEnd ifFalse: [Transcript showln: stream2 next]]
	doWhileFalse: [stream1 atEnd or: [stream2 atEnd]].

New implementation...