fork download
  1. #include <stdio.h>
  2. #include <stdbool.h>
  3.  
  4. bool hasDuplicates(int arr[], int n) {
  5. // สร้างอาร์เรย์ตรวจสอบการปรากฏของตัวเลข
  6. bool seen[n];
  7.  
  8. // กำหนดค่าเริ่มต้นทุกช่องเป็น false (ยังไม่เจอ)
  9. for (int i = 0; i < n; i++) {
  10. seen[i] = false;
  11. }
  12.  
  13. // วนลูปผ่านทุกค่าของอาร์เรย์
  14. for (int i = 0; i < n; i++) {
  15. // ถ้าเจอตัวเลขซ้ำที่เคยเจอแล้วใน seen[] ให้ return true
  16. if (seen[arr[i]]) {
  17. return true; // พบค่าซ้ำ
  18. }
  19. // ถ้ายังไม่เจอ ให้ทำเครื่องหมายว่าเจอแล้ว
  20. seen[arr[i]] = true;
  21. }
  22.  
  23. // ถ้าไม่มีค่าซ้ำเลย
  24. return false;
  25. }
  26.  
  27. int main() {
  28. int arr[] = {0, 2, 3, 1, 4, 5, 2}; // ตัวอย่างอาร์เรย์ที่มีค่าซ้ำ
  29. int n = sizeof(arr) / sizeof(arr[0]); // ขนาดของอาร์เรย์
  30.  
  31. if (hasDuplicates(arr, n)) {
  32. printf("อาร์เรย์นี้มีค่าซ้ำ\n");
  33. } else {
  34. printf("อาร์เรย์นี้ไม่มีค่าซ้ำ\n");
  35. }
  36.  
  37. return 0;
  38. }
Success #stdin #stdout 0.01s 5284KB
stdin
Standard input is empty
stdout
อาร์เรย์นี้มีค่าซ้ำ