Pascal – Pro9ramming https://pro9ramming.com Software craftsman's blog Wed, 15 Apr 2020 17:51:06 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.3 Sum of even numbers https://pro9ramming.com/sum-of-even-numbers/ Tue, 20 Dec 2016 07:53:55 +0000 http://pro9ramming.com/blog/?p=385 The task is to create a program that sums all even numbers from 1 to n. If number modulus by 2 is equal to zero than that number is even (k mod 2 = 0). n is a parameter (from standard input).

Pascal solution:

program even_nums_sum;
var i,n,s:integer;
begin
    readln(n);
    s:=0;
    for i:=1 to n do
    begin
        if i mod 2 = 0 then
        begin
            s:=s+i;
        end;
    end;
    writeln(s);
    readln();
end.

]]>
Reversed calculation https://pro9ramming.com/reversed-calculation/ Fri, 12 Dec 2014 19:43:27 +0000 http://pro9ramming.com/blog/?p=64 Continue reading Reversed calculation]]> Task is to write a program that will add one reversed number to another and write their reversed sum. If number is 123 than reversed number is 321.
As you can see all zeros on the end of number are deleted in reversed number.
Input
Two numbers in different lines in standard input.
Output
One number that represent solution.
Sample Input
24
1
Sample Output
34
Sample Input
4358
754
Sample Output
1998
Sample Input
305
794
Sample Output
1
Pascal solution:

program reversed;
uses wincrt;
var
a,b:string;
i,s,t:integer;
begin 
  readln(a);
  readln(b);
  while length(a)<length(a) do
    a:=a+'0';
  while length(b)<length(b) do
    b:=b+'0';
  t:=0;
  for i:=1 to length(b) do
  begin
    s:=ord(a[i])+ord(b[i])-2*ord('0')+t;
    a[i]:=chr(ord('0')+(s mod 10));
    t:=s div 10;
  end;
  if t<>0 then
    a:=a+'1';
  while a[length(a)]='0' do
    delete(a,length(a),1);
  while a[1]='0' do
    delete(a,1,1);
  writeln(a);
end.

 

]]>
Herding Frosh https://pro9ramming.com/herding-frosh/ Fri, 05 Dec 2014 02:43:27 +0000 http://pro9ramming.com/blog/?p=285 Continue reading Herding Frosh]]> One day, a lawn in the center of campus became infested with frosh. In an effort to beautify the campus, one of our illustrious senior classmen decided to round them up using a length of pink silk. Your job is to compute how much silk was required to complete the task.
The senior classman tied the silk to a telephone post, and walked around the perimeter of the area containing the frosh, drawing the silk taught so as to encircle all of them. He then returned to the telephone post. The senior classman used the minimum amount of silk necessary to encircle all the frosh plus one extra meter at each end to tie it.
You may assume that the telephone post is at coordinates (0,0), where the first dimension is north/south and the second dimension is east/west. The coordinates of the frosh are given in meters relative to the post. There are no more than 1,000 frosh.
Input
The input begins with a single positive integer on a line by itself indicating the number of test cases, followed by a blank line.
Each test case consists of a line specifying the number of frosh, followed by one line per frosh with two real numbers given his or her position.
There is a blank line between two consecutive inputs.
Output
For each test case, the output consists of a single number: the length of silk in meters to two decimal places. The output of two consecutive cases will be separated by a blank line.
Sample Input
1
4
1.0 1.0
-1.0 1.0
-1.0 -1.0
1.0 -1.0
Sample Output
10.83
Solution
The key is to calculate sum of every distance. Adding (0,0) coordinates to a array makes things easier (see the picture).

herding_frosh_expl

Solution in example input is 10,83. There are 3 x 2 and 2 x sqrt(2), and remember two meters at the ends, so 4*2+2*sqrt(2)=10.83.

More about Euclidean distance on wiki.

Pascal solution:

program herding_frosh;
uses wincrt;
type
  tarray=record
  x,y:integer;
  end;
var
n,i:integer;
b:array[1..100] of real;
function euclidean_distance(x1,y1,x2,y2:integer):real;
begin
  euclidean_distance:=sqrt(sqr(x1-x2)+sqr(y1-y2));
end;
function calculate:real;
var
  i,n:integer;
  r:real;
  a:array[0..100] of tarray;
begin
r:=0;
readln(n);
with a[0] do
  begin
   x:=0;
   y:=0;
  end;
for i:=1 to n do
readln(a[i].x,a[i].y);
for i:=1 to n do
  begin
    r:=r+euclidean_distance(a[i].x,a[i].y,a[i-1].x,a[i-1].y);
  end;
r:=r+euclidean_distance(a[n].x,a[n].y,a[0].x,a[0].y)+2;
calculate:=r;
end;

begin
readln(n);
for i:=1 to n do
begin
   readln;
   b[i]:=calculate;
end;
for i:=1 to n do
writeln(b[i]:9:2);
end.

 

]]>
Uppercase and lowercase string https://pro9ramming.com/uppercase-and-lowercase-string/ Thu, 04 Dec 2014 02:43:27 +0000 http://pro9ramming.com/blog/?p=320 Task is to write a program for converting a string to upper and lower case. Of course, use of libraries is forbidden. Program should work with ASCII and should take care of other characters that are not letters.

Solution in Pascal:

program upper_lower_case;
uses wincrt;
var
  s,k:string;
  label error;
function uppercase(s:string):string;
var
i:integer;
begin
  for i:=1 to length(s) do
    if (s[i]>='a') and (s[i]<='z') then
      dec(s[i],32);
    uppercase:=s;
end;
function lowercase(s: string): string;
var
i:integer;
begin
  for i:=1 to length(s) do
    if (s[i]>='A') and (s[i]<='Z') then
     inc(s[i],32);
    lowercase:=s;
end;
begin
  writeln('Enter string ?');
  readln(s);
  error:
  writeln('Enter "u" for upper or "l" for');
  writeln('lower case string ?');
  readln(k);
  if k='u' then
     writeln(uppercase(s))
  else
    if k='l' then
      writeln(lowercase(s))
    else   
     goto error;
end.

 

]]>
Decimal to binary converter https://pro9ramming.com/decimal-to-binary-converter/ Wed, 03 Dec 2014 21:43:27 +0000 http://pro9ramming.com/blog/?p=174 Continue reading Decimal to binary converter]]> The task is to create decimal to binary converter.
For example, to find a binary equivalent of 21, you divide by 2 in steps and take modulus.
21 / 2 = 10 remain 1
10 / 2 = 5 remain 0
5 / 2  = 2 remain 1
2 / 2 = 1 remain 0
1 / 2 = 0 remain 1
At the end, read modulus from bottom-up and you’ll get 1s and 0s.

TPW code:

program dec_to_bin;
uses wincrt;
var
  a:array[1..100] of 0..1;
  n,k,i:integer;
  label top;
begin
top:
writeln('Enter decimal number !');
readln(n);
k:=0;
while n>0 do
begin
k:=k+1;
a[k]:=n mod 2 ;
n:=n div 2;
end;
writeln('Binary number is : ');
for i:=k downto 1 do
write(a[i]);
writeln;
writeln('Press Enter if you want to try again !');
readln;
clrscr;
goto top;
end.

 

]]>
Working with files in Pascal https://pro9ramming.com/working-with-files-in-pascal/ Sun, 30 Nov 2014 01:43:27 +0000 http://pro9ramming.com/blog/?p=201 Continue reading Working with files in Pascal]]> Every programming language has it’s own ways of working with files.
In Pascal, text variable has to be declared like this:

var
input:text;

Next 4 commands are essential:

assign(text_variable,string_location);
reset(text_variable);
rewrite(text_variable);
close(text_variable);

Reset opens a file for reading, and rewrite opens a file for
writing, and assign assigns the file with the text variable,
or connects them, and close closes that connection.
“string_location” represents a string that is location of file.
That string, if the file is in the same dir or folder as .exe
is for example “input.txt” or “input.in”,
and if you want to specify olcation you use standard dir declaration
for example “C:/text/input.txt”.
ATTENTION: File must be created before writing or reading from it.
You can not assign non-existed file.

Next thing after you assign and reset file is reading from it,
you can use read() or readln() functions like

readln(file_variable,variable_list);

Write a program which reads an integer variable from file “input.in”
and writes on screen 2*that_variable.

TPW:

program example1;
uses wincrt;
var
n:integer;
input:text;
begin
assign(input,'input.in');
reset(input);
readln(input,n);
writeln(2*n);
close(input);
end.

ATTENTION : That variable must be in the first line of that file.
For writing to file, write() and writeln() functions the same way as you use
read() and readln() functions, like this:

writeln(file_variable,variable_list);

Make a program which reads 2 numbers from 2 separate lines from file
“input.txt” and writes all numbers between them into file “output.txt”.
If the second number is smaller than first then it writes numbers from
second to first, and if they are equal, then it writes in file
“The numbers are equal.”.

program example2;
uses wincrt;
var
i,a,b:integer;
input,output:text;
begin
assign(input,'input.txt'); reset(input);
assign(output,'output.txt'); rewrite(output);
readln(input,a);
readln(input,b);
if a=b then
  writeln(output,'The numbers are equal.')
else
  if a>b then
   for i:=b to a do
     writeln(output,i)
  else
    if a<b then
      for i:=a to b do
        writeln(output,i);
close(input);
close(output);
end.

You should always close the files on the end.

]]>
Separate words from text https://pro9ramming.com/separate-words-from-text/ Sat, 29 Nov 2014 21:43:27 +0000 http://pro9ramming.com/blog/?p=132 Continue reading Separate words from text]]> Wordlists are downloaded from various sites by Hackers. But why don’t make your own. The motivation is to make a program for making wordlists from text. This algorithm separates words with recursion and also recursively removes all chars that did not pass alphabet test.
So you’ll get words that are characters of English alphabet (a,b,c, . . ., y,z).
And i did it using files. So first you make input and output file, and in input file you just paste text, run this program and open output file, and everything is done, just use FTP Bruteforcer.

program separate_words;
uses wincrt;
var
s,locin,locout:string;
input,output:text;
function alphabetcheck(s:string):boolean;
var
  x:integer;
  y:boolean;
begin
  y:=true;
    for x:=1 to length(s) do
      if ((s[x]<'A') or (s[x]>'Z')) and (y=true) then
       if s[x]='' then
         y:=true
       else
         if ((s[x]<'a') or (s[x]>'z')) then
           y := false;
        if y=true then
            alphabetcheck:=true
        else
            alphabetcheck:=false;
end;
function lowercase(s:string):string;
var
  i:integer;
begin
  for i:=1 to length(s) do
    if (s[i]>='A') and (s[i]<='Z') then
      inc(s[i], 32);
    lowercase:=s;
end;
function remove_chars(s:string):string;
var
  i,br:integer;
  g:array[1..10] of char;
begin
br:=0;
  for i:=1 to length(s) do
    if not alphabetcheck(s[i]) then
      remove_chars:=remove_chars(copy(s,1,i-1)+copy(s,i+1,length(s)))
    else
     br:=br+1;
     if br=length(s) then
       remove_chars:=s;    
end;
procedure one_line(s:string);
begin
  if pos(' ',s)=0 then
    writeln(output,lowercase(remove_chars(s)))
  else
    begin
      writeln(output,lowercase(remove_chars(copy(s,1,pos(' ',s)-1))));
      one_line(copy(s,pos(' ',s)+1,length(s)));
    end;
end;
begin
  writeln('Enter location of input file !');
  readln(locin);
  writeln('Enter location of output file !');
  readln(locout);
  assign(input,locin); reset(input);
  assign(output,locout); rewrite(output);
  repeat
    begin
      readln(input,s);
      one_line(s);
    end;
  until eof(input);
  close(input);
  close(output);
  writeln('task completed succesfully !');
end.

 

]]>
Definite integral https://pro9ramming.com/definite-integral/ Tue, 25 Nov 2014 09:43:27 +0000 http://pro9ramming.com/blog/?p=60 Task is to create a program that determines a definite integral of the function f(x)=sin(x)*ln(x), where bounds are given by real parameters A and B (segment of Ox). That basically means that you have to calculate the area under the function.

Here is the solution in TPW:

program integral;
uses wincrt;
const dx = 0.0001;
var
  i,a,b,p:real;
  label top;
begin
top:
writeln('Enter start of segment of Ox !');
readln(a);
repeat
begin
writeln('Enter end of segment of Ox !');
readln(b);
end;
until b>a;
i:=a+dx;
p:=0;
repeat
begin
  p:=p+abs(dx*sin(i)*ln(i));
  i:=i+dx;
end;
until i>b;
writeln('Solution is ',p:9:4);
writeln('Press Enter to try again !');
readln;
clrscr;
goto top;
end.

 

]]>
Separate digits from integer number https://pro9ramming.com/separate-digits-from-integer-number/ Tue, 25 Nov 2014 07:43:27 +0000 http://pro9ramming.com/blog/?p=91 Continue reading Separate digits from integer number]]> If you have to find sum of integer’s digits, then use this algorithm is essential. In TPW there are no standard functions as strtoint() and inttosr() as in Delphi. You can easily do this in Delphi with this functions. But in Pascal there is a way to do this without this functions with “mod” and “div” operators.
These functions can be easily understood from this example:

5 div 2 = 2
5 mod 2 = 1

If you get the modulus of a number when divided with 10, you would get last digit, than you can divide it by 10 and do modulus again till you reach zero.

Here is the implementation in TPW:

program cut_digits_out_of_number;
uses wincrt;
var
  n:longint;
  i,j:integer;
  a:array [1..100] of integer;
begin
writeln('Program for cutting digits');
writeln('out of an integer number !');
writeln('Enter integer number !');
readln(n);
i:=0;
repeat
begin
   i:=i+1;
   a[i]:=n mod 10;
   n:=n div 10;  
end;
until n=0;
writeln('Digits are : ');
for j:=i downto 1 do
writeln(a[j]);
end.

But if you want to use function like in Delphi strtoint(), you can make it in Pascal. Like i made it. And i used string cutting and i made that function, so solution looks like this:

program cut_digits_out_of_number;
uses wincrt;
var
  n:string;
  i:integer;
  a:array [1..100] of integer;
function numcheck(s: string): boolean;
var
  x:integer;
begin
numcheck:=true;
for x:=1 to length(s) do
  if (ord(s[x])<48) or (ord(s[x])>57) then
   if s[x]<>'' then
    numcheck:=false;
end;
function str_to_int(s:string):integer;
var
  check:integer;
  i:integer;
begin
   if numcheck(s) then
    val(s,i,check);
   str_to_int:=i;
end;
begin
writeln('Program for cutting digits');
writeln('out of an integer number !');
writeln('Enter integer number !');
readln(n);
for i:=1 to length(n) do
begin
a[i]:=str_to_int(n[i]);
end;
for i:=1 to length(n) do
writeln(a[i]);
end.

Or you can use val procedure, explained in Help:

valprocedure

]]>
Reverse and Add task https://pro9ramming.com/reverse-and-add-task/ Sun, 23 Nov 2014 07:43:27 +0000 http://pro9ramming.com/blog/?p=305 Continue reading Reverse and Add task]]> The reverse and add function starts with a number, reverses its digits, and adds the reverse to the original. If the sum is not a palindrome (meaning it does not give the same number read from left to right and right to left), we repeat this procedure until it does.
For example, starting with 195 as the initial number, 9,339 is the resulting palindrome after the fourth addition:

195  
591   
___
786   

786
687
___
1,473

1,473

This method leads to palindromes in a few steps for almost all of the integers. But there are interesting exceptions. 196 is the first number for which no palindrome has been found. It has never been proven, however, that no such palindrome exists. The task is to write a program that takes a given number and gives the resulting palindrome (if one exists) and the number of iterations it took to find it. It can be assumed that all the numbers used as test data will terminate in an answer with less than 1,000 iterations (additions), and yield a palindrome that is not greater than 4,294,967,295.
Input
The first line will contain an integer N (0 < N ≤ 100), giving the number of test cases, while the next N lines each contain a single integer P whose palindrome you are to compute.
Output
For each of the N integers, print a line giving the minimum number of iterations to find the palindrome, a single space, and then the resulting palindrome itself.
Sample Input
3
195
265
750
Sample Output
4 9339
5 45254
3 6666
Pascal code:

program reverse_and_add;
uses wincrt;
var
n,steps,p,i:longint;
a:array[1..100] of longint;
function reverse(k:longint):longint;
var
  p,i,g,f:longint;
  a:array[1..100] of 0..9;
begin
  g:=1;
  i:=0;
  f:=0;
  repeat
    begin
     i:=i+1;
     a[i]:=k mod 10;
     k:=k div 10;
    end;
  until k=0;
  for p:=1 to i-1 do
   g:=g*10;
   for p:=1 to i do
     begin
      f:=f+g*a[p];
      g:=g div 10;
     end;
     reverse:=f;
end;
function add(k:longint):longint;
var
  i:integer;
begin
  i:=0;
  repeat
    begin
      k:=k+reverse(k);
      i:=i+1;
    end;
  until reverse(k)=k;
  steps:=i;
  add:=k;
end;
begin
readln(n);
for i:=1 to n do
readln(a[i]);
for i:=1 to n do
   begin
     p:=add(a[i]);
     writeln(steps,' ',p);
   end;
end.

C++ code:

#include <iostream>
#include <cstdio>

using namespace std;

int steps,p,i;
int a [100];

int reverse(int k)
{
  int p,i,g,f;
  int a[100];
  g=1;
  i=0;
  f=0;
  do
    {
     i++;
     a[i] = k % 10;
     k = k / 10;
    }
  while (!k == 0);
  for (p=1;p<=i-1;p++)
   g=g*10;
    for (p=1;p<=i;p++)
     {
      f=f+g*a[p];
      g=g / 10;
      }
     return f;
}
int add(int k)
{
  int i;
  i=0;
  while (reverse(k)>k | reverse(k)<k)
    {
      k = k + reverse(k);
      i++;
    }
  
  steps = i;
  return k;
}
int main()
{
    int n;
    cout<<"enter number of test cases"<<endl;
cin>>n;
for (i=1;i<=n;i++)
cin>>a[i];
for (i=1;i<=n;i++)
   {
     p=add(a[i]);
     cout<<steps<<" "<<p<<endl;
   }
   system("pause");
}

 

]]>