Kiểm tra 2 mảng tại vị trí có cùng phần tử?
Viết chương trình JavaScript để kiểm tra xem hai mảng số nguyên có cùng độ dài có giống nhau hay không. Các mảng sẽ tương tự nhau nếu một mảng có thể được lấy từ một mảng khác bằng cách hoán đổi nhiều nhất một cặp phần tử.
Ví dụ:

Mã nguồn:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Write a JavaScript program to check whether two arrays of integers of same length are similar or not. The arrays will be similar if one array can be obtained from another array by swapping at most one pair of elements</title>
<script>
function array_checking(arra1, arra2) {
for(var i = 0; i < arra1.length; i++) {
for(var j = i; j < arra1.length; j++) {
var result = true,
temp = arra1[i];
arra1[i] = arra1[j];
arra1[j] = temp;
for(var k = 0; k < arra1.length; k++) {
if(arra1[k] !== arra2[k]) {
result = false;
break;
}
}
if(result) {
return true;
}
arra1[j] = arra1[i];
arra1[i] = temp;
}
}
return false;
}
document.write(array_checking([10,20,30], [10,20,30])+"<br/>")
document.write(array_checking([10,20,30], [30,10,20])+"<br/>")
document.write(array_checking([10,20,30,40], [10,30,20,40])+"<br/>")
</script>
</head>
<body>
</body>
</html>
Lưu đồ thuật toán:

Thấy bài viết hữu ích?
Ủng hộ tác giả để có thêm nhiều bài viết chất lượng nhé!