fork download
  1. const dishes = [
  2. { "id": 0, "name": "Pizza", "price": 8, "vote": 12 },
  3. { "id": 1, "name": "Gà rán", "price": 5, "vote": 9 },
  4. { "id": 2, "name": "Khoai tây chiên", "price": 3, "vote": 7 },
  5. { "id": 3, "name": "Trà sữa", "price": 3, "vote": 6 },
  6. { "id": 4, "name": "Bánhngọt", "price": 2, "vote": 4 }
  7. ]
  8. const budget = 10;
  9. const n = dishes.length;
  10. const S = {
  11. length: n,
  12. depth: 0,
  13. choices: [1, 0],
  14. current_state: [],
  15. arr: dishes,
  16. }
  17.  
  18. function f(S, result) {
  19. if (S.depth === n) {
  20. result.push([...S.current_state]);
  21. return;
  22. }
  23. for (const choice of S.choices) {
  24. if (choice) {
  25. S.current_state = [...S.current_state, dishes[S.depth]]
  26. }
  27. S.depth += 1;
  28.  
  29. f(S, result);
  30.  
  31. S.depth -= 1;
  32. if (choice) {
  33. S.current_state.pop();
  34. }
  35. }
  36. }
  37. let result = []
  38. f(S, result)
  39. let answer_array = [];
  40. let maxVote = 0;
  41. for (const state of result) {
  42. let sumVote = 0;
  43. let sumPrice = 0;
  44. for (const dish of state) {
  45. sumVote += dish.vote
  46. sumPrice += dish.price
  47. }
  48. if (sumVote > maxVote && sumPrice <= budget) {
  49. answer_array = [...state]
  50. maxVote = sumVote
  51. }
  52. }
  53. console.log(JSON.stringify(answer_array))
  54.  
Success #stdin #stdout 0.03s 17304KB
stdin
Standard input is empty
stdout
[{"id":1,"name":"Gà rán","price":5,"vote":9},{"id":2,"name":"Khoai tây chiên","price":3,"vote":7},{"id":4,"name":"Bánhngọt","price":2,"vote":4}]