0
I’m struggling with a problem, which at first I thought was quite trivial, but in the end I couldn’t do it. It is an exercise in a proof of Algorithms it is below:
MASTERMIND GAME
CONSIDER THE FOLLOWING DEFINITIONS:
const MAX = 20; CORINI = 1; CORFIM = 30;
type cores: CORINI..CORFIM; (*faixa de valores, subtipo de integer*)
vetor = array [1..MAX] of cores;
1.Write, in Pascal, procedures or functions for:
(a)Read a vector with n [2. MAX] color type elements, ensuring that all elements belong to the range[CORINI,CORFIM] and that there is no repeated element in the read vector;
I did the program in the Pascal language, but I have the following error:
I don’t know how, accept any user value, integer say, and assign it in a variable of type colors. My code is below:
program mastermind;
const MAX = 20; CORINI = 1; CORFIM = 30;
type cores = CORINI..CORFIM; (*faixa de valores, subtipo de integer*)
vetor = array [1..MAX] of cores;
var vetor_de_cores: vetor; n: integer;
function esta_no_intervalo(n: integer): Boolean;
begin
esta_no_intervalo:= False;
if (n >= 1) and (n <= 30) then
esta_no_intervalo:= True;
end;
function eh_repetido(vetor_de_cores: vetor; limitador: integer; x: integer): Boolean;
var i: integer;
begin
eh_repetido:= True;
if limitador = 1 then
eh_repetido:= False
else
begin
for i:= 1 to limitador-1 do
begin
if vetor_de_cores[i] = x then
eh_repetido:= False;
end;
end;
end;
function valor_valido(var x: cores; vetor_de_cores: vetor; i: integer): cores;
begin
while (esta_no_intervalo(x) = False) or (eh_repetido(vetor_de_cores, i, x) = True) do
begin
writeln('Entrada invalida');
read(x);
valor_valido:= x;
end;
end;
procedure ler_vetor(var n: integer; var vetor_de_cores: vetor);
var i: integer; x: integer;
begin
for i:= 1 to n do
begin
read(x);
vetor_de_cores := valor_valido(x, vetor_de_cores, i);
end;
end;
(*PROGRAMA PRINCIPAL*)
begin
read(n); (*n é um tam do vetor entre 2 e MAX*)
ler_vetor(n, vetor_de_cores);
end.
On the line 50 you are calling the function
valor_valido
passing the first argument the "x" which was declared as integer. It is expecting a variable of type "colors".vetor_de_cores := valor_valido(x, vetor_de_cores, i);
. Tip: Change the type of the function’s first argumentvalor_valido
, thus:function valor_valido(var x: integer; vetor_de_cores: vetor; i: integer): cores;
– Rodrigo Tognin
I made the modifications, but the problem remains, because the function 'valued' takes 'x', but this x is of type integer.
– Pedro
I also realized that if I modify all occurrences of x, for the type 'colors', if the user type a value above 255 or less than 0 the result is a pseudorandom number, but that in some moments is in the range of type 'colors''.
– Pedro