質問

アルファベットの繰り返しについて質問があります。 <!> quot; a <!> quot;で始まるループが必要です。 <!> quot; z <!> quot;で終わります。その後、ループが始まります<!> quot; aa <!> quot; <!> quot; az <!> quot;に数えます。その後、<!> quot; ba <!> quot;で始まります。最大<!> quot; bz <!> quot;など...

誰かが解決策を知っていますか?

ありがとう

編集:char <!> quot; a <!> quot;を与えるのを忘れました。関数に対して、関数はbを返す必要があります。 <!> quot; bnc <!> quotを指定すると、関数は<!> quot; bnd <!> quot;

を返す必要があります
役に立ちましたか?

解決

編集:OPの最新の編集が望むとおりに実行しました

これは最も簡単なソリューションであり、テスト済みです:

static void Main(string[] args)
{
    Console.WriteLine(GetNextBase26("a"));
    Console.WriteLine(GetNextBase26("bnc"));
}

private static string GetNextBase26(string a)
{
    return Base26Sequence().SkipWhile(x => x != a).Skip(1).First();
}

private static IEnumerable<string> Base26Sequence()
{
    long i = 0L;
    while (true)
        yield return Base26Encode(i++);
}

private static char[] base26Chars = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
private static string Base26Encode(Int64 value)
{
    string returnValue = null;
    do
    {
        returnValue = base26Chars[value % 26] + returnValue;
        value /= 26;
    } while (value-- != 0);
    return returnValue;
}

他のヒント

最初の努力、a-z、aa-zzのみ

public static IEnumerable<string> GetExcelColumns()
{
    for (char c = 'a'; c <= 'z'; c++)
    {
        yield return c.ToString();
    }
    char[] chars = new char[2];
    for (char high = 'a'; high <= 'z'; high++)
    {
        chars[0] = high;
        for (char low = 'a'; low <= 'z'; low++)
        {
            chars[1] = low;
            yield return new string(chars);
        }
    }
}

これは「zz」で停止することに注意してください。もちろん、ここではループに関して見苦しい重複があります。幸いなことに、これは簡単に修正できます。さらに柔軟にすることもできます。

2回目の試行:より柔軟なアルファベット

private const string Alphabet = "abcdefghijklmnopqrstuvwxyz";

public static IEnumerable<string> GetExcelColumns()
{
    return GetExcelColumns(Alphabet);
}

public static IEnumerable<string> GetExcelColumns(string alphabet)
{
    foreach(char c in alphabet)
    {
        yield return c.ToString();
    }
    char[] chars = new char[2];
    foreach(char high in alphabet)
    {
        chars[0] = high;
        foreach(char low in alphabet)
        {
            chars[1] = low;
            yield return new string(chars);
        }
    }
}

a、b、c、d、aa、ab、ac、ad、baなどを生成する場合は、GetExcelColumns("abcd")を呼び出します。

3回目の試行(さらに改訂)-無限のシーケンス

public static IEnumerable<string> GetExcelColumns(string alphabet)
{
    int length = 0;
    char[] chars = null;
    int[] indexes = null;
    while (true)
    {
        int position = length-1;
        // Try to increment the least significant
        // value.
        while (position >= 0)
        {
            indexes[position]++;
            if (indexes[position] == alphabet.Length)
            {
                for (int i=position; i < length; i++)
                {
                    indexes[i] = 0;
                    chars[i] = alphabet[0];
                }
                position--;
            }
            else
            {
                chars[position] = alphabet[indexes[position]];
                break;
            }
        }
        // If we got all the way to the start of the array,
        // we need an extra value
        if (position == -1)
        {
            length++; 
            chars = new char[length];
            indexes = new int[length];
            for (int i=0; i < length; i++)
            {
                chars[i] = alphabet[0];
            }
        }
        yield return new string(chars);
    }
}

再帰を使用するとよりクリーンなコードになる可能性がありますが、効率的ではありません。

特定のポイントで停止したい場合は、LINQを使用できます:

var query = GetExcelColumns().TakeWhile(x => x != "zzz");

<!> quot;再起動<!> quot;イテレータ

指定されたポイントからイテレータを再起動するには、softwarejediで提案されているように、実際にSkipWhileを使用できます。もちろん、それはかなり非効率的です。呼び出し間で状態を保持できる場合は、イテレーターを保持できます(どちらのソリューションでも)。

using (IEnumerator<string> iterator = GetExcelColumns())
{
    iterator.MoveNext();
    string firstAttempt = iterator.Current;

    if (someCondition)
    {
        iterator.MoveNext();
        string secondAttempt = iterator.Current;
        // etc
    }
}

