2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Scalaでリストをランダムに並び替えたり、互い違いに編みこんだり

2
Last updated at Posted at 2015-01-17

どちらも適当なタプルを作ってから並び替えています。もっといい方法があったら教えて下さいませ。

リストをランダムに並び替え

  val random = new Random()
  def shuffle[T](objects: Seq[T]): Seq[T] = objects.map((_, random.nextInt())).sortWith((a, b) => a._2 < b._2).map(_._1)

2015/01/19追記:コメント欄で教えていただきましたが、以下の標準メソッドでランダムな並び替えはできました。

scala.util.Random.shuffle(objects)

リストを互い違いに編みこみ

  /**
   * Weaves sequences.
   * e.g.
   * val l1 = Seq(1,2,3)
   * val l2 = Seq(500,600,700)
   * val l3 = weave(l1,l2)
   * // l3 == Seq(1,500,2,600,3,700)
   * @param objects
   * @tparam T the type of the elements.
   * @return a new sequence resulting from weaving all element sequences.
   */
  def weave[T](objects: Seq[T]*): Seq[T] = {
    val all:Seq[(T, Int, Int)] = objects.zipWithIndex.map { case (list, i) => zipWithIndexAndPriority(list, i)}.flatten
    all.sortWith((a, b) => if (a._2 == b._2) a._3 < b._3 else a._2 < b._2).map(_._1)
  }

  private def zipWithIndexAndPriority[T](objects: Seq[T], priority: Int): Seq[(T, Int, Int)] = objects.zipWithIndex.map { case (o, i) => (o, i, priority)}
2
2
3

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?