How to convert values from characters to numbers - pascal

How to convert letters into numbers.
Let's say A:=5 and B:=10.
When the input is AB, i want the output result to be A+B (510)
I'm going to do this with all characters in alphabet.

This will lead you to a complete solution:
program ccn;
const
a= 'A';
z= 'Z';
type
domain= a..z;
var
conv: array[ domain] of integer;
input: string;
i: integer;
begin
conv[ 'A'] := 5;
conv[ 'B'] := 10;
{ ...more}
input := 'AB';
writeln( 'input:', input);
write( 'output:');
for i := 1 to length( input)
do
write( conv[ input[ i]]);
writeln;
end.

i am not a pascal specialist, but this should work:
get the ordinal number of each letter with
n:=ord(s)
then you can substract the Ord of the ascii "A" of it and add 10 if you wish to have 10 for A 11 for B etc;
in case you want to map the letters to your own numbers you could use an array instead which contains 5 at the index corresponding to the ordinal posisition of "A", 10 at position of B, etc.
then apply
str()
to each resulting n
then use
+
or
concat()
to put the strings together

Related

How to multiply odd numbers from an array?

I have a program that reads a N number of integers and push them into an array, then I need to multiply the odd numbers from the array.
Program p2;
type
tab = array[1..10] of integer;
var
a, c : tab;
n, i, prod : integer;
begin
writeln('n=');
readln(n);
prod := 1;
writeln('Enter array numbers:');
for i := 1 to n do
read(a[i]);
if (a[i] mod 2 = 1) then
prod := a[i] * prod;
writeln('The produs of the odd numbers is: ',prod);
end.
For example when you enter the n as 5, and the numbers: 1, 2, 3, 4, 5;
The result of multiplication of odd numbers should be 15. Can someone help me to fix it working properly.
First off, whitespace and indentation are not terribly significant in Pascal, but they can be your ally in understanding what your program is doing, so let's make your code easier to read.
Program p2;
type
tab = array[1..10] of integer;
var
a, c : tab;
n, i, prod : integer;
begin
writeln('n=');
readln(n);
prod := 1;
writeln('Enter array numbers:');
for i := 1 to n do
read(a[i]);
if a[i] mod 2 = 1 then
prod := a[i] * prod;
writeln('The produs of the odd numbers is: ', prod);
end.
With indentation, it should be apparent what's happening. Your conditional only runs once, rather than each time through your loop. As suggested in the comments, begin and end neatly solve this problem by creating a block where the conditional is checked each time the loop runs.
program p2;
type
tab = array[1 .. 10] of integer;
var
a, c : tab;
n, i, prod : integer;
begin
writeln('n=');
readln(n);
prod := 1;
writeln('Enter array numbers:');
for i := 1 to n do
begin
read(a[i]);
if a[i] mod 2 = 1 then
prod := a[i] * prod;
end;
writeln('The produs of the odd numbers is: ', prod);
end.

One row, multiple inputs?

In pascal, as you might know, you can assign multiple variables values in one single line (as long as you have variables to catch them in):
var x, y, z: integer;
readln(x, y, z, etc...);
But what if i wanted to have only one variable, which would sequentially recieve those values which sit, practically, in the void?
Let me explain:
Number of values?
>3 (for example)
Insert values:
4 6 9
Now, these values, would periodically be assigned to 'a' for example, and once i'm done with the number 4, i want it to recieve 6, and 9 afterwards. Is there any way i can do this?
In Extended Pascal, ISO 10206, you can do the following:
program lists(input, output);
procedure processList(length: integer);
var
list: array[1..length] of integer;
var
n: integer;
begin
writeLn('Insert ', length:1, ' values:');
for n := 1 to length do
begin
read(list[n]);
end;
{ Here you can further process `list` }
end;
var
n: integer;
begin
writeLn('Number of values?');
readLn(n);
processList(n);
end.
A better implementation uses schemata for this task:
program lists(input, output);
type
list(length: integer) = array[1..length] of integer;
var
n: integer;
l: ^list;
begin
writeLn('Number of values?');
readLn(n);
{ dynamically allocate memory for `l` }
new(l, n);
writeLn('Insert values:');
for n := 1 to l^.length do
begin
read(l^[n]);
end;
dispose(l);
end.
At compile-time undiscriminated schema data types can only be handled via pointers, which is always a little unpleasant for us programmers, but it works.

How to generate a random combination of digits that are already defined in Pascal?

