[Algorithm] Meeting hour optimization (Kanpsack problem) and Dynamic programming
For example we have array of meeting objects:
const data = [
{ name: "m1", hours: },
{ name: "m2", hours: },
{ name: "m3", hours: },
{ name: "m4", hours: },
{ name: "m5", hours: }
];
For a day, 8 hours, we want to take as any meetings as possible:
const res = optimizeMeetings(data, );
You should write function 'optimizeMeetings', get the results of selected meetings to attend.
This problem is the same as Knapack problem, we can construct a table:
hours / total | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
2 | 0 | 2 | 2 | 2 | 2 | 2 | 2 | 2 |
4 | 0 | 2 | 2 | 4 | 4 | 6 | 6 | 6 |
3 | 0 | 2 | 3 | 4 | 5 | 6 | 7 | 7 |
3 | 0 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
1 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
The max hours we can take is the last row & col value, which in the end should be 8.
Then we should trace back the table to find which items should be included.
Final Code:
/**@description
* When we have our result for Knapsack problem, we want to back trace to get the selected items.
*
* What we need to do is trace form last item of the memo, moving up
*/
const backTrace = (hours, totalHours, memo) => {
function helper(memo, row, col) {
let current = memo[row][col];
let selected = [];
while (current >= && row >= && col >= ) {
// If we reach the first row, then check whether we have the remaining?
// If yes then we need to add this row item into final result
if (row === && current !== ) {
selected.push(row);
break;
} let sameRowPrevCol = memo[row][col - ];
let prevRowSameCol = memo[row - ][col]; if (current !== sameRowPrevCol && prevRowSameCol !== current) {
// Item should be selected if the value with sibling values are differnet
selected.push(row);
// calcuate the remaining
col = current - hours[row] - ;
row = row - ;
} else if (prevRowSameCol === current && current !== sameRowPrevCol) {
// current is coming from previous row with the same column, reset row
row = row - ;
} else if (current === sameRowPrevCol && prevRowSameCol !== current) {
// current is coming from previous column with the same row, reset column
col = col - ;
}
// Update current with new row and new column
current = memo[row][col];
}
return selected;
} return helper(memo, hours.length - , totalHours.length - );
}; const getMaxHours = (hours, totalHours) => {
let memo = [...new Array(hours.length)].map(
x => new Array(totalHours.length)
);
function helper(hours, totalHours, memo) {
for (let row in hours) {
const value = hours[row];
for (let col in totalHours) {
// Fill in the first row
if (!memo[row - ]) {
memo[row][col] = value <= totalHours[col] ? value : ;
continue;
} // if the current value is larger than constrain, we use previous value
const prevRowSameCol = memo[row - ][col];
if (value > totalHours[col]) {
memo[row][col] = prevRowSameCol;
continue;
} // if the current value is equal to constrain, then Max{value, prevRowSameCol}
if (value === totalHours[col]) {
memo[row][col] = Math.max(value, prevRowSameCol);
} // if the current value is smaller than constrain
// Math {value + memo[row - 1][diff]: where diff is constrain-value, prevRowSameCol}
if (value < totalHours[col]) {
const diff = totalHours[col] - value - ;
memo[row][col] = Math.max(
prevRowSameCol,
value + memo[row - ][diff]
);
}
}
}
return memo;
}
memo = helper(hours, totalHours, memo);
const selectedIndex = backTrace(hours, totalHours, memo); return {
memo,
selectedIndex
};
}; function* genearteNumberAry(start, num) {
let i = start;
while (i <= num) {
yield i;
i++;
}
} /**
* Main
*/
/**
* @param meetings: [{name: string, hours: number}]
* @param haveHours: number
*
* @returns [meetings]
*/
function optimizeMeetings(meetings, haveHours) {
const hours = meetings.map(m => m.hours);
const haveHoursAry = Array.from(genearteNumberAry(, haveHours));
const { selectedIndex } = getMaxHours(hours, haveHoursAry);
return selectedIndex.map(i => meetings[i]);
} const data = [
{ name: "m1", hours: },
{ name: "m2", hours: },
{ name: "m3", hours: },
{ name: "m4", hours: },
{ name: "m5", hours: }
]; const res = optimizeMeetings(data, );
console.log(JSON.stringify(res)); // [{"name":"m4","hours":3},{"name":"m3","hours":3},{"name":"m1","hours":2}]
[Algorithm] Meeting hour optimization (Kanpsack problem) and Dynamic programming的更多相关文章
- Codeforces 1503C Travelling Salesman Problem(Dynamic Programming)
题意 大家都是优秀生,这点英文还是看得懂的:点此看题 题解 由于旅行路线成一个环,所以从哪里出发不重要,我们把景点按照 a i a_i ai 排序,不妨就从左边最小的出发.基础的旅行费用 c i c ...
- hdu 4223 Dynamic Programming?
Dynamic Programming? Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Oth ...
- hdu 4972 A simple dynamic programming problem(高效)
pid=4972" target="_blank" style="">题目链接:hdu 4972 A simple dynamic progra ...
- [Optimization] Dynamic programming
“就是迭代,被众人说得这么玄乎" “之所以归为优化,是因为动态规划本质是一个systemetic bruce force" “因为systemetic,所以比穷举好了许多,就认为是 ...
- [Optimization] Advanced Dynamic programming
这里主要是较为详细地理解动态规划的思想,思考一些高质量的案例,同时也响应如下这么一句口号: “迭代(regression)是人,递归(recursion)是神!” Video series for D ...
- HDU-4972 A simple dynamic programming problem
http://acm.hdu.edu.cn/showproblem.php?pid=4972 ++和+1还是有区别的,不可大意. A simple dynamic programming proble ...
- 以计算斐波那契数列为例说说动态规划算法(Dynamic Programming Algorithm Overlapping subproblems Optimal substructure Memoization Tabulation)
动态规划(Dynamic Programming)是求解决策过程(decision process)最优化的数学方法.它的名字和动态没有关系,是Richard Bellman为了唬人而取的. 动态规划 ...
- 最优化问题 Optimization Problems & 动态规划 Dynamic Programming
2018-01-12 22:50:06 一.优化问题 优化问题用数学的角度来分析就是去求一个函数或者说方程的极大值或者极小值,通常这种优化问题是有约束条件的,所以也被称为约束优化问题. 约束优化问题( ...
- [Algorithms] Using Dynamic Programming to Solve longest common subsequence problem
Let's say we have two strings: str1 = 'ACDEB' str2 = 'AEBC' We need to find the longest common subse ...
随机推荐
- BZOJ 4213 贪吃蛇 上下界费用流 网络流
https://darkbzoj.cf/problem/4213 https://www.cnblogs.com/DaD3zZ-Beyonder/p/5733326.html 题目描述 dbzoj又崩 ...
- hdu 1429 bfs+状压
题意:这次魔王汲取了上次的教训,把Ignatius关在一个n*m的地牢里,并在地牢的某些地方安装了带锁的门,钥匙藏在地牢另外的某些地方.刚开始 Ignatius被关在(sx,sy)的位置,离开地牢的门 ...
- Atlas 安装运行随笔
Atlas 是一个用于数据库负载均衡 ,读写分离的中间件,他实现了mysql 的语法,对于普通调用DAL 层来说的话,和mysql 是一样的. 一,安装1,从源码安装 , 可以参考 http://bl ...
- 90. 子集 II
90. 子集 II 题意 给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集). 说明:解集不能包含重复的子集. 示例: 输入: [1,2,2]输出:[ [2], [1], ...
- python开发_html_html处理
''' python中,html模块提供了只提供了一个方法: html.escape(s, quote = True) 该方法主要是把html文件中的特殊字符(&,<,>,&quo ...
- windows下python2.7.14版本的安装
本文主要对window下如何安装Python进行图解说明 步骤一.从官网下载相应的版本(本文以2.7.14为例),https://www.python.org/downloads/release/py ...
- Toast信息框
Toast组件的功能和对话框有些相似,可是使用上更简单,使用Toast组件的目的仅仅有一个,就是在屏幕上弹出一个消息窗体告知用户某个信息,并且这个窗体没有不论什么button,经过几秒钟后就会消失.假 ...
- 报错:不允许保存更改。您所做的更改要求删除并重新创建以下表……
在使用SQL Server 2008为某个表添加列的时候出现启用了"阻止保存要求重新创建表的更改问题的设置方法..."报错: 解决方法: 工具--选项--Designers-- ...
- [转载] 关于matlab GUI的一点心得
转载自 落落轻尘 [Fig文件方式,即使用菜单File->New->GUI来设计界面] 首先值得注意的是,在低版本matlab上制作的含GUI的m文件一般不能在高版本的matlab上面运行 ...
- windows tomcat nginx session(当一台tomcat关闭后)
在windows下作nginx负载均衡测试. nginx的配置文件如下: worker_processes 1; events { worker_connections 1024; } http ...