Viết chương trình nhập vào 2 mảng số nguyên A, B đại diện cho 2 tập hợp (không thể có 2 phần tử trùng nhau trong một tập hợp). Trong quá trình nhập, phải kiểm tra: nếu phần tử vừa nhập vào đã có trong mảng thì không bổ sung vào mảng. In ra màn hình các phần tử là giống nhau của 2 tập hợp A, B.
Quảng cáo
3 câu trả lời 164
program GiaoTapHop;
const
MAX_SIZE = 100;
var
A, B, GiaoTapHop: array[1..MAX_SIZE] of integer;
sizeA, sizeB, sizeGiao: integer;
i, j, element: integer;
found: boolean;
procedure NhapMang(var arr: array of integer; var size: integer);
var
i: integer;
begin
write('Nhap kich thuoc mang: ');
readln(size);
writeln('Nhap cac phan tu cua mang:');
for i := 1 to size do
begin
repeat
write('Phan tu ', i, ': ');
readln(element);
found := false;
for j := 1 to i - 1 do
begin
if arr[j] = element then
begin
writeln('Phan tu da ton tai trong mang. Nhap lai.');
found := true;
break;
end;
end;
until not found;
arr[i] := element;
end;
end;
procedure TimGiaoTapHop(A, B: array of integer; sizeA, sizeB: integer; var GiaoTapHop: array of integer; var sizeGiao: integer);
var
i, j: integer;
begin
sizeGiao := 0;
for i := 1 to sizeA do
for j := 1 to sizeB do
if A[i] = B[j] then
begin
sizeGiao := sizeGiao + 1;
GiaoTapHop[sizeGiao] := A[i];
end;
end;
procedure InMang(arr: array of integer; size: integer);
var
i: integer;
begin
writeln('Cac phan tu cua mang la:');
for i := 1 to size do
write(arr[i], ' ');
writeln;
end;
begin
NhapMang(A, sizeA);
NhapMang(B, sizeB);
TimGiaoTapHop(A, B, sizeA, sizeB, GiaoTapHop, sizeGiao);
writeln('Cac phan tu la giao cua hai tap hop:');
InMang(GiaoTapHop, sizeGiao);
end.
def nhap_mang():
n = int(input("Nhập số phần tử của mảng: "))
return [int(input(f"Nhập phần tử thứ {i + 1}: ")) for i in range(n)]
# Nhập mảng A và mảng B
mang_A, mang_B = nhap_mang(), nhap_mang()
# Tìm và in ra các phần tử giống nhau
giong_nhau = set(mang_A) & set(mang_B)
if giong_nhau == True: print("Các phần tử giống nhau của hai tập hợp A và B là:", giong_nhau)
else: print("Không có các phần tử giống nhau của hai tập hợp A và B.")
Chúc bạn học tốt!
Quảng cáo
Câu hỏi hot cùng chủ đề
-
6047