I would like to ask if anybody can give a hand in solving the following issue: How should I use the random function in Pascal in order to generate a random combination of digits that are already initialized (I mean that I have given values to four variables and I want via the random function to create a random combination of these four digits).
Thanks in advance!
Rossi
var digits : array[0..3] of integer = (10,20,30,40);
i : integer;
begin
Randomize; // initialize the random generator. Only once per program
for i:=0 to 50 do
Writeln(digits[random(4)]);
end.
The Writeln line draws a number 0<=x<4 so 0..3, and looks it up in the digits array, then writes it to console output. It is draws 50 random numbers and then quits.
var
randomnumber,i:integer;
number:array[0..3] of integer;
begin
randomize;
for i:= 0 to 3 do
begin
readln(number[i]);
end;
randomnumber:= (number[random(4)] * 1000) + (number[random(4)] * 100) + (number[random(4)] * 10) + (number[random(4)] * 1);
writeln(randomnumber);
end.
I hope this could help.
But the given initial value should be between 0 to 9.
If you want that the output contains each digit only once, then you would need to stored the digits which have already been chosen in a set to prevent them from being chosen again.
const
digits: array [0..3] of integer = (1, 3, 5, 7);
var
i, n, total: integer;
stored: set of integer;
begin
Randomize;
stored:= [];
total:= 0;
for i:= 1 to 4 do
begin
repeat
n:= random (4);
until not (n in stored);
stored:= stored + [n];
total:= total * 10 + digits[n];
end;
writeln (total)
end.

When the program runs, writes ->->->->. Why does it do that?

