Skip to content
Snippets Groups Projects
Commit 19bc18b0 authored by jguzman12's avatar jguzman12
Browse files

fixed errors

parent 76ec8fc5
No related branches found
No related tags found
No related merge requests found
...@@ -3,23 +3,51 @@ import { createSlice } from '@reduxjs/toolkit'; ...@@ -3,23 +3,51 @@ import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({ const counterSlice = createSlice({
name: 'counter', name: 'counter',
initialState: { initialState: {
value: 0, candies: [],
maxCandyWeight: 0,
result: {
totalTastiness: 0,
quantities: [],
},
}, },
reducers: { reducers: {
setValue: (counter, action) => { setCandies: (state, action) => {
const { state.candies = action.payload;
value,
} = action.payload;
counter.value = value;
}, },
setMaxWeight: (state, action) => {
state.maxWeight = action.payload;
}, },
}); knapsack: (state) => {
export default counterSlice; const { candies, maxWeight } = state;
export const { const dp = Array(maxWeight + 1).fill(0);
setValue, const quantities = Array(maxWeight + 1)
} = counterSlice.actions; .fill(0)
.map(() => Array(candies.length).fill(0));
export function selectValue(state) { for (let w = 0; w <= maxWeight; w++) {
return state.counter.value; 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 const { setCandies, setMaxWeight, knapsack } = counterSlice.actions;
export const selectCandies = (state) => state.counter.candies;
export const selectMaxWeight = (state) => state.counter.maxWeight;
export const selectResult = (state) => state.counter.result;
export default counterSlice.reducer;
...@@ -3,7 +3,7 @@ import { createRoot } from 'react-dom/client'; ...@@ -3,7 +3,7 @@ import { createRoot } from 'react-dom/client';
import { Provider } from 'react-redux'; import { Provider } from 'react-redux';
import { HashRouter as Router } from 'react-router-dom'; 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 { App } from './app.js';
import './index.css'; import './index.css';
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment