-1

I am new to Pascal and have a sample.txt file with the following integers:

1 2 
2 1
1 3
3 1
1 4

How do I find the integer from the file with the minimum and maximum occurrences in Pascal language? In the above example, max occurrences would be the integer 1 (occurs 5 times) and minimum would be 4 (occurs once).

I understand I must open the file and read the values in and I've figured out this much so far. Is there a shorter way to perform this?

var
  V1, V2, V3, V4, V5, V6, V7, V8, V9, V10: Integer; 
begin 
  Assign(F, 'sample.txt');
  Reset(F);
  read(F, V1);  
  read(F, V2);
  read(F, V3);
  read(F, V4);
  read(F, V5);
  read(F, V6);
  read(F, V7);
  read(F, V8);
  read(F, V9);
  read(F, V10);

  writeln('Max Occurrence')
  writeln('Min Occurrence')

  Close(F);
  writeln; 

Thanks in advance!

J Pham
  • 3
  • 1
  • Use a loop to read in the contents of the file. Do you know what a loop is? – David Heffernan Feb 09 '19 at 07:40
  • How would you do it without a computer, using pencil & paper? Once you've figured that out, write the code to express it in Pascal. Hint: When you get to the coding, an `array` is a convenient data structure to use to store and process the data. You can find the answers you need either by scanning the array or sorting it; both are elementary operations which you need to learn how to do. You will learn nothing if someone simply posts a solution to your problem. – MartynA Feb 09 '19 at 11:39
  • @MartynA: Actually, if you must constantly add items and if it is not sure upfront how many you will add, a list is a much better data structure. But a list may be a little too much for a complete beginner. – Rudy Velthuis Feb 09 '19 at 19:17
  • @RudyVelthuis: Sure, my first thought was a (linked) list - I have a pre-Delphi aversion to arrays - but, as you say, it would probably be a little too much for this exercise. – MartynA Feb 09 '19 at 19:32
  • @MartynA: I meant a simple stock TList, not a linked list. The linked list would be even farther above a beginner's horizon. – Rudy Velthuis Feb 09 '19 at 19:35

1 Answers1

0

Basically

 writeln('Max Occurrence',max(v1,max(v2,max(v3,max(v4,max(v5,max(v6,max(v7,max(v8,max(v9,v10)))))))))))
 writeln('min Occurrence',min(v1,min(v2,min(v3,min(v4,min(v5,min(v6,min(v7,min(v8,min(v9,v10)))))))))));

give or take a ")", but a teacher might not accept that as a solution without a loop, because it doesn't scale with the number of inputs.

The principle is that the final maximum is the maximum of the temporary maximum + the next data item

Marco van de Voort
  • 25,628
  • 5
  • 56
  • 89