別の方法として、とにかくforeachを使用するようにコードを構造化して、実際に使用できる最初の値に分割することもできます。

次は、必要な文字列をリストに追加します:

List<string> result = new List<string>();
for (char ch = 'a'; ch <= 'z'; ch++){
    result.Add (ch.ToString());
}

for (char i = 'a'; i <= 'z'; i++)
{
    for (char j = 'a'; j <= 'z'; j++)
    {
        result.Add (i.ToString() + j.ToString());
    }
}

ここにはたくさんの答えがあり、受け入れられていることはわかっていますが、IMOのおかげで、必要以上に難しくなっています。次の方が簡単でわかりやすいと思います:

static string NextColumn(string column){
    char[] c = column.ToCharArray();
    for(int i = c.Length - 1; i >= 0; i--){
        if(char.ToUpper(c[i]++) < 'Z')
            break;
        c[i] -= (char)26;
        if(i == 0)
            return "A" + new string(c);
    }
    return new string(c);
}

これは入力検証を行わないことに注意してください。発信者を信頼しない場合は、最初にIsNullOrEmptyチェックを追加し、ループの先頭にc[i] >= 'A' && c[i] <= 'Z' || c[i] >= 'a' && c[i] <= 'z'チェックを追加する必要があります。またはそのままにして、 GIGO にしてください。

これらのコンパニオン関数の使用法も見つけることができます:

static string GetColumnName(int index){
    StringBuilder txt = new StringBuilder();
    txt.Append((char)('A' + index % 26));
    //txt.Append((char)('A' + --index % 26));
    while((index /= 26) > 0)
        txt.Insert(0, (char)('A' + --index % 26));
    return txt.ToString();
}
static int GetColumnIndex(string name){
    int rtn = 0;
    foreach(char c in name)
        rtn = rtn * 26 + (char.ToUpper(c) - '@');
    return rtn - 1;
    //return rtn;
}

これらの2つの関数はゼロベースです。つまり、<!> quot; A <!> quot; = 0、<!> quot; Z <!> quot; = 25、<!> quot; AA <!> quot; = 26など。それらを1ベースにする(ExcelのCOMインターフェイスのように)には、各関数のコメント行の上の行を削除し、それらの行のコメントを解除します。

NextColumn関数と同様に、これらの関数は入力を検証しません。両方とも、それが彼らが得るものであるなら、あなたにゴミを与えます。

ここ<!>#8217; sが思いついたものです。

/// <summary>
/// Return an incremented alphabtical string
/// </summary>
/// <param name="letter">The string to be incremented</param>
/// <returns>the incremented string</returns>
public static string NextLetter(string letter)
{
  const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  if (!string.IsNullOrEmpty(letter))
  {
    char lastLetterInString = letter[letter.Length - 1];

    // if the last letter in the string is the last letter of the alphabet
    if (alphabet.IndexOf(lastLetterInString) == alphabet.Length - 1) 
    {
        //replace the last letter in the string with the first leter of the alphbat and get the next letter for the rest of the string
        return NextLetter(letter.Substring(0, letter.Length - 1)) + alphabet[0];
    }
    else 
    {
      // replace the last letter in the string with the proceeding letter of the alphabet
      return letter.Remove(letter.Length-1).Insert(letter.Length-1, (alphabet[alphabet.IndexOf(letter[letter.Length-1])+1]).ToString() );
    }
  }
  //return the first letter of the alphabet
  return alphabet[0].ToString();
}

ちょっと好奇心が強い、どうして

    private string alphRecursive(int c) {
         var alphabet = "abcdefghijklmnopqrstuvwxyz".ToCharArray();
         if (c >= alphabet.Length) {
             return alphRecursive(c/alphabet.Length) + alphabet[c%alphabet.Length];
         } else {
             return "" + alphabet[c%alphabet.Length];
         }
    }

これは、10進数の代わりに26進数のみを使用してintを表示するようなものです。次のアルゴリズムを試して、配列のn番目のエントリを見つけてください

q = n div 26;
r = n mod 26;
s = '';
while (q > 0 || r > 0) {
  s = alphabet[r] + s;
  q = q div 26;
  r = q mod 26;
}

もちろん、最初のn個のエントリが必要な場合、これは最も効率的なソリューションではありません。この場合、ダニエルのソリューションのようなものを試してください。

これを試してこれを思いついた:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Alphabetty
{
    class Program
    {
        const string alphabet = "abcdefghijklmnopqrstuvwxyz";
        static int cursor = 0;
        static int prefixCursor;
        static string prefix = string.Empty;
        static bool done = false;
        static void Main(string[] args)
        {
            string s = string.Empty;
            while (s != "Done")
            {
                s = GetNextString();
                Console.WriteLine(s);
            }
            Console.ReadKey();

        }        
        static string GetNextString()
        {
            if (done) return "Done";
            char? nextLetter = GetNextLetter(ref cursor);
            if (nextLetter == null)
            {
                char? nextPrefixLetter = GetNextLetter(ref prefixCursor);
                if(nextPrefixLetter == null)
                {
                    done = true;
                    return "Done";
                }
                prefix = nextPrefixLetter.Value.ToString();
                nextLetter = GetNextLetter(ref cursor);
            }

            return prefix + nextLetter;
        }

        static char? GetNextLetter(ref int letterCursor)
        {
            if (letterCursor == alphabet.Length)
            {
                letterCursor = 0;
                return null;
            }

            char c = alphabet[letterCursor];
            letterCursor++;
            return c;
        }
    }
}

これは、私が作成したもので、似ているものがあります。可能な限り小さな番号付けスキーマを設計するために反復カウントを試していましたが、十分な一意性が得られました。

アルファ文字を追加するたびに可能性が26倍になることはわかっていましたが、使用する文字、数字、またはパターンの数がわかりませんでした。

それで、次のコードに導かれました。基本的に、AlphaNumber文字列を渡すと、Letterを持つすべての位置が最終的に<!> quot; z \ Z <!> quotに増分されます。番号があったすべての位置は、最終的に<!> quot; 9 <!> quot;に増加します。

つまり、2つの方法のいずれかで呼び出すことができます。

//This would give you the next Itteration... (H3reIsaStup4dExamplf)
string myNextValue = IncrementAlphaNumericValue("H3reIsaStup4dExample") 

//Or Loop it resulting eventually as "Z9zzZzzZzzz9zZzzzzzz"
string myNextValue = "H3reIsaStup4dExample"
while (myNextValue != null)
{
   myNextValue = IncrementAlphaNumericValue(myNextValue)
   //And of course do something with this like write it out
}

(私にとっては、<!> quot; 1AA000 <!> quot;のようなことをしていました)

public string IncrementAlphaNumericValue(string Value)
    {
        //We only allow Characters a-b, A-Z, 0-9
        if (System.Text.RegularExpressions.Regex.IsMatch(Value, "^[a-zA-Z0-9]+$") == false)
        {
            throw new Exception("Invalid Character: Must be a-Z or 0-9");
        }

        //We work with each Character so it's best to convert the string to a char array for incrementing
        char[] myCharacterArray = Value.ToCharArray();

        //So what we do here is step backwards through the Characters and increment the first one we can. 
        for (Int32 myCharIndex = myCharacterArray.Length - 1; myCharIndex >= 0; myCharIndex--)
        {
            //Converts the Character to it's ASCII value
            Int32 myCharValue = Convert.ToInt32(myCharacterArray[myCharIndex]);

            //We only Increment this Character Position, if it is not already at it's Max value (Z = 90, z = 122, 57 = 9)
            if (myCharValue != 57 && myCharValue != 90 && myCharValue != 122)
            {
                myCharacterArray[myCharIndex]++;

                //Now that we have Incremented the Character, we "reset" all the values to the right of it
                for (Int32 myResetIndex = myCharIndex + 1; myResetIndex < myCharacterArray.Length; myResetIndex++)
                {
                    myCharValue = Convert.ToInt32(myCharacterArray[myResetIndex]);
                    if (myCharValue >= 65 && myCharValue <= 90)
                    {
                        myCharacterArray[myResetIndex] = 'A';
                    }
                    else if (myCharValue >= 97 && myCharValue <= 122)
                    {
                        myCharacterArray[myResetIndex] = 'a';
                    }
                    else if (myCharValue >= 48 && myCharValue <= 57)
                    {
                        myCharacterArray[myResetIndex] = '0';
                    }
                }

                //Now we just return an new Value
                return new string(myCharacterArray);
            } 
        }

        //If we got through the Character Loop and were not able to increment anything, we retun a NULL. 
        return null;  
    }

再帰を使用した私の試み:

public static void PrintAlphabet(string alphabet, string prefix)
{
    for (int i = 0; i < alphabet.Length; i++) {
        Console.WriteLine(prefix + alphabet[i].ToString());
    }

    if (prefix.Length < alphabet.Length - 1) {
        for (int i = 0; i < alphabet.Length; i++) {
            PrintAlphabet(alphabet, prefix + alphabet[i]);
        }
    }
}

次に、単にPrintAlphabet("abcd", "")を呼び出します;

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top