random - Given 4 numbers of array of 1 to 10 elements. Find 3 numbers whose sum can generate all the four numbers? -
i given array containing list of 4 random numbers (1 10 inclusive). supposed generate list of 3 numbers (1 10 inclusive) can generate 4 numbers of initial list adding 3 numbers of generated list.
someone please provide algorithm doing this.
since solution contains 3 numbers in 1..10 range, brute force effective algorithm here (at 1000 possibilities check in naive implementation). c# code be
public static int[] bruteforce(int[] data) { hashset<int> hs = new hashset<int>(); (int x = 1; x <= 10; ++x) (int y = x; y <= 10; ++y) (int z = y; z <= 10; ++z) { hs.clear(); (int = 0; < data.length; ++i) hs.add(data[i]); hs.remove(x); hs.remove(y); hs.remove(z); hs.remove(x + y); hs.remove(x + z); hs.remove(y + z); hs.remove(x + y + z); if (hs.count <= 0) return new int[] { x, y, z }; // <- solution } return new int[] {}; // <- no solution found }
some test cases:
- bruteforce(new int[] {1, 3, 7, 8}); // <- [1, 2, 5]
- bruteforce(new int[] {1, 3, 7, 9}); // <- [1, 2, 6]
- bruteforce(new int[] {1, 6, 7, 9}); // <- [1, 2, 6]; same previous case
- bruteforce(new int[] {4, 6, 7, 9}); // <- [1, 3, 6]
- bruteforce(new int[] {5, 6, 7, 9}); // <- [2, 3, 4]
- bruteforce(new int[] {1, 2, 4, 8}); // <- no solution found
even problem set (all possible lists of 4 items in 1..10 range) small enough (10000 items) solved brute force algorithm implemented above. can find out 768 4-items lists 10000 can't generated 3-items lists.
Comments
Post a Comment