Skip to content

Instantly share code, notes, and snippets.

@masahitojp
Created August 21, 2014 17:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save masahitojp/9facff894f99a606d417 to your computer and use it in GitHub Desktop.
Save masahitojp/9facff894f99a606d417 to your computer and use it in GitHub Desktop.
package me.masahito
import scala.annotation.tailrec
object Main {
def getConsecutiveIndexes[T](t: (List[T], List[T])): List[Int] = {
pullConsecutiveNumbers(getSameElementsIndexList(t))
}
def getSameElementsIndexList[T] (t: (List[T], List[T])): List[Int] = {
{0 to (t._1.zip(t._2).size -1)}.filter(i => t._1(i) == t._2(i)).toList
}
@tailrec
private def pullConsecutiveNumbersRecursive(list: List[Int], last:Int ,acc:List[Int]) : List[Int] = {
if(list.head - last == 1) pullConsecutiveNumbersRecursive(list.tail, list.head, list.head :: acc)
else acc.reverse
}
def pullConsecutiveNumbers(list:List[Int]): List[Int] = {
pullConsecutiveNumbersRecursive(list.tail, list.head, List(list.head) )
}
package me.masahito
import org.scalatest.FunSuite
/**
* Created by masahito on 2014/08/22.
*/
class MainTest extends FunSuite {
test("get match index list") {
val a = (List(1,2,3,4,5), List(1,2,3,5,5))
assert(Main.getSameElementsIndexList(a) === List(0,1,2,4))
}
test("empty list") {
val a = (List.empty[Int], List.empty[Int])
assert(Main.getSameElementsIndexList(a) === List.empty[Int])
}
test("pullConsecutiveNumbers") {
val a = List(1,2,3,4,6)
assert(Main.pullConsecutiveNumbers(a) === List(1,2,3,4))
}
test("lsit match + pullConsecutiveNumbers") {
val a = (List(1,2,3,4,5), List(1,2,3,5,5))
assert(Main.pullConsecutiveNumbers(Main.getSameElementsIndexList(a)) === List(0,1,2))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment