2

I wanted to optimize my code, so instead of copying my entire char array for each iteration in the alphabet, I opted to do the copying beforehand and then I'd just add chars into the copy.

E.g.:

copy "lord" (i=0)

modify the first letter (aord, bord, cord &c)

copy "lord" (i=1)

modify the second letter (lard, lbrd, lcrd &c)

&c

    for (int i = 0; i < wordLength; i++) {
        Word moddedWord = new Word(Arrays.copyOf(temp.word.content, wordLength));
        for (int c = 0; c < alphabetLength; c++) {
            if (alphabet[c] != temp.word.content[i]) {
                // Word moddedWord = new Word(Arrays.copyOf(temp.word.content, wordLength));
                moddedWord.content[i] = alphabet[c];
                Word res = WordList.Contains(moddedWord);
                if (res != null && WordList.MarkAsUsedIfUnused(res)) {
                    WordRec wr = new WordRec(res, temp);
                    q.Put(wr);
                }
            }
        }
    }

However, when I do this small change, my program doesn't work, when it used to when I instead used the commented line for copying. I've debugged this for hours on end now and I can find nothing that changes this, I've tried various forms of copying, I've tried storing the "original" word as a String and then converting it to a char array when I need to copy it, nothing seems to work. Oh by the way, "Word" is just a wrapper for char[] (Word.content is a char[] field).

2
  • What do you mean by "does not work"? Are you storing the same array over and over or do you get an exception, or what happens? Commented Nov 13, 2013 at 8:56
  • It starts infinite looping actually, which is really weird, since I've been using IntelliJ's debugger, which tells me it only gets to q.Put(wr) for valid words. Commented Nov 13, 2013 at 9:00

1 Answer 1

1

You can't avoid copying if you want to store each modification of the word. Here:

new WordRec(res, temp);

you create a word record based on the mutable instance of the word and then you keep changing that one instance. You'd need to copy temp inside this constructor. So the best you achieve is copying a bit later, possibly a bit less due to the "ifology" within which it happens.

Now, if you really want to improve performance, then rework the WordList to be a WordSet and have O(1) lookup time with the Contains method.

A final note: please respect the Java naming conventions. Methods start with a lowercase letter.

Sign up to request clarification or add additional context in comments.

1 Comment

I am using a HashSet for WordList currently, so Contains should already be O(1). I've changed my Contains method for wordlist now to make a "deep copy" of the Word. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.