Here is the textfile that the program must read, and put every num. in a different variable.
The first num., in this case 3, is the n, and tells the procedure the program how many times to be done. Between the nums., there is a space.
The text file f is like that
3 2
2 1
1 5
4 2
When it runs the code the following thing keeps being writen
->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->
->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->
->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->
->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->
->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->
->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->->
Why do that happeen?
Can anyone please help me with this program?
The code is the following one.
Program thefinalp;
Uses SysUtils;
Var
f: Text;
m, d: Integer;
n: Char;
c: String[1];
a, e: array of Integer;
LowArr: Integer;
HighArr: Integer;
ArrayLen: Integer;
i: Integer;
begin
Assign(f, 'd:\tempfiles\finalp.txt');
Reset(f);
repeat
Readln(f, n);
Write(n);
until (n = ' ');
Read(f, c);
Write(c);
while not SeekEoln(f) do
begin
read(f, d);
Write(d);
End;
Readln;
Writeln;
StrToIntDef(n, m);
setlength(a, m);
LowArr := Low(a);
HighArr := High(a);
ArrayLen := Length(a);
setlength(e, m);
LowArr := Low(e);
HighArr := High(e);
ArrayLen := Length(e);
for i := LowArr to HighArr do
begin
repeat
Read(f, a[i]);
Write(a[i]);
until (n = ' ');
Read(f, c);
Write(c);
while not SeekEoln(f) do
begin
read(f, e[i]);
Write(e[i]);
End;
Readln;
Writeln;
End;
Readln;
End.
In your first repeat until, you are readlning into a char. The first character will appear in n and the remainder of the characters will be skipped entirely until the newline has been read. AT that point, your file-pointer will be at 2 on the second line of data.
Since your test is for n=' ' then the readln will again be executed, this time delivering 2 into n and pushing the file-pointer to the 1 on the third line.
When eventually end-of-file is reached, a Control-Z character is 'read' from the file. This is the character you are seeing. Since it isn't Space, the loop continues forever.
Change the readln here to a read and one character will be read. (then it works, and you can go on to the next problem...)
Remember, readln reads until it has read a newline. Read reads into the variable - if it's a char, it reads one char. If it's a string, it reads a string - but not the newline.
Program thefinalp;
Uses SysUtils;
Var
f:Text;
m,d:Integer;
n:string;
n2:string;
c:String[1];
a,e:array of integer;//dynamic array//
LowArr:Integer;
HighArr:Integer;
ArrayLen:Integer;
i:Integer;
ch : char;
function readinteger : string;
var
st : string;
begin
st := '';
// read up to first digit
repeat
read(f,ch);
write(ch);
until ch in ['0'..'9'];
//accumulate digits
repeat
st := st + ch;
read(f,ch);
write(ch);
until not (ch in ['0'..'9']);
readinteger := st;
end;
begin
Assign(f,'q21366050.txt');
Reset(f);
// read first integer
n:= readinteger;
// read second integer
n2:= readinteger;
m := StrToInt(n); //puts a string into an integer//
setlength(a,m);
LowArr:=Low(a);
HighArr:=High(a);
ArrayLen:=Length(a);
setlength(e,m);
LowArr:=Low(e);
HighArr:=High(e);
ArrayLen:=Length(e);
for i:= LowArr to HighArr do
begin
// read first integer
n:= readinteger;
// read second integer
n2:= readinteger;
a[i]:=StrToInt(n); //puts a string into an integer//
e[i]:=StrToInt(n2); //puts a string into an integer//
End;
Writeln;
writeln('Results');
for i:= LowArr to HighArr do
writeln(inttostr(i),'=',inttostr(a[i]),',',inttostr(e[i]));
// pause to read results
Readln;
End.
Unfortunately, it's a little difficult to figure out just exactly what you want to do. This routine will read the first line and then put the remaining lines into a[?] and e[?].
Using descriptive variablenames would perform some of the documentation so you can follow what is happening. Since I don't actually know, I'm having to make assumptions and make a few things up to fill in the gaps.
Looking at the main routine, first you assign a filename (I used q21366050.txt for my convenience) and open the file with a reset.
Next job is to read the first number in from the file. Now you have only shown single-digit numbers, but it's easy to set the routine to cope with a sequence.
n:=readinteger;
assigns the result of the function readinteger to the string n
readinteger works this way: first clear the string st which is a "local variable" - only available to this routine. Then keep reading characters into ch until the character read is in the range '0'..'9' - so it skips until it reads a digit. Then it adds the digit read to the string st and continues to read characters and accumulate them until the character found is not a digit. (That character, should we need it, is in ch) We then assign the accumulated string of digits to the resut of the function.
Hence, n will get the first string of digits in the file; the next character has been read,and we know it isn't a digit (otherwise it would have been appended to the string returned).
We then repeat the process with n2. All of the remaining characters before then next digit are skipped, the digit sequence returned and the following character placed in ch
Then we assign the resullt of converting the string n to an integer to m. You haven't described what the other number may be used for, so it's there - but unused.
Set up the two arays, a and e.
Then use the same routine to read the next integer. It doesn't matter that there are CRLF characters - we skip to the next numeric and return it. and repeat that for the second number in the line.
Convert the two numbers and put them into their respective arrays.
Do this m times.
inally, write a new line to the display, then another reporting Results and then repeat m times write a line containing the iteration number i and the values of the two arrays, a and e, all as integers-converted-to-strings and with = and , characters to show that we're not just repeating the dat read from the input.
Finally, wait for an input from the keyboard (since the readln has no explicit filevar) which holds the program open until we can see the results.
Now - nominally, of course, you should also close the file before terminating...

How to convert a string to integer

Example :
a = 1
b = 2
c = 3
..
..
z = 26
aa = 27
ab = 28
how to convert another string into an integer? for example i want to convert 'lmao' to an integer. please help me :) thank you.
in pascal :)
To convert ordinary base-10 strings into numbers, you take each character from left to right, convert it to its numeric value (between 0 and 9) and add it to the total you already have (which you initialize to zero). If there are more characters following the one you just processed, then multiply the total by 10. Repeat until you run out of characters.
For example, the number 374 is 3×102 + 7×101 + 4×100. Another way of writing that, which more closely models the conversion algorithm I described above, is (((3)×10+7)×10+4.
You can adapt that to handle any string of characters, not just numeric characters. Instead of 10, the base is 26, so multiply by that. And instead of digits, the characters are a through z. Your example string would be evaluated like this: (((l)×26+m)×26+a)×26+o. Substitute numbers for those letters, and you get 219,742.
Here's some code to do it. It doesn't check for errors; it assumes that the string will only contain valid characters and that the string won't represent a number that's too big to fit in an Integer variable.
function SpecialStrToInt(const s: string): Integer;
var
i: Integer;
subtotal: Integer;
c: Char;
charval: Integer;
begin
subtotal := 0;
for i := 1 to Length(s) do begin
c := s[i];
charval := Ord(c) - Ord('a') + 1;
subtotal := subtotal * 26;
subtotal := subtotal + charval;
end;
SpecialStrToInt := subtotal;
end;
An oddity about your format is that there's no way to represent zero.

Resources