Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

ค้นหา陣列โดยใช้ XOR ต่างกันของสมาชิกในกลุ่มขนาด 4 ใน Java

ภาพรวมปัญหา

เราได้รับอาร์เรย์จำนวนเต็มขนาด N (ซึ่งเป็นพหุคูณของ 4) และต้องดำเนินการ XOR (Exclusive OR) บนอาร์เรย์ดังกล่าว โดยที่ input[1-4] จะสอดคล้องกับ utility_arr[1-4] และเงื่อนไขการคำนวณคือ หาก arr[1-4] = {a1, a2, a3, a4} แล้ว q[1-4] = {a1 ⊕ a2 ⊕ a3, a1 ⊕ a2 ⊕ a4, a1 ⊕ a3 ⊕ a4, a2 ⊕ a3 ⊕ a4}

ตัวอย่าง Input/Output

ตัวอย่างที่ 1

Input: int[] input = { 5, 2, 3, 4 };

Output: ผลลัพธ์หลังการดำเนินการ XOR: 4 3 2 5

คำอธิบาย:

a1 ⊕ a2 ⊕ a3 = 5 ⊕ 2 ⊕ 3 = 4
a1 ⊕ a2 ⊕ a4 = 5 ⊕ 2 ⊕ 4 = 3
a1 ⊕ a3 ⊕ a4 = 5 ⊕ 3 ⊕ 4 = 2
a2 ⊕ a3 ⊕ a4 = 2 ⊕ 3 ⊕ 4 = 5

ตัวอย่างที่ 2

Input: int[] input = { 7, 6, 4, 4, 3, 8, 9, 5 };

Output: ผลลัพธ์หลังการดำเนินการ XOR: 5 5 7 6 2 14 15 4

แนวทางการแก้ปัญหา

  • ใช้สมบัติของ XOR: a ⊕ a = 0 และ a ⊕ 0 = a
  • (a ⊕ b ⊕ c) ⊕ (b ⊕ c ⊕ d) = a ⊕ d (เพราะ (b ⊕ c) ⊕ (b ⊕ c) = 0)
  • แบ่งอาร์เรย์เป็นกลุ่มละ 4 ตัว และใช้สมบัติ XOR คำนวณผลลัพธ์แต่ละกลุ่ม
  • จาก (a ⊕ d) สามารถคำนวณ b และ c ได้: (a ⊕ b ⊕ d) ⊕ (a ⊕ d) = b และ (a ⊕ c ⊕ d) ⊕ (a ⊕ d) = c
  • จาก b และ c สามารถหา a และ d ได้: (a ⊕ b ⊕ c) ⊕ b ⊕ c = a และ (b ⊕ c ⊕ d) ⊕ b ⊕ c = d
  • วนลูปด้วย pointer i และ j จนครบทุกกลุ่ม 4 ตัว

ตัวอย่างโค้ด Java

import java.util.Arrays;

public class Tutorials {
    static int ans = 0;
    public static void main(String args[]) {
        int[] input = {7, 1, 2, 3};
        int[] arr = new int[input.length];
        for (int i = 0, j = 0; j < input.length / 4; j++) {
            ans = input[i] ^ input[i + 3];
            arr[i + 1] = input[i + 1] ^ ans;
            arr[i + 2] = input[i + 2] ^ ans;
            arr[i] = input[i] ^ ((arr[i + 1]) ^ (arr[i + 2]));
            arr[i + 3] = input[i + 3] ^ (arr[i + 1] ^ arr[i + 2]);
            i += 4;
        }
        System.out.println("Different XORs of elements in groups of size 4 is: ");
        for (int i = 0; i < arr.length; i++) {
            System.out.println(arr[i]);
        }
    }
}

ผลลัพธ์

Different XORs of elements in groups of size 4 is : 4 5 6 0