Home > Mobile >  Given an array arr of size n and an integer X. Find if there's a triplet in the array which sum
Given an array arr of size n and an integer X. Find if there's a triplet in the array which sum

Time:11-13

Given an array arr of size n and an integer X. Find if there's a triplet in the array which sums up to the given integer X.

    Input:
        n = 5, X = 10
        arr[] = [1 2 4 3 6]
        
    Output:
        Yes
        
    Explanation:
        The triplet {1, 3, 6} in 
        the array sums up to 10.

CodePudding user response:

the line of reasoning is: Get all the possible combinations of 3 numbers in the array arr. Find which has sum=X, print only these triplets

import numpy as np
import itertools
arr=np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
X=10
combinations=np.array(list(itertools.combinations(arr, 3)))
triplets=combinations[combinations.sum(axis=1)==X]

print(f'Triplets with sum equal to {X} are:\n{triplets}')

output:

Triplets with sum equal to 10 are:
[[0 1 9]
 [0 2 8]
 [0 3 7]
 [0 4 6]
 [1 2 7]
 [1 3 6]
 [1 4 5]
 [2 3 5]]
  • Related