0% found this document useful (0 votes)
268 views12 pages

SM-2 Spaced Repetition Algorithm Guide

SM-2 Spaced Repetition Algorithm

Uploaded by

onlykf069
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
268 views12 pages

SM-2 Spaced Repetition Algorithm Guide

SM-2 Spaced Repetition Algorithm

Uploaded by

onlykf069
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

SM-2 Spaced Repetition Algorithm

Complete Implementation Guide for Developers


What is SM-2?
SM-2 (SuperMemo 2) is the algorithm that revolutionized computer-assisted learning in 1987. It's the
grandfather of most modern spaced repetition systems, including Anki's default algorithm. The core
idea: calculate the optimal time to review information just before you're about to forget it.

📐 The Core Algorithm


Key Variables
javascript
// For each piece of information you track:
{
n: 0, // Repetition number (how many times reviewed)
EF: 2.5, // Easiness Factor (how easy the item is for you)
I: 1, // Inter-repetition interval (days until next review)
lastReview: Date, // When last reviewed
nextReview: Date // When to review next
}

The SM-2 Formula


javascript
function calculateNextInterval(quality, n, EF, I) {
// quality: Your self-assessment (0-5 scale)
// 0 - Complete blackout
// 1 - Incorrect, but recognized when shown answer
// 2 - Incorrect, but felt close
// 3 - Correct, but difficult recall
// 4 - Correct, with hesitation
// 5 - Perfect recall
// Step 1: Calculate new Easiness Factor
let newEF = EF + (0.1 - (5 - quality) * (0.08 + (5 - quality) * 0.02));
// Keep EF bounded (minimum 1.3 for hardest items)
if (newEF < 1.3) newEF = 1.3;
// Step 2: Calculate next interval
let newInterval;
if (quality < 3) {
// Failed recall - reset to beginning
newInterval = 1;
n = 0;
} else {
// Successful recall - increase interval
if (n === 0) {
newInterval = 1;
} else if (n === 1) {
newInterval = 6;
} else {
newInterval = [Link](I * newEF);
}
n = n + 1;
}
return {
interval: newInterval,
EF: newEF,
repetition: n
};
}
🎯 How It Actually Works
Example Learning Journey
Let's say you're learning the concept "React Hooks useEffect cleanup function":
Day 0 (First Learning)
You learn it for the first time
Initial values: EF = 2.5 , n = 0 , I = 1
Next review: Tomorrow
Day 1 (First Review)
You recall it correctly but with hesitation (quality = 4)
New EF: 2.5 + (0.1 - 1 * 0.1) = 2.5 (unchanged)
Next interval: 6 days
Next review: Day 7
Day 7 (Second Review)
Perfect recall (quality = 5)
New EF: 2.5 + 0.1 = 2.6 (gets easier)
Next interval: 6 * 2.6 = 15.6 ≈ 16 days
Next review: Day 23
Day 23 (Third Review)
Struggled but got it (quality = 3)
New EF: 2.6 + (0.1 - 2 * 0.12) = 2.46
Next interval: 16 * 2.46 = 39.36 ≈ 39 days
Next review: Day 62

💻 Complete JavaScript Implementation


javascript
class SM2SpacedRepetition {
constructor() {
[Link] = new Map(); // Store all learning items
}
// Add new item to learn
addCard(id, content) {
[Link](id, {
id: id,
content: content,
n: 0,
EF: 2.5,
I: 1,
lastReview: null,
nextReview: new Date(),
history: []
});
}
// Review a card and calculate next review
reviewCard(id, quality) {
const card = [Link](id);
if (!card) throw new Error('Card not found');
// Record the review
const reviewDate = new Date();
[Link]({
date: reviewDate,
quality: quality,
EF: [Link],
interval: card.I
});
// Calculate new values
let newEF = [Link] + (0.1 - (5 - quality) * (0.08 + (5 - quality) * 0.02));
newEF = [Link](1.3, newEF); // Minimum bound
let newInterval;
let newN = card.n;
if (quality < 3) {
// Reset on failure
newInterval = 1;
newN = 0;
} else {
// Progress on success
switch(card.n) {
case 0:
newInterval = 1;
break;
case 1:
newInterval = 6;
break;
default:
newInterval = [Link](card.I * [Link]);
}
newN = card.n + 1;
}
// Update card
card.n = newN;
[Link] = newEF;
card.I = newInterval;
[Link] = reviewDate;
[Link] = [Link](reviewDate, newInterval);
return {
nextReview: [Link],
interval: newInterval,
easiness: newEF
};
}
// Get cards due for review
getDueCards() {
const now = new Date();
const due = [];
for (const [id, card] of [Link]) {
if ([Link] <= now) {
[Link](card);
}
}
// Sort by priority (overdue items first)
return [Link]((a, b) => [Link] - [Link]);
}
// Helper function
addDays(date, days) {
const result = new Date(date);
[Link]([Link]() + days);
return result;
}
// Get statistics
getStats() {
let total = [Link];
let learned = 0;
let due = 0;
const now = new Date();
for (const card of [Link]
values()) {
if (card.n > 0) learned++;
if ([Link] <= now) due++;
}
return {
total: total,
learned: learned,
due: due,
retention: learned / total * 100
};
}
}
// Usage Example
const srs = new SM2SpacedRepetition();
// Add a new concept to learn
[Link]('react-1', 'useEffect cleanup function returns cleanup logic');
// Review it (quality: 0-5)
const result = [Link]('react-1', 4); // Correct with hesitation
[Link](`Next review in ${[Link]} days`);

🔧 Custom Modifications for Your Use Case


1. Time-of-Day Optimization
javascript
// Modify intervals based on your schedule
function adjustForSchedule(baseInterval, cardType) {
const adjustments = {
'technical': 1.0, // Review technical stuff normally
'concepts': 1.2, // Give more time for abstract concepts
'commands': 0.8, // Review commands more frequently
'facts': 1.1 // Slightly longer for pure facts
};
return [Link](baseInterval * (adjustments[cardType] || 1.0));
}

2. Contextual Difficulty Adjustment


javascript
// Adjust EF based on context
function contextualEF(baseEF, context) {
// If reviewed during gym (harder context), boost EF
if (context === 'gym') {
return baseEF * 1.1; // Give credit for harder conditions
}
// If reviewed while tired (after 8pm), adjust
const hour = new Date().getHours();
if (hour >= 20) {
return baseEF * 1.05;
}
return baseEF;
}

3. Workout-Integrated Algorithm
javascript
class WorkoutSRS extends SM2SpacedRepetition {
reviewCard(id, quality, context = {}) {
// Track where review happened
const location = [Link] || 'default';
const energy = [Link] || 'normal';
// Adjust quality based on context
let adjustedQuality = quality;
if (location === 'gym' && quality >= 3) {
// Successful recall at gym = bonus
adjustedQuality = [Link](5, quality + 0.5);
}
if (energy === 'tired' && quality >= 3) {
// Successful recall when tired = bonus
adjustedQuality = [Link](5, quality + 0.3);
}
return [Link](id, adjustedQuality);
}
}

📊 Alternative Algorithms to Consider


1. SM-18 (Latest SuperMemo)
More sophisticated but complex
Considers time of day, sleep quality
Better for long-term retention
2. FSRS (Free Spaced Repetition Scheduler)
javascript
// Simplified FSRS - Better than SM-2 for most cases
function FSRS(difficulty, stability, retrievability) {
// Uses machine learning principles
const optimalInterval = stability * [Link](0.9) / [Link](retrievability);
return [Link](1, [Link](optimalInterval));
}
3. Custom Hybrid for Developers
javascript
class DeveloperSRS {
calculateInterval(card, quality) {
// Base: SM-2 algorithm
let interval = this.sm2Calculate(card, quality);
// Adjust for information type
if ([Link] === 'syntax') {
interval *= 0.7; // See syntax more often
} else if ([Link] === 'concept') {
interval *= 1.3; // Concepts need less frequent review
} else if ([Link] === 'bug-pattern') {
interval *= 0.5; // Critical to remember
}
// Adjust for source
if ([Link] === 'production-bug') {
interval *= 0.6; // Never forget production issues!
}
// Cap based on importance
if ([Link] === 'critical') {
interval = [Link](interval, 30); // Never go beyond 30 days
}
return interval;
}
}

🎮 Gamification Layer
javascript
class GamifiedSRS extends SM2SpacedRepetition {
constructor() {
super();
[Link] = new Map();
[Link] = [];
}
reviewCard(id, quality) {
const result = [Link](id, quality);
// Track streaks
if (quality >= 3) {
const currentStreak = [Link](id) || 0;
[Link](id, currentStreak + 1);
// Check achievements
if (currentStreak === 10) {
[Link]('Consistent Learner', id);
}
// Bonus interval for streaks
if (currentStreak > 5) {
[Link] *= 1.1; // 10% bonus for good streaks
}
} else {
[Link](id, 0); // Reset streak on failure
}
return result;
}
unlockAchievement(name, cardId) {
[Link]({
name: name,
cardId: cardId,
date: new Date()
});
// Could trigger notification here
[Link](`🏆 Achievement Unlocked: ${name}!`);
}
}
🚀 Implementation Tips
1. Start Simple: Begin with basic SM-2, add modifications after 30 days of data
2. Track Everything: Log quality scores, time of day, energy levels
3. Analyze Your Data: After 100+ reviews, analyze your personal forgetting curve
4. Adjust Parameters: Your optimal EF might not be 2.5 - experiment!
5. Mobile Sync: Use IndexedDB for offline, sync when online

