diff --git a/minimal-app/src/features/counter/counterSlice.js b/minimal-app/src/features/counter/counterSlice.js index 60b530ea9df1ea8926e7d47066d33e4c9e27c061..ba8d37e8e8ba2d0b0ecfb1ae78e3c9fdeedf4313 100644 --- a/minimal-app/src/features/counter/counterSlice.js +++ b/minimal-app/src/features/counter/counterSlice.js @@ -3,23 +3,51 @@ import { createSlice } from '@reduxjs/toolkit'; const counterSlice = createSlice({ name: 'counter', initialState: { - value: 0, + candies: [], + maxCandyWeight: 0, + result: { + totalTastiness: 0, + quantities: [], + }, }, reducers: { - setValue: (counter, action) => { - const { - value, - } = action.payload; - counter.value = value; + setCandies: (state, action) => { + state.candies = action.payload; + }, + setMaxWeight: (state, action) => { + state.maxWeight = action.payload; + }, + knapsack: (state) => { + const { candies, maxWeight } = state; + + const dp = Array(maxWeight + 1).fill(0); + const quantities = Array(maxWeight + 1) + .fill(0) + .map(() => Array(candies.length).fill(0)); + + for (let w = 0; w <= maxWeight; w++) { + for (let i = 0; i < candies.length; i++) { + const { tastiness, weight } = candies[i]; + if (weight <= w) { + const newTastiness = dp[w - weight] + tastiness; + if (newTastiness > dp[w]) { + dp[w] = newTastiness; + quantities[w] = [...quantities[w - weight]]; + quantities[w][i] += 1; + } + } + } + } + + state.result.totalTastiness = dp[maxWeight]; + state.result.quantities = quantities[maxWeight]; }, }, }); -export default counterSlice; +export const { setCandies, setMaxWeight, knapsack } = counterSlice.actions; -export const { - setValue, -} = counterSlice.actions; +export const selectCandies = (state) => state.counter.candies; +export const selectMaxWeight = (state) => state.counter.maxWeight; +export const selectResult = (state) => state.counter.result; -export function selectValue(state) { - return state.counter.value; -} +export default counterSlice.reducer; diff --git a/minimal-app/src/index.js b/minimal-app/src/index.js index 98a67e4729efd6f3b4562a19667906f766cb9d53..0e1d5960f8ac2eaaa0250b4558a98d016e1d54e4 100644 --- a/minimal-app/src/index.js +++ b/minimal-app/src/index.js @@ -3,7 +3,7 @@ import { createRoot } from 'react-dom/client'; import { Provider } from 'react-redux'; import { HashRouter as Router } from 'react-router-dom'; -import { store } from './app/store.js'; +import store from './app/store.js'; import { App } from './app.js'; import './index.css';