Last active
August 29, 2015 14:14
-
-
Save thomascrha/247fa9dfe6f246546203 to your computer and use it in GitHub Desktop.
Angry Children - (Incomplete: memory hog)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*Problem Statement | |
Given a list of N integers, your task is to select K integers from the list such that it's unfairness is minimized. | |
if (x1,x2,x3,…,xk) are K numbers selected from the list N, the unfairness is defined as | |
max(x1,x2,…,xk)−min(x1,x2,…,xk) | |
where max denotes the largest integer among the elements of K, and min denotes the smallest integer among the elements of K. | |
Input Format | |
The first line contains an integer N. | |
The second line contains an integer K. N lines follow. Each line contains an integer that belongs to the list N. | |
Note | |
Integers in the list N may not be unique. | |
Output Format | |
An integer that denotes the minimum possible value of unfairness. | |
Constraints | |
2≤N≤105 | |
2≤K≤N | |
0≤integer in N ≤109 | |
*/ | |
function processData(input) { | |
var array = input.replace( /\n/g, " " ).split( " " ); | |
var numNumbers = array[1]; | |
var numInGroup = array[0]; | |
var numSet = array.splice(2,array[0]); | |
var numSets = k_combinations(numSet,numNumbers); | |
var resultArr = []; | |
for(var i = 0;i<=numSets.length;i++){ | |
var min = Math.min.apply(null, numSets[i]); | |
var max = Math.max.apply(null, numSets[i]); | |
var temp = max - min; | |
//console.log(temp + " " + min + " " + max + " " + numSets[i]) | |
resultArr.push(temp); | |
} | |
resultArr.pop(); | |
console.log(Math.min.apply(null, resultArr)); | |
} | |
function k_combinations(set, k) { | |
var i, j, combs, head, tailcombs; | |
if (k > set.length || k <= 0) { | |
return []; | |
} | |
if (k == set.length) { | |
return [set]; | |
} | |
if (k == 1) { | |
combs = []; | |
for (i = 0; i < set.length; i++) { | |
combs.push([set[i]]); | |
} | |
return combs; | |
} | |
// Assert {1 < k < set.length} | |
combs = []; | |
for (i = 0; i < set.length - k + 1; i++) { | |
head = set.slice(i, i+1); | |
tailcombs = k_combinations(set.slice(i + 1), k - 1); | |
for (j = 0; j < tailcombs.length; j++) { | |
combs.push(head.concat(tailcombs[j])); | |
} | |
} | |
return combs; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment