Jump to content

Comparing two strings in .txt file

- - - - -

  • Please log in to reply
2 replies to this topic

#1
Slammerek

Slammerek

    Newbie

  • Members
  • Pip
  • 8 posts
Hi,
I have .txt file which looks like this(example):
1R

2L

3L

2R

3L

4L

5L

3R

4L

4R

5R

5R

6R

6R

1R

2L

3L

4L

2R

5L

3R

4R

5L

3L

4L

6R

6L

And I need a algorithm which takes first half of this .txt file and compare it with second half and say if its same or it's not.
I'm stuck at this so if there is anybody who can help me i would appreciate that.

Thx in advance :)

#2
gregwarner

gregwarner

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 853 posts
  • Location:Arkansas
I'm assuming that the data in your text file will already be sorted, since that's what it looks like here.
This should be a very simple algorithm, then. All you need to do is read each string into a string array, find the halfway point (if the array has an odd number of elements, you can assume the two halves are not equal, since equal halves will only be able to add up to an even amount), and then compare the values of the first half with the 2nd half one by one. As soon as you find one that doesn't match, you can drop out of the sequence and return an invalid match. The pseudocode would be as follows:

Read each line in file into string array.

If length of string array is even,

    Let "half" = array length / 2.

    Loop on "i" from zero to "half" (exclude half from the loop):

        if array[i] != array[half + i],

            The halves are not matched.

            Exit loop.

        end if

    end loop

else (the length of the string is odd)

    The halves are not matched.

end if.

There are a few lines missing from the pseudocode above, specifically the return types (match or no match). You'll have to implement a way to make sure it returns the proper value depending on the outcome. But besides that, the gist of the algorithm is there and you should be able to go from that.
Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.

– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid


#3
Slammerek

Slammerek

    Newbie

  • Members
  • Pip
  • 8 posts
Thanks a lot greg ;)
My first thought was to read first half and save it to array then do the same with second half and compare those arrays.
But your solution is much easier and elegant :):thumbup1:




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users