php to processing - variable variables

Hi, I need to port this piece of php code but it uses variable variables, any idea on how to achieve this?

Answers

  • edited May 2015 Answer ✓

    Dunno PHP, sorry. And Java, just like C/C++, is very strongly typed.
    That is, in Java we gotta declare the type of each variable and each container.

    Your $lists seems like an array of String[] type.
    So it's something like: String[] lists = {}

    Unfortunately, we can't dynamically create variables in Java.
    That is, all variables gotta be explicitly written in the source.
    We can't just pick or concatenate a String and state that is a new variable now.

    However, we can use a Map type container w/ {key : value} pairs.
    I've chosen StringDict for this attempt: https://processing.org/reference/StringDict.html
    But some HashMap<String, String> would be even faster...

    // forum.processing.org/two/discussion/10726/
    // php-to-processing-variable-variables
    
    final String[] lists = {
      "interjections", 
      "determiners", 
      "adjectives", 
      "nouns", 
      "adverbs", 
      "verbs", 
      "prepositions", 
      "conjunctions", 
      "comparatives"
    };
    
    final StringDict paths = new StringDict(lists.length);
    
    for (String part : lists)  paths.set(part, dataPath(part + ".txt"));
    
    println(paths);
    println();
    
    println("verbs:", paths.get("verbs"));
    exit();
    
  • edited October 2016

    thanks, really helpful

  • edited May 2015

    In this sense, how can I create a multidimensional array from this code? --original php script:

        for ($i=0; $i<2; $i++) {
                foreach ($lists as $part) ${$part}[$i]  = trim(${$part}[rand(0,count(${$part}) - 1)]);
            }
    

    In this case $verb is different to $verb[1]``

  • edited May 2015

    In Java, the [] array access operator always means the index of some array:
    https://processing.org/reference/arrayaccess.html

    Seems like in PHP, [] has multiple meanings.
    While in ${$part}[$i] = the [] over there means array access,
    in ${$part}[rand( ... )] apparently it means a char position within the String now.

    And translating the latter to Java's String, it corresponds to its method charAt():
    https://processing.org/reference/String_charAt_.html

    Plus the count() function would correspond to String's length() method:
    https://processing.org/reference/String_length_.html

    And obviously, rand() is Processing's random(): 3:-O
    https://processing.org/reference/random_.html

    In short, it's randomly picking up 1 char outta the String as value and associating it w/ the same String as the key.
    So the {key : value} pair relationship is <String, Character> in Java.

    For that, this time we're gonna use a HashMap<String, Character> in place of previous StringDict.
    More specifically, an array of Map<String, Character>[]: :D
    https://processing.org/reference/HashMap.html

    You see, If I got that right, the ${$part}[$i] is actually creating an array of Map[] in order to store 1 random() char.

    Well, here it goes the probable solution for your mysterious PHP sample: #:-S

    // forum.processing.org/two/discussion/10726/
    // php-to-processing-variable-variables
    
    final String[] lists = {
      "interjections", 
      "determiners", 
      "adjectives", 
      "nouns", 
      "adverbs", 
      "verbs", 
      "prepositions", 
      "conjunctions", 
      "comparatives"
    };
    
    import java.util.Map;
    
    final int capacity = ceil(lists.length/.75);
    final Map<String, Character>[] chars = new Map[] {
      new HashMap<String, Character>(capacity), new HashMap<String, Character>(capacity)
    };
    
    for (String part : lists)  for (int i = 0; i != chars.length; ++i)
      chars[i].put( part, part.charAt((int) random(part.length())) );
    
    printArray(chars);
    println();
    
    println("verbs:", chars[0].get("verbs"), chars[1].get("verbs"));
    exit();
    
  • edited February 2016

    how can i do an array of maps or dicts?

    There should be a HasMap/StringDic tutorial, really powerful and useful..

  • Before anything, an alternative to previous example: :D

    // forum.processing.org/two/discussion/10726/
    // php-to-processing-variable-variables
    
    final String[] lists = {
      "interjections", 
      "determiners", 
      "adjectives", 
      "nouns", 
      "adverbs", 
      "verbs", 
      "prepositions", 
      "conjunctions", 
      "comparatives"
    };
    
    import java.util.Map;
    import java.util.Map.Entry;
    
    final int capacity = ceil(lists.length/.75), len = 2;
    final Map<String, char[]> chars = new HashMap<String, char[]>(capacity);
    
    for (String part : lists) {
      char[] ch = new char[len];
      for ( int i = 0; i != len; ch[i++] = part.charAt((int) random(part.length())) );
      chars.put(part, ch);
    }
    
    for (Entry<String, char[]> pair : chars.entrySet()) {
      print(pair.getKey(), ":  ");
      for (char ch : pair.getValue())  print(ch, ' ');
      println();
    }
    
    println("\nverbs:", chars.get("verbs")[0], chars.get("verbs")[1]);
    exit();
    
  • edited May 2015
    • In order to get those external words, we've gotta load them 1st.
    • But I wonder which type are they: CSV, TSV or 1 word in each line.
    • I'll just assume it's the latter. A simple loadStrings() will do the whole work then:
      https://processing.org/reference/loadStrings_.html

    • In order to store the output from loadStrings(), we're gonna need Map<String, String[]>.

    • That is, each grammar word is associated w/ an array of String[].

    // forum.processing.org/two/discussion/10726/
    // php-to-processing-variable-variables
    
    // 2015-May-11
    
    final String[] LIST = {
      "interjections", 
      "determiners", 
      "adjectives", 
      "nouns", 
      "adverbs", 
      "verbs", 
      "prepositions", 
      "conjunctions", 
      "comparatives"
    };
    
    import java.util.Map;
    import java.util.Map.Entry;
    
    final int CAPACITY = ceil(LIST.length/.75);
    final Map<String, String[]> grammar = new HashMap<String, String[]>(CAPACITY);
    
    for (String entry : LIST)  grammar.put(entry, loadStrings(entry + ".txt"));
    
    for (Entry<String, String[]> pair : grammar.entrySet()) {
      println(pair.getKey(), ':');
      printArray(pair.getValue());
      println();
    }
    
    print("Random word value from \"verbs\" key: ");
    String[] words = grammar.get("verbs");
    println("\"" + words[(int) random(words.length)] + "\"");
    exit();
    
  • edited February 2016

    In this case it would be better to just assign to different String vars each .txt file isn't?

  • edited May 2015
    • Well, you've asked about what would be the equivalent PHP code in Processing/Java.
    • PHP was creating variables dynamically at runtime.
    • Java can't do that! All variables are statically declared in the source code before hand.
    • Although we can rely on some Map-like container in order to emulate that.
    • However, if you are satisfied in explicitly declaring each of those 9 "grammar" variables now,
      that's the Java's way after all. :P
  • edited May 2015

    I was hoping I could do something like grammar.get("verbs")[random(n)]...

    Haven't you spotted these last lines in my example? $-)

    String[] words = grammar.get("verbs");
    println( "\"" + words[ (int) random(words.length) ] + "\"" );
    

    It's doing exactly what you asked for! They can be synthesized this way too:

    grammar.get("verbs")[ (int) random(grammar.get("verbs").length) ]
    

    But it's faster & shorter to temporarily store grammar.get("verbs") in some variable than repeating it more than once! :-B

  • edited May 2015

    The Map approach would allow us to even choose a random() "grammar" category: ;;)

    String category = LIST[ (int) random(LIST.length) ];
    String[] words  = grammar.get(category);
    String pickWord = words[ (int) random(words.length) ];
    
    println( "Grammar Category:", category );
    println( "Random  Word: \"" + pickWord + "\"" );
    
  • edited February 2016

    This is the version I just did with string arrays.. It's not that elegant but works.. (the only part I haven't ported is the one between "/* */" --cause I don't get the foreach clause. Any ideas?

  • edited May 2015 Answer ✓

    This is the version I just did with String arrays... It's not that elegant but works...

    Well, I've posted many examples using Map containers already.
    It's not easy to wrap around how to use them. And I didn't learn about them in 1 day either! b-(
    Indeed separate variables are much easier & comfortable to get around... B-)

    ... 'cause I don't get the foreach clause.

    There are 2 types of for () loops in Java: regular for ( ; ; ) & enhanced for ( : ):
    https://processing.org/reference/for.html

    PHP's foreach equivalent in Java is for ( : ). In my code posts you'll find lotsa them:

    • for (String entry : LIST) {}
    • for (Entry<String, String[]> pair : grammar.entrySet()) {}

    P.S.: In PHP, the container to be traversed is the 1st argument before as.
    While in Java's for ( : ) it's the opposite! It is placed after the :! :-t

  • Really helpful, man. Thanks a lot.

Sign In or Register to comment.