Skip to content

Instantly share code, notes, and snippets.

@wdanxna
Created January 14, 2019 12:08
Show Gist options
  • Save wdanxna/85079fb90da1170b4f9f7fce583f41be to your computer and use it in GitHub Desktop.
Save wdanxna/85079fb90da1170b4f9f7fce583f41be to your computer and use it in GitHub Desktop.
reshape
fun<T> reShape(list: List<T>, vararg dims: Int): List<Any> {
fun groupBy(list: List<Any>, by: Int): List<Any> {
assert(list.size % by == 0)
val ret: MutableList<List<T>> = mutableListOf()
var j = 0
for (i in list.size downTo 1 step by) {
val o = mutableListOf<T>()
for (k in 1..by) {
o.add(list[j++] as T)
}
ret.add(o)
}
return ret
}
fun iter(list: List<Any>, dims: List<Int>): List<Any> {
if (dims.size == 1) return list
val dim = dims.last()
assert(list.size % dim == 0)
return iter(groupBy(list, dim), dims.dropLast(1))
}
return iter(list as List<Any>, dims.asList())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment