4 Commits

Author SHA1 Message Date
=
5feee1007b hw 8 done (Thank You!) 2026-04-24 19:57:14 +10:00
=
4532122dee logic done 2026-04-24 17:44:39 +10:00
=
4e2f4eb525 added all components 2026-04-24 17:03:42 +10:00
=
1335275ed7 refactored quiz slice, site loads 2026-04-24 16:09:47 +10:00
8 changed files with 326 additions and 120 deletions

View File

@@ -30,6 +30,7 @@ export function SortableItem({ item ,isDisabled}: SortableItemProps) {
sx={{ sx={{
border: '1px solid gray', border: '1px solid gray',
borderRadius: '5px', borderRadius: '5px',
height:"4.4em"
}}> }}>
<ListItemIcon> <ListItemIcon>
<DragIndicatorIcon /> <DragIndicatorIcon />

View File

@@ -0,0 +1,72 @@
import { Grid, List, ListItem, ListItemButton, ListItemText } from '@mui/material';
import { useDispatch, useSelector } from 'react-redux';
import type { tTasks } from "../quizData"
import { useEffect } from 'react';
import { addList, mixUp } from './quizSlice';
import Checkbox from '@mui/material/Checkbox';
import type { RootState } from '../../store';
import type { ChangeEvent } from 'react';
import { setCheckedItems } from './quizSlice';
interface ComponentProps {
tasks: tTasks;
index: number;
}
function Matching({ tasks, index }: ComponentProps) {
const dispatch = useDispatch();
const answers: boolean[] = tasks.map((item) => Boolean(item.answer));
const items: string[] = tasks.map((item) => String(item.answer));
const arr = useSelector((state: RootState) => state.quiz.userAnswers[index]);
// const correctAnswers = useSelector((state: RootState) => state.quiz.correctAnswers[index]);
const questions = useSelector((state: RootState) => state.quiz.questions[index]);
const isDisabled = useSelector((state: RootState) => state.quiz.isTestingDone);
useEffect(() => {
dispatch(addList({ index, items: items,questions:tasks.map((item) => String(item.question)), answers: answers, quizType: "M" }));
}, []);
useEffect(() => {
dispatch(mixUp());
}, []);
const handleCheckboxAction = (checkboxIndex: number) => (_: ChangeEvent<HTMLInputElement, Element>, checked: boolean) => {
let answersCopy = arr.map((x)=>(Boolean(x)));
answersCopy[checkboxIndex] = checked;
dispatch(setCheckedItems({ index, items: answersCopy }));
};
// console.log(arr);
return (
<Grid container spacing={2}>
<Grid size={12}>
<List>
{tasks.map((_, itemIndex) => (
<ListItem key={itemIndex}>
<ListItemButton
sx={{
border: '1px solid gray',
borderRadius: '5px',
textAlign: 'right',
}}>
<ListItemText primary={arr == undefined ? "loading": questions[itemIndex]} />
<Checkbox
onChange={isDisabled ? (..._) => { _ } : handleCheckboxAction(itemIndex)}
checked={Boolean(arr == undefined ? false : arr[itemIndex])}
sx={{ '& .MuiSvgIcon-root': { fontSize: 28 } }}
/>
</ListItemButton>
</ListItem>
))}
</List>
</Grid>
<Grid size={12}>
</Grid>
</Grid>
);
}
export default Matching

View File

@@ -1,51 +1,52 @@
import { Grid, List, ListItem, ListItemButton, ListItemText } from '@mui/material'; import { Grid, List, ListItem, ListItemButton, ListItemText } from '@mui/material';
import type {tTasks} from "../quizData" import type { tTasks } from "../quizData"
import SortableList from '../features/SortableList'; import SortableList from '../features/SortableList';
import { useEffect } from 'react'; import { useEffect } from 'react';
import { useDispatch } from 'react-redux'; import { useDispatch } from 'react-redux';
import { addList,mixUp } from './quizSlice'; import { addList, mixUp } from './quizSlice';
interface ComponentProps { interface ComponentProps {
tasks: tTasks; tasks: tTasks;
index: number; index: number;
} }
function Matching({tasks,index}: ComponentProps) { function Matching({ tasks, index }: ComponentProps) {
const dispatch = useDispatch(); const dispatch = useDispatch();
const answers: string[] = tasks.map((item) => String(item.answer));
// Добавляем список ответов очередного задания в хранилище // Добавляем список ответов очередного задания в хранилище
useEffect(() => { useEffect(() => {
dispatch(addList({ index, items: answers })); dispatch(addList({ index, items: answers, answers:answers, questions:tasks.map((item) => String(item.question)), quizType: "M" }));
}, []); }, []);
useEffect(() => { useEffect(() => {
dispatch(mixUp()); dispatch(mixUp());
}, []); }, []);
const answers: string[] = tasks.map((item) => String(item.answer));
return ( return (
<Grid container spacing={2}> <Grid container spacing={2}>
<Grid size={6}> <Grid size={6}>
<List> <List>
{tasks.map((item, index) => ( {tasks.map((item, index) => (
<ListItem key={index}> <ListItem key={index}>
<ListItemButton <ListItemButton
sx={{ sx={{
border: '1px solid gray', border: '1px solid gray',
borderRadius: '5px', borderRadius: '5px',
textAlign: 'right', textAlign: 'right',
}}> height:"4.4em"
<ListItemText primary={item.question} /> }}>
</ListItemButton> <ListItemText primary={item.question} />
</ListItem> </ListItemButton>
</ListItem>
))} ))}
</List> </List>
</Grid> </Grid>
<Grid size={6}> <Grid size={6}>
<SortableList index={index} answers={answers}/> <SortableList index={index} answers={answers} />
</Grid> </Grid>
</Grid> </Grid>
); );
} }

View File

@@ -1,34 +1,50 @@
import { Box, Button, Container, Typography } from '@mui/material'; import { Box, Button, Container, Typography } from '@mui/material';
import { quiz } from "../quizData"; import { quiz } from "../quizData";
import { useSelector } from 'react-redux'; import { useSelector } from 'react-redux';
import {useState } from 'react'; import { useState } from 'react';
import Matching from './Matching'; import Matching from './Matching';
import Sorting from './Sorting';
import Choosing from './Choosing';
import type { RootState } from '../../store'; import type { RootState } from '../../store';
import store from '../../store'; import store from '../../store';
import { useDispatch } from 'react-redux'; import { useDispatch } from 'react-redux';
import { mixUp, startTesting, stopTesting } from './quizSlice'; import { mixUp, startTesting, stopTesting } from './quizSlice';
function QuizStats() { function QuizStats() {
let correctAnswers = useSelector((state: RootState) => state.quiz.correctAnswers);
const userAnswers = useSelector((state: RootState) => state.quiz.userAnswers);
const checkTask = (index: number): string => { const correctCount = (index: number): number => {
useSelector((state: RootState) => state.lists.lists[index]);
let state = store.getState(); let state = store.getState();
if (state.lists.correctAnswers.length <= index) { if (state.quiz.correctAnswers.length <= index) {
return ""; return 0;
} }
let correctCounter = state.lists.lists[index].reduce((prev, answ, i) => prev + Number(state.lists.correctAnswers[index][i] === answ), 0) return userAnswers[index].reduce((prev, answ, i) => prev + Number(correctAnswers[index][i] === answ), 0);
if (correctCounter == state.lists.lists[index].length) {
return "все ответы верные"
}
return `верно ${correctCounter}/${state.lists.lists[index].length}`
} }
const counts = userAnswers.map((_,index)=>correctCount(index));
const questionCounts = userAnswers.map((answers)=>answers.length);
const total= counts.reduce((x,c)=>c+x,0);
const totalQuestionCount= questionCounts.reduce((x,c)=>c+x,0);
const donePercentage = Math.round(total/totalQuestionCount*100*100)/100;
const quizPartText = (counter: number, len: number, taskIndex:number) => {
if (counter == len) {
return <Typography key={taskIndex}>Task {taskIndex+1}: everethyng is correct</Typography>
}
return <Typography key={taskIndex}>Task {taskIndex+1}: correct {counter}/{len}</Typography>
}
return ( return (
<Container sx={{ margin: "auto" }}> <Container sx={{ margin: "auto", d:"flex",flexDirection:"column" }}>
<h3>Результаты теста</h3> <h2>Результаты теста</h2>
<Typography>Задание 1: {checkTask(0)}</Typography> {
<Typography>Задание 2: {checkTask(1)}</Typography> counts.map((count,idx)=>quizPartText(count,questionCounts[idx],idx))
}
<h3>Итого {donePercentage}% Верно</h3>
</Container> </Container>
) )
} }
@@ -42,6 +58,7 @@ function Quiz() {
dispatch(mixUp()); dispatch(mixUp());
dispatch(startTesting()); dispatch(startTesting());
} }
const checkQuiz = () => { const checkQuiz = () => {
setDisplayingResults(true); setDisplayingResults(true);
dispatch(stopTesting()); dispatch(stopTesting());
@@ -51,18 +68,27 @@ function Quiz() {
return ( return (
<Container maxWidth="md"> <Container maxWidth="md">
{quiz.map((item, index) => ( {quiz.map((item, index) => (
<Box key={item.id} component="section" sx={{ m: 2, p: 2 }}> <Box key={item.id} component="section" sx={{ m: 2, p: 2}}>
<Typography variant="h5" gutterBottom> <Typography variant="h5" gutterBottom>
{index + 1}. {item.title} {index + 1}. {item.title}
</Typography> </Typography>
<Matching index={index} tasks={item.tasks} /> {[
</Box>
))} <Matching index={index} tasks={item.tasks} key={index}/>,
<Sorting index={index} tasks={item.tasks} key={index}/>,
<Choosing index={index} tasks={item.tasks} key={index}/>
][(["M", "S", "C"].indexOf(item.type))]}
</Box>
))}
<Box sx={{ display: 'flex', justifyContent: 'space-around' }}>
<Button onClick={checkQuiz} variant="contained">Check</Button>
<Button onClick={resetQuiz} variant="contained">Reset</Button>
</Box>
<Box sx={{ display: 'flex', justifyContent: 'space-around' }}>
<Button onClick={checkQuiz} variant="contained">Проверить</Button>
<Button onClick={resetQuiz} variant="contained">Начать снова</Button>
</Box>
{displayingResults && <QuizStats />} {displayingResults && <QuizStats />}
</Container> </Container>

View File

@@ -4,8 +4,7 @@ import { useDispatch, useSelector } from 'react-redux';
import { setDraggedItems } from './quizSlice'; import { setDraggedItems } from './quizSlice';
import type { RootState } from '../../store'; import type { RootState } from '../../store';
import List from '@mui/material/List'; import List from '@mui/material/List';
import { SortableItem } from '../components/SortableItem' import { SortableItem } from '../components/SortableItem';
interface ComponentProps { interface ComponentProps {
index: number; index: number;
answers: string[]; answers: string[];
@@ -14,8 +13,8 @@ interface ComponentProps {
function SortableList({ index}: ComponentProps) { function SortableList({ index}: ComponentProps) {
const dispatch = useDispatch(); const dispatch = useDispatch();
const arr = useSelector((state: RootState) => state.lists.lists[index]) const arr = useSelector((state: RootState) => state.quiz.userAnswers[index])
const isDisabled = useSelector((state: RootState) => state.lists.isTestingDone) const isDisabled = useSelector((state: RootState) => state.quiz.isTestingDone)
const draggedItems = arr || []; const draggedItems = arr || [];
const handleDragEnd = (event: any) => { const handleDragEnd = (event: any) => {
@@ -30,11 +29,11 @@ function SortableList({ index}: ComponentProps) {
return ( return (
<DndContext collisionDetection={closestCenter} onDragEnd={handleDragEnd}> <DndContext collisionDetection={closestCenter} onDragEnd={handleDragEnd}>
<SortableContext items={draggedItems} <SortableContext items={draggedItems.map((x)=> String(x))}
strategy={verticalListSortingStrategy}> strategy={verticalListSortingStrategy}>
<List> <List>
{draggedItems.map((item) => ( {draggedItems.map((item) => (
<SortableItem key={item} item={item} id={item} isDisabled={isDisabled}/> <SortableItem key={String(item)} item={String(item)} id={String(item)} isDisabled={isDisabled} />
))} ))}
</List> </List>
</SortableContext> </SortableContext>

View File

@@ -0,0 +1,35 @@
import { Grid} from '@mui/material';
import type { tTasks } from "../quizData"
import SortableList from '../features/SortableList';
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { addList, mixUp } from './quizSlice';
interface ComponentProps {
tasks: tTasks;
index: number;
}
function Matching({ tasks, index }: ComponentProps) {
const dispatch = useDispatch();
const answers: string[] = tasks.map((item) => String(item.answer));
// Добавляем список ответов очередного задания в хранилище
useEffect(() => {
dispatch(addList({ index, items: answers, answers:answers,questions:tasks.map((item) => String(item.question)), quizType: "M" }));
}, []);
useEffect(() => {
dispatch(mixUp());
}, []);
return (
<Grid container spacing={2}>
<Grid size={12}>
<SortableList index={index} answers={answers} />
</Grid>
</Grid>
);
}
export default Matching

View File

@@ -1,7 +1,7 @@
import { createSlice } from '@reduxjs/toolkit'; import { createSlice } from '@reduxjs/toolkit';
import type {PayloadAction} from '@reduxjs/toolkit'; import type { PayloadAction } from '@reduxjs/toolkit';
function shuffle<T>(array:Array<T>):Array<T> { function shuffle<T>(array: Array<T>): Array<T> {
let currentIndex = array.length; let currentIndex = array.length;
// While there remain elements to shuffle... // While there remain elements to shuffle...
@@ -19,55 +19,67 @@ function shuffle<T>(array:Array<T>):Array<T> {
} }
interface QuizState { interface QuizState {
userAnswers: string[][]; // хранит перемещаемые элементы каждого списка ответов userAnswers: (string | boolean)[][]; // хранит перемещаемые элементы каждого списка ответов
correctAnswers:string[][] |boolean[][];// ответы для вопрсов, в случае с matching просто правильная последоавтельность, для sorting аналогично, для choosе последоватеьность boolean questions: string[][];
isTestingDone:boolean// запрет на взаимодействие с квизом после окончания тестирования, чтобю юзер не наглел correctAnswers: (string | boolean)[][];// ответы для вопрсов, в случае с matching просто правильная последоавтельность, для sorting аналогично, для choosе последоватеьность boolean
quizTypes: Array<"M" | "S" | "C">;
isTestingDone: boolean// запрет на взаимодействие с квизом после окончания тестирования, чтобю юзер не наглел
} }
const initialState: QuizState = { const initialState: QuizState = {
userAnswers: [], userAnswers: [],
correctAnswers:[], correctAnswers: [],
isTestingDone:false quizTypes: [],
questions:[],
isTestingDone: false,
}; };
const listsSlice = createSlice({ const listsSlice = createSlice({
name: 'lists', name: 'lists',
initialState, initialState,
reducers: { reducers: {
addList: (state, action: PayloadAction<{index: number; items: string[]}>)=>{ addList: (state, action: PayloadAction<{ index: number; items: string[]; questions: string[]; answers: (string|boolean)[]; quizType : "S" | "M" | "C"}>) => {
const { index, items } = action.payload; const { index, items,questions,answers,quizType} = action.payload;
state.questions.splice(index, 1, questions);
state.userAnswers.splice(index, 1, items); // с нулём создаётся по 2 экземпляра, видно в отладке state.userAnswers.splice(index, 1, items); // с нулём создаётся по 2 экземпляра, видно в отладке
state.correctAnswers.splice(index, 1, items); state.quizTypes.splice(index, 1, quizType); //
state.correctAnswers.splice(index, 1, answers);
}, },
setDraggedItems: (state, action: PayloadAction<{ index: number; items: string[] }>) => { setDraggedItems: (state, action: PayloadAction<{ index: number; items: (string|boolean)[] }>) => {
const { index, items } = action.payload; const { index, items } = action.payload;
if (index >= 0 && index < state.userAnswers.length) { if (index >= 0 && index < state.userAnswers.length) {
state.userAnswers[index] = items; // обновляем конкретный список state.userAnswers[index] = items; // обновляем конкретный список
} }
}, },
setCheckedItems: (state, action: PayloadAction<{ index: number; items: string[] }>) => { setCheckedItems: (state, action: PayloadAction<{ index: number; items: boolean[] }>) => {
const { index, items } = action.payload; const { index, items } = action.payload;
if (index >= 0 && index < state.userAnswers.length) { if (index >= 0 && index < state.userAnswers.length) {
state.userAnswers[index] = items; // обновляем конкретный список state.userAnswers[index] = items; // обновляем конкретный список
} }
}, },
mixUp: (state) => { mixUp: (state) => {
state.userAnswers=state.userAnswers.map((list)=> state.userAnswers = state.userAnswers.map((list,index) => {
{ if(typeof(state.correctAnswers[index][0])==="boolean"){
return shuffle(list); list.map(()=>false);
}) let indexes = shuffle( list.map((_,idx)=>idx));
state.correctAnswers[index]=state.correctAnswers[index].map((_,i,arr)=>arr[indexes[i]])
state.questions[index]=state.questions[index].map((_,i,arr)=>arr[indexes[i]])
return list.map(()=>false)
}
return shuffle<string|boolean>(list);
})
}, },
stopTesting:(state)=>{ stopTesting: (state) => {
state.isTestingDone=true; state.isTestingDone = true;
}, },
startTesting:(state)=>{ startTesting: (state) => {
state.isTestingDone=false; state.isTestingDone = false;
} }
}, },
}); });
// Экспортируем действия и редьюсер // Экспортируем действия и редьюсер
export const { addList, setDraggedItems,mixUp,startTesting,stopTesting } = listsSlice.actions; export const { addList, setDraggedItems,setCheckedItems, mixUp, startTesting, stopTesting } = listsSlice.actions;
export type {QuizState} export type { QuizState }
export default listsSlice.reducer; export default listsSlice.reducer;

View File

@@ -12,81 +12,141 @@ export type tQuizzes = {
export const quiz: tQuizzes = [ export const quiz: tQuizzes = [
{ {
"id": 1, "id": 0,
"type": "M", "type": "C",
"title": "вопросй", "title": "RAM price jump: pick true statements",
"tasks": [ "tasks": [
{ {
"question": "адын?", "question": "AI server demand pushed DRAM contracts up in 2024-2025",
"answer": "адын" "answer": true
}, },
{ {
"question": "2", "question": "Laptop DDR5 demand was the main global driver",
"answer": "2" "answer": false
}, },
{ {
"question": "3", "question": "HBM supply limits affected overall memory pricing",
"answer": "3" "answer": true
}, },
{ {
"question": "4", "question": "Memory prices stayed flat through 2025",
"answer": "4" "answer": false
}
]
},
{
"id": 1,
"type": "M",
"title": "Match RAM market terms",
"tasks": [
{
"question": "HBM",
"answer": "High Bandwidth Memory"
}, },
{
"question": "DRAM",
"answer": "Dynamic Random Access Memory"
},
{
"question": "NAND",
"answer": "Flash storage memory"
},
{
"question": "Contract price",
"answer": "Long-term negotiated memory price"
}
] ]
}, },
{ {
"id": 2, "id": 2,
"type": "S", "type": "S",
"title": "Вопрос 2 СОРТИРУЙ", "title": "Sort AI stack by deployment flow",
"tasks": [ "tasks": [
{ {
"question": "1", "question": "1",
"answer": 1 "answer": "Collect and clean data"
}, },
{ {
"question": "22", "question": "2",
"answer": 2 "answer": "Train model"
}, },
{ {
"question": "333", "question": "3",
"answer": 3 "answer": "Optimize for inference"
}, },
{ {
"question": "4444", "question": "4",
"answer": 4 "answer": "Deploy and monitor"
}, }
{
"question": "5555",
"answer": 5
},
] ]
} },
,
{ {
"id": 2, "id": 3,
"type": "C", "type": "C",
"title": "Вопрос 3 Выбирай!", "title": "AI trends: choose true",
"tasks": [ "tasks": [
{ {
"question": "да", "question": "Edge AI adoption grew in 2024-2026",
"answer": true "answer": true
}, },
{ {
"question": "нет", "question": "LLMs removed the need for GPUs",
"answer": false "answer": false
}, },
{ {
"question": "и снова да", "question": "Smaller task-specific models are still widely used",
"answer": true "answer": true
}, },
{ {
"question": "нет", "question": "AI inference always runs only in cloud",
"answer": false "answer": false
}
]
},
{
"id": 4,
"type": "M",
"title": "Match low-energy embedded methods",
"tasks": [
{
"question": "Sleep mode",
"answer": "Turns off CPU blocks between events"
}, },
{ {
"question": "дааа", "question": "DVFS",
"answer": true "answer": "Adjusts voltage and frequency to save power"
}, },
{
"question": "Interrupt wakeup",
"answer": "Wakes MCU only on external/internal trigger"
},
{
"question": "Duty cycling",
"answer": "Runs sensors and radio in short active bursts"
}
]
},
{
"id": 5,
"type": "S",
"title": "Sort low-energy embedded design steps",
"tasks": [
{
"question": "1",
"answer": "Measure baseline current"
},
{
"question": "2",
"answer": "Set sleep and wake strategy"
},
{
"question": "3",
"answer": "Tune radio and sensor duty cycle"
},
{
"question": "4",
"answer": "Validate battery-life target"
}
] ]
} }
] ]