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

fixed errors

parent 76ec8fc5
Branches
Tags
No related merge requests found
......@@ -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;
},
});
export default counterSlice;
knapsack: (state) => {
const { candies, maxWeight } = state;
export const {
setValue,
} = counterSlice.actions;
const dp = Array(maxWeight + 1).fill(0);
const quantities = Array(maxWeight + 1)
.fill(0)
.map(() => Array(candies.length).fill(0));
export function selectValue(state) {
return state.counter.value;
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 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';
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';
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment