Date: 03/19/07 (Code WTF) Keywords: security Когда читаешь код в статьях, обычно ожидаешь увидить вылизаный код. Однако бывают примеры когда не понимаешь, как код прошел редактора. Очень странный кусок кода я нашел в статье на MSDN Using Permutations in .NET for Improved Systems Security. Этот пример напомнил мне анекдот про чайник (вресия про програмистов). Пример из статьи:
public Permutation(int n, int k)
{
this.data = new int[n];
this.order = this.data.Length;
// Step #1 - Find factoradic of k
int[] factoradic = new int[n];
for (int j = 1; j <= n; ++j)
{
factoradic[n-j] = k % j;
k /= j;
}
// Step #2 - Convert factoradic to permuatation
int[] temp = new int[n];
for (int i = 0; i < n; ++i)
{
temp[i] = ++factoradic[i];
}
this.data[n-1] = 1; // right-most element is set to 1.
for (int i = n-2; i >= 0; --i)
{
this.data[i] = temp[i];
for (int j = i+1; j < n; ++j)
{
if (this.data[j] >= this.data[i])
++this.data[j];
}
}
for (int i = 0; i < n; ++i) // put in 0-based form
{
--this.data[i];
}
} // Permutation(n,k)
Очевидно, что добавление единицы и последующее вычитание являются избыточными, и код мог бы быть записан способом, указаным ниже. Так же, после инициализации temp, массивы temp и factoradic имеют одинаковые значения элементов. Так что, непонятно зачем temp создавался.
public Permutation(int n, int k)
{
this.data = new int[n];
this.order = this.data.Length;
// Step #1 - Find factoradic of k
int[] factoradic = new int[n];
for (int j = 1; j <= n; ++j)
{
factoradic[n-j] = k % j;
k /= j;
}
// Step #2 - Convert factoradic to permuatation
this.data[n-1] = 0; // right-most element is set to 0.
for (int i = n-2; i >= 0; --i)
{
this.data[i] = factoradic[i];
for (int j = i+1; j < n; ++j)
{
if (this.data[j] >= this.data[i])
++this.data[j];
}
}
} // Permutation(n,k)
Source: http://community.livejournal.com/code_wtf/73670.html
|