How to convert a string to integer - pascal

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.

Related

TPascal, Stack Overflow, Recursion

My program should inverse a string (ex. for Hello world returns dlrow olleH) and it works only for strings smaller than 20 characters. For 20 or more i get "Error 202 Stack overflow". Thank you :)
Program Inv;
var S, A: String;
n: integer;
Function I(X: String; z: integer):String;
begin
if z=1 then I:=X[z] else
I:=X[z]+I(X, z-1);
end;
begin
write ('Enter your text: ');
readln (S);
n:=length(S);
A:=I(S, n);
writeln (A);
readln;
end.
Unless you are required to show a recursive solution, you're usually better to sticking with iteration(a). Recursion uses an often-limited resource (the stack) to weave its magic and is often the cause of crashes when you exceed that limit.
Iterative solutions tend to be far less restrictive, such as the code below:
program PaxCode;
Function reverse(inp_str: string) : string;
var out_str : string = '';
var idx : integer = 1;
begin
while (idx <= length(inp_str)) do
begin
out_str := inp_str[idx] + out_str;
idx := idx + 1
end;
reverse := out_str
end;
var test_str: string = 'My hovercraft is full of eels and they will not let me drive it';
begin
writeln(test_str);
writeln(reverse(test_str))
end.
As you can see, the output is correct, and not limited to twenty (or twenty-nine) characters:
My hovercraft is full of eels and they will not let me drive it
ti evird em tel ton lliw yeht dna slee fo lluf si tfarcrevoh yM
(a) The best areas for recursion are those where each level removes a sizable proportion of the solution space. For example, binary searches remove fully 50% of the remaining solution space on every level so you could search through a structure holding four billion entries with just thirty-two levels, since 232 is a touch above 4.2 billion.
Something like reversing a 400-character string will take, ..., let me think, oh yes, 400 levels. That won't necessarily end well :-)

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.

How to convert values from characters to numbers

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

Most repeated character in a row

My task is to show most used letter in a row. For example if you put in aabbbbccbbb most repeated character is B and it is used 4 times. There was a very similar topic about the same task, but i didnt understand the code. Most repeating character in a string
Program Task;
var s:string;
i,k,g,count:integer;
c:char;
begin
Readln(s);
g:=0;
while Length(s) > 0 do
begin
c := s[1];
i:=1;
while i<= Length(s) do
begin
If (c=s[i]) then
delete(s,i,1)
else
Inc(i);
If (c=s[i]) then
Inc(g);
end;
end;
Writeln(g);
Readln;
end.
There are many problems i face. First is i dont know how to show which character is most used and second is i dont know how compare which one of repeating characters is most used.
For example if i write aaaabbbc it will give me answer of 7 because there is 4xa and 3xb.
All the help is most appreciated.
If it's just about english characters, you might just allocate an array to keep a count per character. In that case, the code could look like this.
I wrote this using Delphi. I hope it works as well in your flavour of Pascal.
program Task;
{$APPTYPE CONSOLE} // For Delphi
var
s: string[50];
i: Integer;
Counters: array[Char] of Integer;
Highest: Char;
begin
// Initialize counters.
for i := 0 to 255 do
Counters[Char(i)] := 0;
s := 'aabbbbccbbb';
// Count the characters.
for i := 1 to Length(s) do
Inc(Counters[s[i]]);
// Find out which one is highest.
Highest := #0;
for i := 0 to 255 do
if Counters[Char(i)] > Counters[Highest] then
Highest := Char(i);
// Output that character and its count.
WriteLn('The highest character is ', Highest, ' with ', Counters[Highest], ' occurrences.');
ReadLn;
end.
In less academic setups, using an array like this might not be the most efficient, because it contains a counter for every possible character, including those that don't occur in the string at all. That means, if you want to use this exact code for every possible character in the unicode table, your array would be a couple of megabytes large (still not really a problem on modern computers, but still).
You can improve this code by using a kind of dictionary or list to keep track of the items, so you need only to add those items you find, but if you have to write that yourself, it will make your program quite a bit larger.
EDIT:
As per request in comment: Counting the longest subsequent range of characters:
program Task;
{$APPTYPE CONSOLE} // For Delphi
var
s: String;
i: Integer;
Longest: Integer;
Current: Integer;
LongestChar: Char;
begin
s := 'aabbbbccbbb';
Longest := 0;
Current := 0;
// Count the characters.
for i := 1 to Length(s) do
begin
Inc(Current);
// If it's the last char or the next char is going to be different, restart the counting.
if (i = Length(s)) or (s[i] <> s[i+1]) then
begin
if Current > Longest then
begin
Longest := Current;
LongestChar := s[i];
end;
Current := 0;
end;
end;
// Output that character and its count.
WriteLn('The highest character is ', LongestChar, ' with ', Longest, ' occurrences.');
ReadLn;
end.
Current > Longest makes sure the first longest sequence is returned in case multiple character sequences have the same length. Change to Current >= Longest if you want the last sequence instead.

How to use Pascal string in equation

I have a little problem. I have written a program which asks for user for a code which contains 11 digits. I defined it as string but now I would like to use every digit from this code individually and make an equation.
for example if code is 37605030299 i need to do equation:
(1*3 + 2*7 + 3*6 + 4*0 + 5*5 + 6*0 + 7*3 + 8*0 + 9*2 + 1*9) / 11
and find out what's the MOD.
This is a calculation for an ISBN check digit.
Use a loop instead. (I'm only showing the total value and check digit calculation - you need to get the user input first into a variable named UserISBN yourself.)
function AddCheckDigit(const UserISBN: string): string;
var
i, Sum: Integer;
CheckDigit: Integer;
LastCharValue: string;
begin
Assert(Length(UserISBN) = 10, 'Invalid ISBN number.');
Sum := 0;
for i := 1 to 10 do
Sum := Sum + (Ord(UserISBN[i]) * i);
{ Calculate the check digit }
CheckDigit := 11 - (Sum mod 11);
{ Determine check digit character value }
if CheckDigit = 10 then
LastCharValue := 'X'
else
LastCharValue := IntToStr(CheckDigit);
{ Add to string for full ISBN Number }
Result := UserISBN + LastCharValue;
end;

Resources