📱 Database Schema
sql
-- SQLite schema for mobile app
CREATE TABLE cards (
id TEXT PRIMARY KEY,
content TEXT NOT NULL,
type TEXT,
n INTEGER DEFAULT 0,
ef REAL DEFAULT 2.5,
interval INTEGER DEFAULT 1,
last_review TIMESTAMP,
next_review TIMESTAMP,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE reviews (
id INTEGER PRIMARY KEY AUTOINCREMENT,
card_id TEXT,
quality INTEGER,
interval_before INTEGER,
interval_after INTEGER,
ef_before REAL,
ef_after REAL,
reviewed_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
context JSON,
FOREIGN KEY (card_id) REFERENCES cards(id)
);
-- Index for performance
CREATE INDEX idx_next_review ON cards(next_review);
CREATE INDEX idx_card_reviews ON reviews(card_id, reviewed_at);

The beauty of SM-2 is its simplicity and proven effectiveness. Start with the basic implementation,
then customize based on your learning patterns. After 30 days, you'll have enough data to fine-tune
the algorithm specifically for your brain!

Common questions

Powered by AI

The Easiness Factor (EF) directly impacts the spacing interval of reviews in the SM-2 algorithm. A higher EF indicates that the learner finds the information easier, allowing for longer intervals between reviews. It is adjusted during each review by taking the self-assessed quality score into account. This adaptive mechanism ensures that review sessions are optimized to occur just before a learner would likely forget the information .

SM-2's core advantage lies in its simplicity and proven effectiveness, which allows users to start with a basic implementation and progressively customize it. This adaptability makes it suitable for personal learning patterns, as individual users can adjust parameters like the optimal Easiness Factor (EF) after collecting sufficient data, typically after 30 days .

Modifying review intervals based on the type of information learned offers benefits such as enhancing focus on less familiar or more abstract concepts by allocating appropriate time intervals. This can improve efficiency and ensure critical or complex knowledge is revisited frequently enough to be retained effectively. However, drawbacks include the potential for complexity in managing multiple interval schedules and the risk of overcomplicating the learning process, which may discourage users if not implemented clearly or intuitively .

Individuals can customize the SM-2 algorithm by adjusting the Easiness Factor based on personal data they collect over time. They can employ modifications such as time-of-day adjustments, contextual difficulty scaling (adjusting intervals based on whether concepts were learned during more challenging contexts), and implementing a gamification layer to enhance engagement and track learning streaks. Experimenting with intervals and changes based on specific types of information learned (e.g., syntax, concepts) allows for a learning experience tailored specifically to the individual's needs .

The SM-2 algorithm adjusts the review interval based on a user's recall performance using a quality score from 0 to 5. A high recall quality score increases the interval and adjusts the Easiness Factor (EF), making it easier in future sessions. Conversely, a low recall quality yields a smaller interval and can reset the progression count (n), demanding more frequent reviews. The intervals can then be further customized based on factors like contextual difficulty or specific learning items .

The integration of a gamification layer in the SM-2 algorithm increases user engagement by providing incentives for consistent learning behaviors, such as achieving streaks and unlocking achievements for repeated successful recalls. This layer adds an element of challenge and reward, motivating users to regularly engage with the learning material, which can lead to a stronger commitment to continuous learning and better outcomes in knowledge retention .

SM-2 can be synchronized with mobile devices using technologies like IndexedDB for offline storage, ensuring that learning data, including intervals and quality scores, is preserved even without internet access. This enables seamless integration of learning sessions across different devices, providing the flexibility to review materials anytime and anywhere. Additionally, using databases like SQLite can facilitate robust management of learning schedules and interactions, thereby enhancing the learning experience by making it accessible and convenient .

Logging quality scores and contextual data is essential for accurately refining the SM-2 algorithm to suit individual learners. Quality scores help track progress and identify patterns in retention and recall, allowing for necessary adjustments in review intervals and EF calculations. Contextual data provides insights into learning conditions that might affect performance, such as the time of day or level of distractions, enabling further customization to optimize learning outcomes. These data-driven adjustments ensure a tailored approach that aligns closely with personal cognitive needs .

Adaptability in a system like SM-2 is crucial because each individual's learning pattern is unique in terms of how quickly they forget information or the specific challenges they face in recalling it. By being flexible and allowing adjustments based on personal data, the system can better align with the individual's forgetting curve, thereby optimizing the time and effort spent on reviews to ensure maximum retention without excessive repetition .

Contextual adjustments can enhance the effectiveness of the SM-2 algorithm by accounting for environmental or emotional factors that impact learning. For instance, learning while tired or in a distraction-heavy environment can decrease retention, so dynamically adjusting the Easiness Factor (EF) or review intervals to provide more leniency in such scenarios can improve overall retention rates. These adjustments create a more robust system that adapts implicitly to a learner's varying conditions, allowing the algorithm to support optimal learning even under less-than-ideal circumstances .

You might also like