Finding the index numbers of an array of similiar Strings

Hi,

I have an array of strings that looks like, {"a","b","d","c","c","e","f","c"}

How can I create an Integer array that can list all the index values of the String array member, c (like {3,4,7})?

It would be great if someone can help me with this! Many thanks in Advance :)

Answers

  • edited December 2015

    well, you need one array for each character / String, right?

    Look at hashMap please

    it's one hashMap for all characters / Strings

    I think you could use the String "c" e.g. as the input and the Array {3,4,7} as output of the hashMap (at the position "c" in the hashmap)

  • //  https : // forum.processing.org/two/discussion/14188/finding-the-index-numbers-of-an-array-of-similiar-strings#latest
    
    //  list all the index values of the String array member, c (like {3,4,7})?
    
    import java.util.Map;
    
    String[] source= {"a", "b", "d", "c", "c", "e", "f", "c"};
    
    // Note the HashMap's "key" is a String and "value" is an int array 
    HashMap <String, int[] > hm = new HashMap<String, int[]>();
    
    void setup() {
      size(300, 300);
    
      // Putting key-value pairs in the HashMap
      setupArrays();
    
      // Using an enhanced loop to interate over each entry
      for (Map.Entry me : hm.entrySet()) {
        print(me.getKey() + " is ");
        printArray(me.getValue());
      }
    
      // We can also access values by their key
      int[] val = null;
      val=hm.get("c");
      if (val!=null) {
        println("\n==================\n now show c : ");
        printArray(val);
      }//if
    }//func
    
    void draw() {
      // empty
    }
    
    void setupArrays() {
      int i=0;
      // looping over the entire source array
      for (String currentString : source) {
    
        // did we have the letter already?
        if (hm.containsKey(currentString)) {
          // yes, old one
          int [] temp = hm.get(currentString);
          temp = append(temp, i);
          hm.put(currentString, temp);
        }// 
        else {
          // No
          int[] temp= new int [1];
          temp[0]=i;
          hm.put(currentString, temp);
        }//else 
    
        // increase index
        i++;
      }//for
    }//function
    //
    
  • a is [0] 0
    b is [0] 1
    c is [0] 3
    [1] 4
    [2] 7
    d is [0] 2
    e is [0] 5
    f is [0] 6
    
    ==================
     now show c : 
    [0] 3
    [1] 4
    [2] 7
    
  • Answer ✓

    new version with a display of a small table

    //  https : // forum.processing.org/two/discussion/14188/finding-the-index-numbers-of-an-array-of-similiar-strings#latest
    
    //  list all the index values of the String array member, c (like {3,4,7})?
    
    import java.util.Map;
    
    String[] source= {"a", "b", "d", "c", "c", "e", "f", "c"};
    
    // Note the HashMap's "key" is a String and "value" is an int array 
    HashMap <String, int[] > hm = new HashMap<String, int[]>();
    
    void setup() {
      size(300, 300);
      background(0);
    
      // Putting key-value pairs in the HashMap
      setupArrays();
    
      // Using an enhanced loop to interate over each entry
      for (Map.Entry me : hm.entrySet()) {
        print(me.getKey() + " is ");
        printArray(me.getValue());
      }
    
      // We can also access values by their key
      int[] val = null;
      val=hm.get("c");
      if (val!=null) {
        println("\n==================\n now show c : ");
        printArray(val);
      }//if
    }//func
    
    void draw() {
      // 
      background(0);
      int columnNumber=0;
      for (char letter = 'a'; letter<='z'; letter++) {
        if  (hm.containsKey(trim(str(letter)))) {
          int[] val = null;
          val=hm.get(trim(str(letter)));
          if (val!=null) {
            fill(255);
            text(trim(str(letter)), 56+columnNumber*19, 50);
            fill(255, 2, 2);
            for (int i=0; i<val.length; i++) {
              text(val[i], 56+columnNumber*19, 50+20+17*i);
            }//for
            columnNumber++;
          }// if
        }// if
      }//for
    }//func 
    
    void setupArrays() {
      int i=0;
      // looping over the entire source array
      for (String currentString : source) {
    
        // did we have the letter already?
        if (hm.containsKey(currentString)) {
          // yes, old one
          int [] temp = hm.get(currentString);
          temp = append(temp, i);
          hm.put(currentString, temp);
        }// 
        else {
          // No
          int[] temp= new int [1];
          temp[0]=i;
          hm.put(currentString, temp);
        }//else 
    
        // increase index
        i++;
      }//for
    }//function
    //
    
  • Thank you @Chrisir :) I have to spend sometime to get a grip on the basics of HashMap

    I was trying to work with the hashMap after your first comment.

    import java.util.Map;
    
    HashMap<String, Integer> collection = new HashMap<String, Integer>();
    
    
    void setup() {
      size(200, 200);
    
      String [] name = {"a", "b", "a", "d", "a" };
    
    
    
    
      for (int i =0; i <name.length; i++) {
    
        collection.put(name[i], i);
      println(collection.get("d"));
    }
    
    
    }
    

    Over here, I was able to print the index numbers in the console. is there an easy way to 'clean' them and take out as an array of integers ? (sorry for my less programming proficiency:D )

  • edited December 2015

    you wrote:

    is there an easy way to 'clean' them and take out as an array of integers ?

    No, you still need one array for each letter

    you could make a 2D array - see tutorials

    what's wrong with my solution?

  • There is nothing wrong with with your Solution @ Chrisir. As a beginner, I was trying out other ways. Your solution works well :)

    Thanks again :)

  • I see

    now, you wrote:

    is there an easy way to 'clean' them and take out as an array of integers ?

    I did that with append. That would work

      int [] temp = hm.get(currentString);
      temp = append(temp, i);
      hm.put(currentString, temp);
    

    but you then still need one array per char or a 2D array

  • edited December 2015 Answer ✓
    // forum.Processing.org/two/discussion/14188/
    // finding-the-index-numbers-of-an-array-of-similiar-strings
    
    // 2015-Dec-29
    
    static final char[] LETTERS = { 'a', 'b', 'd', 'c', 'c', 'e', 'f', 'c' };
    final IntList[] inds = new IntList['z' - 'a' + 1];
    
    void setup() {
      for (int i = 0; i != inds.length; inds[i++] = new IntList());
      for (int i = 0; i != LETTERS.length; inds[LETTERS[i] - 'a'].append(i++));
    
      println(LETTERS);
      println();
    
      println(letterIndices(inds));
      exit();
    }
    
    static final String letterIndices(final IntList... inds) {
      final StringBuilder sb = new StringBuilder();
    
      for (int i = 0; i != inds.length; ++i) {
        final IntList it = inds[i];
        if (it.size() == 0)  continue;
    
        sb.append((char) (i + 'a')).append(": [ ");
        for (final int idx : it.values())  sb.append(idx).append(", ");
        sb.deleteCharAt(sb.length() - 2).append("]\n");
      }
    
      return sb.toString();
    }
    
  • Answer ✓

    better readable version

    // forum.Processing.org/two/discussion/14188/
    // finding-the-index-numbers-of-an-array-of-similiar-strings
    
    // 2015-Dec-29
    
    // source 
    char[] LETTERS = { 'a', 'b', 'd', 'c', 'c', 'e', 'f', 'c' };
    
    // array of IntList (holds the result)
    IntList[] inds = new IntList['z' - 'a' + 1];
    
    void setup() {
    
      // init the array of IntList 
      for (int i = 0; i < inds.length; i++) {
        inds[i] = new IntList(); // each item in the array is an IntList
      }//for
    
      // we loop over the letters (the source)
      for (int i = 0; i < LETTERS.length; i++) {
        // get index for the array of IntList
        int index = LETTERS[i] - 'a';  
        // append the new position i to this IntList
        inds[index].append(i);
      }//for
    
      println(LETTERS);
      println();
    
      println(letterIndices(inds));
      // exit();
    } // func 
    
    String letterIndices( IntList... inds ) {
      StringBuilder sb = new StringBuilder();
    
      for (int i = 0; i < inds.length; i++) {
    
        IntList it = inds[i];
        if (it.size() == 0)  
          continue;
    
        sb.append((char) (i + 'a')).append(": [ ");
        for (final int idx : it.values()) {
          sb.append(idx).append(", ");
        }
    
        sb.deleteCharAt(sb.length() - 2).append("]\n");
      }
    
      return sb.toString();
    }
    
  • This is great!! thanks a lot @chrisir and @GoToLoop :)

  • you're welcome!

Sign In or Register to comment.