// bench_array.ce — array operation benchmark
// Tests: sequential access, push/build, index write, sum reduction, sort

var time = use('time')

def size = 100000

// 1. Build array with push
function bench_push() {
  var a = []
  var i = 0
  for (i = 0; i < size; i++) {
    a[] = i
  }
  return length(a)
}

// 2. Index write into preallocated array
function bench_index_write() {
  var a = array(size, 0)
  var i = 0
  for (i = 0; i < size; i++) {
    a[i] = i
  }
  return a[size - 1]
}

// 3. Sequential read and sum
function bench_seq_read() {
  var a = array(size, 0)
  var i = 0
  for (i = 0; i < size; i++) {
    a[i] = i
  }
  var s = 0
  for (i = 0; i < size; i++) {
    s = s + a[i]
  }
  return s
}

// 4. Reverse array in-place
function bench_reverse() {
  var a = array(size, 0)
  var i = 0
  for (i = 0; i < size; i++) {
    a[i] = i
  }
  var lo = 0
  var hi = size - 1
  var tmp = 0
  while (lo < hi) {
    tmp = a[lo]
    a[lo] = a[hi]
    a[hi] = tmp
    lo = lo + 1
    hi = hi - 1
  }
  return a[0]
}

// 5. Nested array access (matrix-like, 300x300)
function bench_matrix() {
  def n = 300
  var mat = array(n, null)
  var i = 0
  var j = 0
  for (i = 0; i < n; i++) {
    mat[i] = array(n, 0)
    for (j = 0; j < n; j++) {
      mat[i][j] = i * n + j
    }
  }
  // sum diagonal
  var s = 0
  for (i = 0; i < n; i++) {
    s = s + mat[i][i]
  }
  return s
}

// 6. filter-like: count evens
function bench_filter_count() {
  var a = array(size, 0)
  var i = 0
  for (i = 0; i < size; i++) {
    a[i] = i
  }
  var count = 0
  for (i = 0; i < size; i++) {
    if (a[i] % 2 == 0) {
      count = count + 1
    }
  }
  return count
}

function run(name, fn) {
  var start = time.number()
  var result = fn()
  var elapsed = time.number() - start
  var ms = whole(elapsed * 100000) / 100
  log.console(`  ${name}: ${ms} ms  (result: ${result})`)
}

log.console("=== Array Benchmark ===")
log.console(`  size: ${size}`)
run("push         ", bench_push)
run("index_write  ", bench_index_write)
run("seq_read_sum ", bench_seq_read)
run("reverse      ", bench_reverse)
run("matrix_300   ", bench_matrix)
run("filter_count ", bench_filter_count)
