import React, { useState } from 'react'; const FrequencyMeanWidget: React.FC = () => { // Data: Value -> Frequency const [counts, setCounts] = useState({ 0: 3, 1: 5, 2: 6, 3: 4, 4: 2 }); const handleChange = (val: number, delta: number) => { setCounts(prev => ({ ...prev, [val]: Math.max(0, (prev[val as keyof typeof prev] || 0) + delta) })); }; const values = [0, 1, 2, 3, 4]; const totalStudents = values.reduce((sum, v) => sum + counts[v as keyof typeof counts], 0); const totalBooks = values.reduce((sum, v) => sum + v * counts[v as keyof typeof counts], 0); const mean = totalStudents > 0 ? (totalBooks / totalStudents).toFixed(2) : '0'; // Calculate Median position let cumulative = 0; let medianVal = 0; const mid = (totalStudents + 1) / 2; if (totalStudents > 0) { for (const v of values) { cumulative += counts[v as keyof typeof counts]; if (cumulative >= mid) { medianVal = v; break; } } } return (
| Books Read | Students (Freq) |
|---|---|
| {v} | {counts[v as keyof typeof counts]} |
| TOTAL | {totalStudents} |
Weighted Mean
{mean}
Total Books ({totalBooks}) / Students ({totalStudents})
Median
{medianVal}
Middle Position (~{mid.toFixed(1)})