LoginSignup
2

More than 5 years have passed since last update.

負の索引を持った配列を定義したいっ!

Last updated at Posted at 2016-10-03

背景

EditGraphの最短距離を計算したくなりました。
えーそりゃぁもー突然に…

MyersさんやらWuさんやらのアルゴリズムを実装すれば良いです。実装サンプルや解説サイトは簡単に見つかります。
でも、ここ等辺で解説されているのは例えば-Dから+Dまでの索引を持った作業エリアを使ったりするのですが、プログラムで表現する際は、まぁ当然のようにオフセットを掛けて0~2*Dの範囲をアクセスしている訳です。

いや、全く問題ありません。
それで良いじゃないですか。

良いんですけどぉ、マイナス索引でアクセスできるArrayってのがあっても良いかなぁ…
なんて。

方針

  • Collection系は何となく重いような気もするんで、あくまでもSystem.Array系で実装したいかなぁ
  • System.Arrayをサブクラス化しても何ともならん気がするので、ラッパする感じで行きましょう
  • となると、Arrayと同等に扱うにはICloneable, IList, ICollection, IEnumerable等をインタフェース継承するのが良いんでしょうけど、とてもめんどくさいのでforeachできれば良いよね、位のノリで…

実装

で、こんな感じで…

public class VArray<T> {
    public VArray(int LBound, int UBound) {
        array = new T[UBound - LBound + 1];
        this.LBound = LBound;
        this.UBound = UBound;
    }

    T[] array;

    public int Length { get { return array.Length; } }
    public T this[int index] {
        get { return array[index - LBound]; }
        set { array[index - LBound] = value; }
    }
    public int LBound { get; private set; }
    public int UBound { get; private set; }
    public IEnumerator<T> GetEnumerator() {
        foreach (T item in array)
            yield return item;
    }
}

使い方はこんな感じ。

VArray<int> array = new VArray<int>(-5, 5);

for(int i=-5; i<=5; i++)
    array[i] = i;

foreach(int item in array)
    Console.WriteLine(item);

これで、11個のitemWriteLineされてきます。


ま、どれだけ役に立つかは微妙ですけどね。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2