Adding two character arrays and storing the result as characters in another char array in Java

I want to add two character arrays and store the result as characters in another character array. The addition involves adding two English letters from the two arrays as operands. The addition will be wrapped around z back.

eg. Input is Array1 and Array 2 and output is Array 3

Array 1: abcdeyz

Array 2: aaaaaaa

Array 3: bcdefza

Below is the part of my code that doesn't work. Please suggest any changes

    int c = 0;

    char array3[] = new char[count] ;    

for(int a=0;a<array1.length;a++)
    {
        for(int b=0;b<array2.length;b++)
        {
            int temp = (array1[a] + array2[b]) % 26 ;
            array3[c] = (char) temp ; 
            c++ ;
        }
    }

      

+3


source to share


4 answers


This is a fixed and working example of how to do it:

public static void main(String[] args) {
    char[] array1 = new char[] {'a', 'b', 'c', 'd', 'e', 'y', 'z'};
    char[] array2 = new char[] {'a', 'a', 'a', 'a', 'a', 'a', 'a'};
    char[] array3 = new char[array1.length];

    for (int i = 0; i < array1.length; i++) {
      array3[i] = toChar((toInt(array1[i]) + toInt(array2[i]) + 1) % 26);
    }
    System.out.println(Arrays.toString(array3));
}

private static int toInt(char chr) {
    return chr - 'a';
}

private static char toChar(int value) {
    return (char)(value + 'a');
}

      



There are some thoughts to notice here (apart from part - 'a'

, the rest of the answers have already been mentioned):

  • you only need one loop for this task. If you are using 2 nested loops, you will be adding each letter array1

    with each letter array2

    . And you will be bigger array3

    . And since the result does not match the desired result ... :)

  • + 1

    c is toInt(array2[i]) + 1

    necessary because it char - 'a'

    is "zero-based". So 'a' + 'b'

    will result in 'b'

    , not 'c'

    because you will compute 0 + 1

    (which will 'b'

    if you "convert" it back to char by adding 'a'

    ) (I hope this is clear: D)

  • needs to array2

    be at least the same length as 'array1'. It's almost like an addition to cryptography . (I missed part of the padding to keep this code short)

+1


source


Hint - 'a' value is not 0

The problem is on the line -

int temp = (array1[a] + array2[b]) % 26 ;

      



Here is the modified code (assuming all characters are lowercase) -

    int c = 0;

    char array3[] = new char[count] ;    

for(int a=0;a<array1.length;a++)
    {
        for(int b=0;b<array2.length;b++)
        {
            int temp = ( (array1[a]-'a') + (array2[b]-'a')) % 26 ;
            array3[c] = (char) (temp+'a') ; 
            c++ ;
        }
    }

      

+2


source


Modulo 26 is a good way to handle the az-1-26 transformation. This way, your program can be agnostic about the actual ASCII character numbers.

Some other problems:

  • Case insensitive . I would recommend converting your emails to lowercase before processing them.
  • Handling exceptional cases . What if your arrays are of different lengths? Or what if they have a character that is not a letter?

The following code is one way to deal with these things.

public static int letterToInt(char letter) {
    char letterToConvert = Character.toLowerCase(letter);
    int codeForA = (int)'a';
    int numberOfLetter = ((int)letterToConvert) - codeForA + 1;
    if(numberOfLetter < 1 || numberOfLetter > 26) {
        throw new IllegalArgumentException(
                "The character argument can only be a-z or A-Z, but was '" + letter + "'");
    }
    return numberOfLetter;
}

public static char intToLetter(int number) {
    if(number < 1 || number > 26) {
        throw new IllegalArgumentException(
                "The number can only be 1-26, but was " + number);
    }
    int codeForA = (int)'a';
    return (char)(codeForA + number - 1);
}

public static char addLetters(char letter1, char letter2) {
    int numberFromAddedLetters =
            letterToInt(letter1) + letterToInt(letter2);
    int modulo = numberFromAddedLetters % 26;
    return intToLetter(modulo == 0 ? 26 : modulo);
}

public static char[] addLetterArrays(char[] array1, char[] array2) {
    char[] longerArray;
    char[] shorterArray;
    if(array1.length >= array2.length) {
        longerArray = array1;
        shorterArray = array2;
    } else {
        longerArray = array2;
        shorterArray = array1;
    }

    char[] addedLetters = new char[longerArray.length];
    for(int index = 0; index < longerArray.length; index++) {
        if(index < shorterArray.length) {
            addedLetters[index] = addLetters(longerArray[index], shorterArray[index]);
        } else {
            addedLetters[index] = longerArray[index];
        }
    }
    return addedLetters;
}

// Test it out
public static void main(String[] args) {
    char[] letters1 = "abcdeyz".toCharArray();
    char[] letters2 = "aaaaaaa".toCharArray();
    // Prints [b, c, d, e, f, z, a]
    System.out.println(Arrays.toString(addLetterArrays(letters1, letters2)));
}

      

+2


source


Write this:

int temp = (((array1[a] - 'a') + (array2[b] - 'a')) % 26) + 'a';

      

what it does is convert both characters to the appropriate place in the alphabet, do modulo the number of characters in the alphabet for a wrapping effect, and convert back to the correct ascii value.

Note that your code was in trouble because you acted as if the values โ€‹โ€‹of the ascii alphabet were their respective places in the alphabet itself, which is not correct.

+1


source







All Articles