No Programming, No Life

プログラミング関連の話題や雑記

Re:エレベータの制御(基本編)

お題: Server error
投稿: Server error

エレベータシミュレーションは楽しいですね。

考察

今回投稿したコードの、待っている人がいる最上階を探すための

// 待っている人がいる最上階を探す
  def nextList = []
  elev.floors.tail()*.persons.eachWithIndex{ item, idx ->
    nextList << [idx+1, item]
  }
  def topFloor = nextList.findAll{ it[1] != 0 }.last()[0]

の部分がGroovy的なコードとしては効率が悪いな。
なんとかならんだろうか。

これ、要するに


[3, 4, 0, 0]

のようなリストの4のindex(後ろから見て最初に0でなくなる値のindex)を取得したいだけなんですが、一回、

[ [1, 3], [2, 4], [3, 0], [4, 0] ]

のような[index, 元の値]みたいなリストにしてから目的の値を探しています。

追記(2009-01-15)

Groovyでzip - lottzの日記にまさにこの問題を解決する答えがありました。
上記例の場合、

assert [[1, 3], [2, 4], [3, 0], [4, 0]] == [[1, 2, 3, 4], [3, 4, 0, 0]].transpose()
ということで、transpose版はこんな感じかな?
// fumokmm 2009-01-15 Update
//  def nextList = []
//  elev.floors.tail()*.persons.eachWithIndex{ item, idx ->
//    nextList << [idx+1, item]
//  }
//  def topFloor = nextList.findAll{ it[1] != 0 }.last()[0]
  def topFloor = [
    (1..elev.floors.tail()*.persons.size()) as List,
    elev.floors.tail()*.persons
  ].transpose().findAll{ it[1] != 0 }.last()[0]
// fumokmm 2009-01-15 Update

うん、一行ですっきり。