Hello. In college, the whole course was pascal and it was time to practice. They gave individual assignments and deadlines. Not to say that I know Pascal perfectly, rather at the level of an experienced user. In the task there were only 5 tasks, 4 of which were successfully completed and recorded in the report, but from the fifth there were difficulties.

Task text:

Given a two-dimensional array of positive integers. It is known that there are matching elements (identical numbers). Display their indices.

Everything seems to sound simple and should not take a lot of time, but I can’t think of an algorithm. Thank you in advance.

  • Thank you all for the answers. The search algorithm was clear to me, and before I deduced indexes, the problem was duplication. I did not find a normal solution, I invented an Indian method with replacing the number with another after the output of its indices. - rashpil

3 answers 3

1 we take the first element we check with the rest

2 if the same is found, we display the copy index and the index of the element to be checked.

3 spinning in a loop while there are elements in the array

It would be good to introduce a type check if the copy index is less than the index of the element being checked - there is nothing to do, since it will already be taken

  • The solution is the most banal ... it would be possible, for example, to tie in here the search algorithm for identical elements, based on the algorithm used in the quick sort. - AseN
  • 2
    Of course, just a question was asked by the guru of pascal, therefore I don’t think it’s going to be very messy there ... - Gorets
  • 2 @Asen: you should not invent a bicycle, it would be much more efficient to first sort the array with the same quick sort. After sorting, we make another pass in order to display the indices of the same elements: if the current element is equal to the previous one, we output the indices. If it is necessary to output the indices of elements only once, then you will have to add another internal loop for this. result: decent speed + clear algorithm - jmu

Create an array of indices, i.e. fill the array with a natural number. We take the first element, compare it with the others in the cycle. We write the indices of the smaller ones into one array, the big ones into the other (either from the end or first to the middle of the new array), the indices of equal we derive. Recursively repeat the same for smaller ones and for larger ones, while the length is greater than 1.

    The standard algorithm requires each time to go over all the elements for comparison. You can also make a three-dimensional array where the values ​​of the form (number, index in the original array) will be saved and sort by ascending. It turns out something like 10, 19, 89, 128, 170, 230, 300, ... Next, take the number1 from the first array and compare. If number1 becomes less than the number from the second array, then break

    save N / 2 runs per pass