On Wednesday, 20 July 2022 at 09:18:29 UTC, anonymouse wrote:
Given an array of arbitrary dimensions, I would like to accomplish three things: 1) verify that it is rectangular (e.g. all elements have the same length, all sub-elements have the same length, etc.)
        2) flatten and return the flattened copy
        3) transpose and return the transposed copy

Yesterday, I published an example of a lesson we developed with Ali. It's same `transpose()` when I add extra `swap()` for you. I hope it works for you.

```d
import std.stdio;

struct Arrayish(T) {
  T[] element;
  size_t row, column;

  this(size_t row, size_t column) {
    this.element = new T[row * column];
    this.row = row;
    this.column = column;
  }

  ref T opIndex(size_t row, size_t column) {
    size_t first = row * this.column;
    size_t index = first + column;

    return element[index];
  }

  auto opCast(R : T[][])() {
    T[][] d;
    foreach(i; 0..row)
      d ~= slice(i);
    return d;
  }

  auto slice(size_t i) {
    size_t n = i * column;
    return element[n..n + column];
  }

  @property {
    auto length() {
      return row * column;
    }

    auto dup() {
      T[][] d;
      foreach(i; 0..row)
        d ~= slice(i).dup;
      return d;
    }
    void swap() {
      auto tmp = row;
      row = column;
      column = tmp;
    }
  }
}

enum { row = 2, col = 4 }

void main() {
  auto arrayish = Arrayish!int(row, col);

  foreach(r; 0..row) {
    foreach(c; 0..col) {
      const value = r * 1000 + c;
      arrayish[r, c] = value;
    }
  }
  //arrayish.swap();
  const array = cast(int[][])arrayish;
  arrayish[1, 0] = 100;
  typeid(array).writeln(": ", array.length);
  array.writefln!"%(%s\n%)";

  arrayish.length.writeln(" total items");
  
  auto arrayCopy = arrayish.dup;
  arrayish[1, 0] = 1000;
  typeid(arrayCopy).writeln(": ", array.length);
  arrayCopy.writefln!"%(%s\n%)";
}
```

SDB@79

Reply via email to