java - How do I deal with a character array in my homework? -


given 2 character arrays a[] , b[], remove b[] occurrences of characters occur in array a[]. need in-place i.e. without using array of characters. e.g.:

input: a[] = [‘g’, ‘o’]           input  b[] = [‘g’, ’o’, ’o’, ’g’, ’l’, ’e’]   output: b[] = [‘l’, ‘e’] 

code :

public class replacecharacterarray{                 public static void main(string args[]){                   char a[] = [‘g’, ‘o’]                    char b[] = [‘g’, ’o’, ’o’, ’g’, ’l’, ’e’]                //to replace occurences of characters of               //a[] array in b[] array have below logic.                 for(int i=0;i<a.length;i++){                   for(int j=0;j<b.length;j++){                        if(b[j] == a[i]){                          //im stuck here how proceed                    }                }     

you can't remove elements "in place" in java arrays. have fixed length. is, in example you'll have return new array, since can't change length of b array.

here pointers you:

  • maintain write-index b array (left of index, have characters not present in a).
  • iterate through b array
  • while current character contained in a, step forward
  • swap current character (not contained in a) character @ write-index
  • increment write-index, , continue there.

use instance arrays.copyofrange return part of array left of write-index.


regarding update:

  • arrays not written using [ , ] , characters not written using , change them {, } , '.
  • having helper method signature boolean arraycontains(char[] arr, char c) make easier write algorithm
  • if follow approach, benefit having helper method void swap(char[] arr, int index1, int index2).

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -