次のコードは、あなたが望むことをします。
#include <stdio.h>
#include <stdlib.h>
// type to encapsulate our 5 character long string
typedef char combination[5];
combination* getCombinations()
{
char letters[] = {'A','C','G','T'};
combination * combinations = (combination *)calloc(1024, sizeof(combination));
unsigned i;
unsigned int j;
for (i = 0; i < 1024; i++)
{
/*combinations[i] = &strings[i * 5];*/
for (j = 5; j--;){
combinations[i][(4 - j)] = letters[(i >> (j * 2)) % 4]; //
}
}
return combinations;
}
int main()
{
int i;
combination * combinations = getCombinations();
for (i = 0; i < 1024; i++){
printf("%.*s\n", 5, combinations[i]);
}
free(combinations);
}
重要ラインが内部ループである:
combinations[i][4 - j] = letters[(i >> (j * 2)) % 4];
この行の目的は、単純にカウントすることによって組み合わせへのインデックス(0〜1023)をオンにすることです。
はこれを打破するのをしてみましょう:
letters[... % 4]
は何でも(...
)に基づいて文字を返します。値を設定combinations[i][4 - j]
ただ、1
、5
、9
でインデックスを作る...すべてが'C'
を返す
(i >> (j * 2))
これは基本的に私たちは基本4
(可能な文字の数)で選択することができます% 4
一部
リストのi
番目の単語のj
番目の文字(右側から数えて)に移動します。私たちは、アルゴリズムを使い始める前に
私はあなたの文字列が5つの文字を含むように意図されている場合は、少なくとも* 6 *長い文字が –
再帰的な解決策があるのヌルターミネータを保持するように、文字列が必要であることを指摘しますおそらく5つのネストされたループよりも好ましいでしょう。 –
あなたは、試していない他の人のためのコードを書くことを楽しんでいると思います。 –