Provided a 1D array of integers, find all combinations of 3 values from this set
ID: 3547695 • Letter: P
Question
Provided a 1D array of integers, find all combinations of 3 values from this set such that:
a+b+c=0
For example, if one were provided with the set [3 1 3 -4 -6], the resulting answers would be [3 1 -4], [3 1 -4], and [3 3 -6], as these are the three sets of three values which sum to zero from the provided set. Notice that the first and second solution appear to be the same, but correspond to two solutions for the two different 3s in the provided set. Your code should return the answer in 2D array format, where each row is a solution set (3 columns per row). If no solution sets can be found for a given input, the code should output a value of zero.
For this assignment you should find or develop an algorithm for finding these solutions. Once you have found or developed this algorithm, create a flowchart for this algorithm. Your code should be adequately commented, such that one would be able to understand your code by reading comments only. Your code should also include an initial code block giving a brief overview of how to use the function and your solution process, so that someone can query your program for this code block using the help command. Please do NOT use the MATLAB built-in functions perms(), nchoosek(), or the like. This means you should loop through the array yourself to find the required sets.
Develop and implement a method to identify and remove and solutions which are numerically equivalent, so that the result from your code doesn't have any repeated solutions. This should be able to match solutions which contain the same values but in different orders. This means that if the sets [3 1 -4] and [3 -4 1] are in the solution your method should still identify them as equivalent and only return one of them.
Explanation / Answer
function [A]= find_solution(array)
%% INPUT----This function takes as input 'array'
%%'array' must be 1- dimensional vector
%% This computes the number unique solutions for x+y+z=0,where x,y,z coresspond to different elements in the array
%% OUTPUT--- number unqiue solutions.
len=length(array); % len is the length of the input array
p=1; %% used to keep track of the number of solutions
for i=1:len
for j=1:len
for k=1:len
value=array(i)+array(j)+array(k);
if(value==0)
%index(p,:)=sort([i j k]);
solution(p,:)=sort([array(i) array(j) array(k)]); %Iam storing each every possible solution in 'solution' array
% each solution is stored in sorted manner so that identical solutions may be removed in the next part of program
p=p+1;
end
end
end
end
[A,B,C]=unique(solution,'rows'); %% unique(matric,'rows') gives number unique row vectors present in given matrix
display('The solution is:');
A
end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.