문제 ]
Input Format
integers contained in the list, each on a separate line.
Output Format
Output the list with the integers at odd positions removed i.e. the first element, the third element and so on. The relative positions of the remaining even-position elements should be the same as they were in the original array. Each integer will be on a separate line.
NOTE: By odd positions, we mean the first, third, fifth, etc position of the array needs to be filtered out. As per programming language conventions, these might (and they often do) correspond to indices and so on.
Sample Input
2
5
3
4
6
7
9
8
Sample Output
5
4
7
8
제출 ]
def f(arr:List[Int]):List[Int] = {
arr.tail.iterator.sliding(1, 2).toList.flatten
//arr.view.zipWithIndex.filter(_._2 % 2 != 0).map(_._1).force.toList
}
풀이 ]
arr.tail.iterator.sliding(1, 2).toList.flatten
iterator의 함수 sliding을 이용해 리스트의 짝수 인덱스 값을 구분한다.
def sliding[B >: A](size: Int, step: Int = 1): GroupedIterator[B]
예시)
// Returns List(ArraySeq(1, 2, 3), ArraySeq(2, 3, 4), ArraySeq(3, 4, 5)) (1 to 5).iterator.sliding(3).toList
// Returns List(ArraySeq(1, 2, 3, 4), ArraySeq(4, 5)) (1 to 5).iterator.sliding(4, 3).toList
// Returns List(ArraySeq(1, 2, 3, 4)) (1 to 5).iterator.sliding(4, 3).withPartial(false).toList
첫번째 인자는 뽑을 갯수, 두번째 인자는 각 인덱스 마다 건널 뛸 값을 말한다.
리턴 값이 Iterator므로 toList로 형변환 후, flatten함수로 하나의 리스트를 만든다.
예시)
val xs = List( Set(1, 2, 3), Set(1, 2, 3) ).flatten // xs == List(1, 2, 3, 1, 2, 3) val ys = Set( List(1, 2, 3), List(3, 2, 1) ).flatten // ys == Set(1, 2, 3)
다른 풀이법으로 는
arr.view.zipWithIndex.filter(_._2 % 2 != 0).map(_._1).force.toList
가 있다.
댓글 없음:
댓글 쓰기