Search code examples
kdb

Find All Pairs Of Target Sum


Can you please help on solution in kdb to find all pairs of target sum. I have find the solution in java using multiple containers but not able to solve in vector programming.

import java.util.HashMap;
import java.util.Map;

public class FindAllPairsOfTargetSum {

    public static void main(String[] args) {
        int arr[] = { 8, 7, 2, 5, 3, 1 };
        FindAllPairsOfTargetSum.findPairs(arr,10);
    }

    public static void findPairs(int arr[], int sum){
        int[][] arrays =new int[10][] ;
        Map<Integer, Integer> map = new HashMap<Integer,Integer>();
        int pairsarr[][] = new int[arr.length][arr.length];
        for (int i = 0; i<arr.length;i++){
            if(map.containsKey(sum - arr[i])){
                System.out.println(" Pair is found : ("+arr[map.get(sum-arr[i])]+": "+(arr[i])+" )");
            }else{
                map.put(arr[i], i);
            }
        }
    }
}

result:Pair is found : (8: 2 ) Pair is found : (7: 3 )


Solution

  • q)x:8 7 2 5 3 1
    
    q)pairs where 10=sum each pairs:raze {{first[y _ x],/: (y+1) _ x}[x] each y}[x;til count x]
    8 2
    7 3
    

    Breaking it down: uses the til count x idiom to pass in list indices (along with the list) to the lambda {{first[y _ x],/: (y+1) _ x}[x] each y}, which gives:

    (8 7;8 2;8 5;8 3;8 1)
    (7 2;7 5;7 3;7 1)
    (2 5;2 3;2 1)
    (5 3;5 1)
    ,3 1
    ()
    

    raze-ing this result gives

    (8 7;8 2;8 5;8 3;8 1;7 2;7 5;7 3;7 1;2 5;2 3;2 1;5 3;5 1;3 1)
    

    And then we find the elements where the sum of each pair is 10. Also worth looking at the _ drop operator: https://code.kx.com/q/ref/drop/ and for similar problems: https://code.kx.com/q/ref/cross/