Given two numbers A and B, creates a third C by mixing the first two alternately?

Asked

Viewed 724 times

2

Given two integers A and B, create a third integer C by following the following rules:

  • The first number of C is the first number of A;
  • The second number of C is the first number of B;
  • The third number of C is the second number of A;
  • The fourth number of C is the second number of B;

So in a row...

  • If the numbers of A or B are of different sizes, complete C with the rest of the larger integer numbers. Ex: A = 10256, B = 512, C should be 15012256.
  • If C is greater than 1,000,000, return -1

Develop an algorithm that meets all the above requirements.

Code proposed as response:

public class ManipulacaoNumerica {

public static void GerarC(String a, String b) {

    if (a != null && b != null) {

        StringBuilder c = new StringBuilder();
        System.out.println("Valores de Entrada: " + a + " - " + b);
        int i = 0;
        int j = 0;

        loop: for (; i <= a.length();) {
            System.out.println(i);
            int proxi = i + 1;
            if (proxi <= a.length()) {
                c.append(a.substring(i, proxi)).toString();
            }
            i++;

            for (; j <= b.length();) {
                System.out.println(j);
                int proxj = j + 1;
                if (proxj <= b.length()) {
                    c.append(b.substring(j, proxj)).toString();
                }
                j++;

                continue loop;

            }
        }
        try{
            int valor = Integer.valueOf(c.toString());
            if (valor < 1000000) {
                System.out.println("Valor de Saída: " + c);
            } else {
                valor = -1;
                System.out.println("Número maior que 1.000.000:" + valor);
            }
        }catch (Exception e) {
            // TODO: handle exception
            int valor = -1;
            System.out.println("Ocorreu um erro na aplicação: "+ e +" o valor de c é: "+valor);
        }
    }
}

public static void Executa(String a, String b) {

    if(a.length() > b.length()){
        GerarC(a,b);
    }else{
        GerarC(b,a);
    }

}

public static void main(String[] args) {

    Executa("24", "1999");

}

}

Is this code really bad? What can be improved?

1 answer

3


It’s not that it’s too bad, but it can be better. Some things are a matter of taste, others have more relevance. There is case that can be bad in a more complex application, but in something simple it does not matter if it is well done or not.

Looking over it seems more interesting to use one for each than a for to scan the texts. But if it is to use the for that at least use it the way it was thought and put the increment inside it and not in the body of the block.

That one continue loop; It doesn’t make any sense. I actually think it’s unnecessary to have two ties, although I understand why they were created separately, only you don’t have to since you’re using for. You can walk both strings simultaneously in the same loop.

I find it an exaggeration to use StringBuilder for so few characters. But it is not wrong to use. In larger cases I would use.

Capture Exception It’s not usually an idea. I don’t even know if there is a need for this exception. I prefer to avoid exceptions by analyzing the data before it occurs. It has several advantages in this.

I don’t see the need for that Executa(). Until the GerarC() is questionable, but may be useful. I’ll leave because there may be a reason not described in the question.

Some will say that it is bad to mix the screen with the calculation, that it would be better to have separation of responsibilities. Of course it depends on the objective. I gave it a separate one, so I left the methods separate.

The code does not strictly do what is stated. It has logic errors. The statement is not good, it does not define everything that can occur. I invented something, even for simplicity.

Organizing a little more code helps too.

I would do something like this:

import java.lang.Math;

class ManipulacaoNumerica {
    public static int GerarC(String a, String b) {
        if (a == null || b == null) return -2; //inventei isso, não sei o que deveria fazer
        String c = "";
        int limite = Math.max(a.length(), b.length());
        for (int i = 0; i <= limite; i++) {
            if (i < a.length()) c += a.charAt(i);
            if (i < b.length()) c += b.charAt(i);
        }
        return c.length() > 6 ? -1 : Integer.valueOf(c.toString()); //inventei,é quase isso
    }

    public static void Executa(String a, String b) {
        System.out.println("Valores de Entrada: " + a + " - " + b);
        System.out.println("Valor de Saída: " + GerarC(a, b));
    }

    public static void main(String[] args) {
        Executa("24", "1999");
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Without words to thank the analysis made, I feel that when we get lost in the middle of the way we need to seek a light, and this is a great place to find the right path again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.