简体   繁体   中英

How to form a Third java Array from given Two String Arrays

I am writing a java code for processing of signals where I have come accross a situation as explained below:

INPUT GIVEN: String Arrays arr1 and arr2. OUTPUT REQD: String Array arr3

      String[] arr1= {"A", "c", "c",  "", "", "c", "c", "B", "", "c","c", "", "A",  "", "", "B", "B", "A"};
      String[] arr2= {"2", "3", "3",  "", "", "2", "1", "3", "", "2","3", "", "2",  "", "", "3", "2", "3"};
      String[] arr3= {"11", "",  "",  "", "", "",  "",  "8", "", "",  "", "", "2",  "", "", "3", "2", "3"};

ALGORITHM: 1. arr1 has elements of 4 types: "A", "B" and "c" and "".

  1. arr2 has some Number Strings like "2", "3" etc. at corresponding index to "A", "B" and "c" in arr1, element "" in arr1 has corresponding element "" in arr2.

  2. arr3 is to be formed from arr1 and arr2.

  3. arr3 has Number Strings only corresponding to "A", "B" elemnts in arr1.

  4. In arr3 the first Number String "11" is from the total of "2", "3", "3", "", "", "2", "1". These are the elements from "A" to "B"(including "A", excluding "B"). "8" is from the total of "3", "", "2","3", "". Next "2" is from the total of "2", "", "". At last it is clear that "3", "2", "3" are from "3", "2", "3" respectively.

    Being new comer to programming and java I need help in the above case. Thanks in anticipation.

I suggest you to declare arr2 and arr3 as int arrays, that will help you do any mathematical operations easily.

And speaking about the approach for the solution, what we can do is maintain an index common for all 3 arrays and then perform the checks on arr1 and necessary operations on arr2 and arr3.

String[] arr1 = {"A", "c", "c",  "", "", "c", "c", "B", "", "c","c", "", "A",  "", "", "B", "B", "A"};
int[] arr2 = {2, 3, 3, 0, 0, 2, 1, 3, 0, 2, 3, 0, 2, 0, 0, 3, 2, 3};

int len = arr1.length, sum=0;
int[] arr3 = new int[len];

for(int i=0; i<len; i++){
    arr3[i] = 0;
}

for(int i = 0 ; i < len ; i++ ){
    sum=0;
    if(arr1[i].equals("A") || arr1[i].equals("B")){
        sum += arr2[i];
        int j=0;
        for(j = i+1; j < len && !arr1[j].equals("A") && !arr1[j].equals("B"); j++){
            sum += arr2[j];
        }
        arr3[i] = sum;
        i= j-1 ;
    }
}

The above piece of code now fills the arr3 with necessary values you can change them to strings by using the Integer.toString() method on each of the value.

If you need any further clarifications let me know. Happy coding ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM