7
I’m trying to create a simple permutation algorithm where you pass any number for example 123 and it should return the largest number without repeating. I tried something like this more when I pass 4242 it does not return me 4422 and yes 4242 as higher.
static void ComparacoesPossiveis(ref int entrada, out int saida)
{
saida = 1;
for (int i = 1; i <= entrada; i++)
{
saida *= i;
}
}
public static void teste(int number)
{
if (number >= 10000000)
{
Console.WriteLine(-1);
Console.ReadKey();
return;
}
var array = number.ToString().ToArray();
int tamanhoArray = array.Length;
int[] vetor = new int[tamanhoArray];
int[] temp = new int[tamanhoArray];
int[] vetTmp = new int[tamanhoArray];
for (int i = 0; i < tamanhoArray; i++)
{
vetor[i] = Convert.ToInt32(array[i].ToString());
}
int y, x;
y = vetor.Length;
ArrayList combinacoes = new ArrayList();
ComparacoesPossiveis(ref y, out x);
while (x > 0)
{
for (int j = 0; j < y - 1; j++)
{
string numero = "";
vetTmp[j] = vetor[j];
vetor[j] = vetor[j + 1];
vetor[j + 1] = vetTmp[j];
for (int i = 0; i < vetor.Length; i++)
numero += vetor[i].ToString();
combinacoes.Add(Convert.ToInt32(numero));
}
x -= y;
}
combinacoes.Sort();
Console.WriteLine("O maior numero é " + combinacoes[combinacoes.Count - 1].ToString());
Console.ReadKey();
}
Smart! When you find the right question for the problem you want to find the solution, it usually becomes simple. The problem, if we don’t think about permutations becomes easier to solve.
– ramaral
So, I don’t know. It may be that he really wanted to do the permutations. But it has no natural reason to complicate. It could be by artificialism. Then the question should state what you cannot use, and what you must do. Since you don’t have it, and the code was already in place, I was on that wave. If I had to permute by definition, I’d still be able to simplify the code being started. How much I don’t know, because there is no parameter of what you can use or not. For example, you can use conversion anointing (string -> int -> string) or you have to do it in your hand?
Sort
?– Maniero
Yes, we do not know what was the purpose of the exercise, the most certain would be to have to calculate the possible permutations and then find the one that represents the largest number. Not knowing this, your answer intelligently solves the problem. (Understand that I am praising and not criticizing)
– ramaral
I think you do not need to calculate anything intermediate, if you are asking for the result. How to arrive at the greatest number is detail. Unless the definition imposes something. Don’t worry, I know it’s not critical. Even if it was, no problem. Don’t think any comment is a problem. It’s just complementary information.
– Maniero