Skip to content

Feat/job sequencing visualizer#780

Open
harsharajkumar-273 wants to merge 2 commits into
algoscope-hq:mainfrom
harsharajkumar-273:feat/job-sequencing-visualizer
Open

Feat/job sequencing visualizer#780
harsharajkumar-273 wants to merge 2 commits into
algoscope-hq:mainfrom
harsharajkumar-273:feat/job-sequencing-visualizer

Conversation

@harsharajkumar-273

@harsharajkumar-273 harsharajkumar-273 commented Jul 13, 2026

Copy link
Copy Markdown

Pull Request Summary

Title: feat: restore greedy algorithms and add job sequencing visualizer

What changed?

This pull request restores the previously reverted Greedy Algorithms visualizer page and components (Huffman Coding and Fractional Knapsack) and adds a brand new Job Sequencing with Deadlines visualizer. The changes include:

  • Restoring step-generation logic and visualizer components for Huffman Coding and Fractional Knapsack.
  • Creating jobSequencingSteps.js and JobSequencingVisualizer.jsx which renders an interactive Gantt chart timeline grid (highlighting backwards slot searches), a live metrics panel (Total Profit, Scheduled, and Missed Jobs), and a dynamic jobs directory card deck.
  • Replacing external lodash.cloneDeep imports with standard browser-native structuredClone() for cleaner imports and resolution.
  • Registering /greedy client-side routes, navigation navbar items, search queries, and complexity analysis parameters.
  • Adding a descriptive README.md to src/components/greedyAlgo/.

Why is this needed?

Job Sequencing with Deadlines is a core greedy optimization algorithm in computer science curricula. Its greedy selection and backwards time-slot search strategies are best understood via step-by-step interactive animations, which were missing in AlgoScope. This PR resolves the feature request to cover this gap.

Closes #731

Type of Change

  • feat - New user-facing feature or algorithm capability

Release Notes

Release note category:

  • Added

Release note entry:

  • Added Job Sequencing with Deadlines visualizer to the Greedy Algorithms page, featuring Gantt chart slot booking animations and a live metrics panel.

Testing and Verification

  • npm ci or npm install
  • npm run build
  • Manual browser testing at http://localhost:5173
  • Responsive testing for affected views
  • No new console errors or warnings

UI Evidence

Before: The Greedy Algorithms page was reverted and inaccessible.
After: Fully accessible Greedy Algorithms page featuring Huffman, Knapsack, and Job Sequencing visualizers with real-time controls.

CI/CD and Deployment Impact

  • Updates Vercel, Nginx, redirects, or client-side routing behavior

Summary by CodeRabbit

  • New Features
    • Added a Greedy Algorithms visualizer page with step-by-step playback and interactive controls.
    • Added visualizations for Huffman Coding, Fractional Knapsack, and Job Sequencing.
    • Added algorithm-specific inputs, live metrics, code highlighting, variable insights, and complexity information.
    • Added Greedy Algorithms to navigation, search, and the visualizer catalog.
  • Documentation
    • Added documentation covering the new visualizer components and supported algorithms.

@vercel

vercel Bot commented Jul 13, 2026

Copy link
Copy Markdown

Someone is attempting to deploy a commit to the bimbok's projects Team on Vercel.

A member of the Team first needs to authorize it.

@netlify

netlify Bot commented Jul 13, 2026

Copy link
Copy Markdown

Deploy Preview for astounding-nougat-da0f6a ready!

Name Link
🔨 Latest commit fd40eac
🔍 Latest deploy log https://app.netlify.com/projects/astounding-nougat-da0f6a/deploys/6a5517b7aa210c0008e3c440
😎 Deploy Preview https://deploy-preview-780--astounding-nougat-da0f6a.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a /greedy visualizer page for Huffman Coding, Fractional Knapsack, and Job Sequencing, including step generators, animated algorithm views, source-code highlighting, playback controls, navigation entries, and complexity metadata.

Changes

Greedy Algorithms Visualizer

Layer / File(s) Summary
Route and algorithm catalog integration
src/App.jsx, src/components/Navbar.jsx, src/components/SearchBar.jsx, src/data/*
Registers the /greedy route and adds the visualizer to navigation, search, catalog, and complexity data.
Greedy step generation and source mapping
src/algorithms/greedy/*
Generates traced steps for Huffman Coding, Fractional Knapsack, and Job Sequencing, with multilingual source templates and active-line mappings.
Visualizer page orchestration
src/components/greedyAlgo/VisualizerPage.jsx, src/components/greedyAlgo/README.md
Coordinates inputs, URL state, playback, code highlighting, algorithm controls, insights, and documentation.
Algorithm-specific visual rendering
src/components/greedyAlgo/*Visualizer.jsx, src/components/greedyAlgo/Greedy*.jsx
Renders animated Huffman trees, scheduling timelines, knapsack contents, metrics, statuses, and completion results.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related issues

Possibly related PRs

Suggested labels: gssoc:approved, type:feature, level:critical

Suggested reviewers: adityapaul26, khushalkks, madhavcodes25

🚥 Pre-merge checks | ✅ 5 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Algorithm Complexity ⚠️ Warning Huffman re-sorts the forest on every merge, so this implementation is O(k^2 log k) (plus snapshot cloning), not O(N log N). Switch Huffman to a min-heap/priority queue, or update the docs/complexityMap to match the sort-per-merge version. Knapsack and job sequencing look aligned.
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and clearly points to the new job sequencing visualizer.
Description check ✅ Passed The description covers the summary, issue reference, change type, release notes, testing, UI evidence, and deployment impact.
Linked Issues check ✅ Passed The job sequencing steps and visualizer match the issue: profit sorting, backward slot search, skipped jobs, timeline, and live metrics.
Out of Scope Changes check ✅ Passed The extra greedy-page restore, routing, docs, and supporting visualizers align with the stated PR objectives and linked issue scope.
Conventional Commits ✅ Passed PR title and the two commits in the PR range both use conventional prefixes (feat:, docs:).
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install timed out. The project may have too many dependencies for the sandbox.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/algorithms/greedy/fractionalKnapsackSteps.js`:
- Around line 29-47: In the fractional knapsack generator, add an early guard
immediately after the input normalization/filtering that checks whether items is
empty, emits a friendly “please add a valid input” step consistent with
generateHuffmanSteps and generateJobSequencingSteps, and stops further start,
ratio, sorting, and total steps from being generated.

In `@src/algorithms/greedy/greedySources.js`:
- Line 45: Update the finish offsets in greedySources.js: change huffman.finish
from 30 to 31 at lines 45-45, knapsack.finish from 24 to 25 at lines 183-183,
and jobsequencing.finish from 32 to 33 at lines 312-312 so each highlight
includes the result line instead of the preceding blank line.
- Around line 41-44: Update the Huffman JS lineMap entries in the greedySources
configuration from sort onward, including sort, pick, merge, push, and finish,
by incrementing each value by one so CodePanel highlights the intended
statements.
- Around line 411-416: Update resolveGreedyLine to select the language-specific
lineMap only when it exists, otherwise fall back to
greedySources[algo]?.javascript.lineMap. Preserve the existing lineKey guard and
return undefined when neither mapping contains the requested key.

In `@src/components/greedyAlgo/HuffmanVisualizer.jsx`:
- Around line 381-387: Remove one of the duplicate GreedyBlock instances titled
“Greedy Algorithm Summary” in HuffmanVisualizer, keeping the remaining block and
its text unchanged.

In `@src/components/greedyAlgo/VisualizerPage.jsx`:
- Line 135: Replace length-based ID generation in the Item handler at
src/components/greedyAlgo/VisualizerPage.jsx#L135-L135 with a suffix derived
from the highest existing Item id or a monotonic counter, preserving uniqueness
after removals. Apply the same change to Job ID generation at
src/components/greedyAlgo/VisualizerPage.jsx#L158-L158 so both handlers always
produce unique React keys and filter-by-id deletions remain correct.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro Plus

Run ID: 3e3ae0f8-45f8-43d4-b33d-8febb5a25ae1

📥 Commits

Reviewing files that changed from the base of the PR and between de62999 and fd40eac.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (16)
  • src/App.jsx
  • src/algorithms/greedy/fractionalKnapsackSteps.js
  • src/algorithms/greedy/greedySources.js
  • src/algorithms/greedy/huffmanCodingSteps.js
  • src/algorithms/greedy/jobSequencingSteps.js
  • src/components/Navbar.jsx
  • src/components/SearchBar.jsx
  • src/components/greedyAlgo/GreedyAlgorithmCard.jsx
  • src/components/greedyAlgo/GreedyBlock.jsx
  • src/components/greedyAlgo/HuffmanVisualizer.jsx
  • src/components/greedyAlgo/JobSequencingVisualizer.jsx
  • src/components/greedyAlgo/KnapsackVisualizer.jsx
  • src/components/greedyAlgo/README.md
  • src/components/greedyAlgo/VisualizerPage.jsx
  • src/data/complexityMap.js
  • src/data/visualizerData.js

Comment on lines +29 to +47
// Deep copy the input items
let items = inputItems
.map((item, index) => ({
id: item.id || `Item ${index + 1}`,
value: Number(item.value),
weight: Number(item.weight),
ratio: 0,
status: 'staged', // staged, ratio-calculated, sorted, active, packed, fractioned, skipped
packedRatio: 0,
packedWeight: 0,
packedValue: 0,
}))
.filter(
(item) =>
!isNaN(item.value) &&
!isNaN(item.weight) &&
item.weight > 0 &&
item.value > 0
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Add an explicit empty-input guard for consistency & clearer UX.

Nice defensive filtering here! But if every item is invalid (or inputItems is empty), items becomes [] and the generator still emits start → ratios → sort → total → complete with a $0 result and no explanation. Both generateHuffmanSteps and generateJobSequencingSteps short-circuit with a friendly "please add a valid input" step — worth mirroring that here so beginners aren't confused by an empty run.

As per path instructions: "Check for edge cases like empty inputs".

🛡️ Suggested guard
     .filter(
       (item) =>
         !isNaN(item.value) &&
         !isNaN(item.weight) &&
         item.weight > 0 &&
         item.value > 0
     )
+
+  if (items.length === 0) {
+    return [
+      createStep({
+        lineKey: 'init',
+        type: 'start',
+        items: [],
+        knapsackState: {
+          capacityLeft: currentCapacity,
+          totalCapacity: currentCapacity,
+          totalValue: 0,
+          contents: [],
+        },
+        message: 'Please add at least one valid item (positive weight and value).',
+        duration: 1000,
+      }),
+    ]
+  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Deep copy the input items
let items = inputItems
.map((item, index) => ({
id: item.id || `Item ${index + 1}`,
value: Number(item.value),
weight: Number(item.weight),
ratio: 0,
status: 'staged', // staged, ratio-calculated, sorted, active, packed, fractioned, skipped
packedRatio: 0,
packedWeight: 0,
packedValue: 0,
}))
.filter(
(item) =>
!isNaN(item.value) &&
!isNaN(item.weight) &&
item.weight > 0 &&
item.value > 0
)
// Deep copy the input items
let items = inputItems
.map((item, index) => ({
id: item.id || `Item ${index + 1}`,
value: Number(item.value),
weight: Number(item.weight),
ratio: 0,
status: 'staged', // staged, ratio-calculated, sorted, active, packed, fractioned, skipped
packedRatio: 0,
packedWeight: 0,
packedValue: 0,
}))
.filter(
(item) =>
!isNaN(item.value) &&
!isNaN(item.weight) &&
item.weight > 0 &&
item.value > 0
)
if (items.length === 0) {
return [
createStep({
lineKey: 'init',
type: 'start',
items: [],
knapsackState: {
capacityLeft: currentCapacity,
totalCapacity: currentCapacity,
totalValue: 0,
contents: [],
},
message: 'Please add at least one valid item (positive weight and value).',
duration: 1000,
}),
]
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/algorithms/greedy/fractionalKnapsackSteps.js` around lines 29 - 47, In
the fractional knapsack generator, add an early guard immediately after the
input normalization/filtering that checks whether items is empty, emits a
friendly “please add a valid input” step consistent with generateHuffmanSteps
and generateJobSequencingSteps, and stops further start, ratio, sorting, and
total steps from being generated.

Source: Path instructions

Comment on lines +41 to +44
sort: 17,
pick: 18,
merge: 21,
push: 27,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== File map =="
git ls-files src/algorithms/greedy/greedySources.js

echo
echo "== Outline =="
ast-grep outline src/algorithms/greedy/greedySources.js --view expanded || true

echo
echo "== Relevant lines =="
wc -l src/algorithms/greedy/greedySources.js
sed -n '1,220p' src/algorithms/greedy/greedySources.js | cat -n

echo
echo "== Search for lineMap / lineKey / CodePanel references =="
rg -n "lineMap|lineKey|CodePanel|greedySources" src . --glob '!**/node_modules/**' || true

Repository: algoscope-hq/AlgoScope

Length of output: 50378


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== Huffman steps =="
sed -n '1,320p' src/algorithms/greedy/huffmanCodingSteps.js | cat -n

echo
echo "== CodePanel line handling =="
sed -n '1,280p' src/components/visualizer/CodePanel.jsx | cat -n

echo
echo "== Greedy visualizer line resolution =="
sed -n '150,230p' src/components/greedyAlgo/VisualizerPage.jsx | cat -n

echo
echo "== Resolve function in greedySources =="
sed -n '400,430p' src/algorithms/greedy/greedySources.js | cat -n

Repository: algoscope-hq/AlgoScope

Length of output: 22539


Bump Huffman JS lineMap entries from sort onward. sort, pick, merge, push, and finish are each one line early, so the CodePanel highlight lands on the previous line instead of the intended statement.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/algorithms/greedy/greedySources.js` around lines 41 - 44, Update the
Huffman JS lineMap entries in the greedySources configuration from sort onward,
including sort, pick, merge, push, and finish, by incrementing each value by one
so CodePanel highlights the intended statements.

Source: Path instructions

pick: 18,
merge: 21,
push: 27,
finish: 30,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Map the relevant file and inspect the flagged regions with line numbers.
wc -l src/algorithms/greedy/greedySources.js
sed -n '1,80p' src/algorithms/greedy/greedySources.js
printf '\n---\n'
sed -n '160,210p' src/algorithms/greedy/greedySources.js
printf '\n---\n'
sed -n '285,340p' src/algorithms/greedy/greedySources.js

printf '\n=== line number check around returns ===\n'
python3 - <<'PY'
from pathlib import Path
p = Path('src/algorithms/greedy/greedySources.js')
lines = p.read_text().splitlines()
for idx in [45,46,47,183,184,185,312,313,314]:
    if 1 <= idx <= len(lines):
        print(f"{idx}: {lines[idx-1]}")
PY

Repository: algoscope-hq/AlgoScope

Length of output: 4756


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
import re

text = Path('src/algorithms/greedy/greedySources.js').read_text()

targets = ['huffman', 'fractionalKnapsack', 'jobSequencing']
for name in targets:
    m = re.search(rf'{name}\s*:\s*\{{\s*javascript:\s*\{{\s*code:\s*`(.*?)`\s*,\s*lineMap:\s*\{{(.*?)\}}\s*,\s*\}}\s*,', text, re.S)
    if not m:
        print(f'FAILED to match {name}')
        continue
    code = m.group(1)
    linemap = m.group(2)
    print(f'=== {name} ===')
    print('lineMap finish:', re.search(r'finish:\s*(\d+)', linemap).group(1))
    lines = code.splitlines()
    for i, line in enumerate(lines, 1):
        print(f'{i:>2}: {line}')
    print('--- total lines:', len(lines))
    print()
PY

Repository: algoscope-hq/AlgoScope

Length of output: 1102


🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n "finish: 24|finish: 32|fraction|knapsack|job" src/algorithms/greedy/greedySources.js
printf '\n--- around 150-210 ---\n'
sed -n '150,210p' src/algorithms/greedy/greedySources.js
printf '\n--- around 290-330 ---\n'
sed -n '290,330p' src/algorithms/greedy/greedySources.js

Repository: algoscope-hq/AlgoScope

Length of output: 4357


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
text = Path('src/algorithms/greedy/greedySources.js').read_text().splitlines()
for start in [150, 290]:
    print(f'=== {start}..{start+70} ===')
    for i in range(start, min(start+70, len(text))+1):
        print(f'{i:>4}: {text[i-1]}')
PY

Repository: algoscope-hq/AlgoScope

Length of output: 4435


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
lines = Path('src/algorithms/greedy/greedySources.js').read_text().splitlines()

for start, end in [(150, 210), (290, 350)]:
    print(f'=== {start}..{end} ===')
    for i in range(start, min(end, len(lines)) + 1):
        print(f'{i:>4}: {lines[i-1]}')
    print()
PY

Repository: algoscope-hq/AlgoScope

Length of output: 3804


🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n "finish:\s*(24|32)|lineMap|return " src/algorithms/greedy/greedySources.js

Repository: algoscope-hq/AlgoScope

Length of output: 829


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
from pathlib import Path
lines = Path('src/algorithms/greedy/greedySources.js').read_text().splitlines()

# Print the surrounding regions for the remaining finish markers.
for needle in ['finish: 24,', 'finish: 32,']:
    idx = next(i for i,l in enumerate(lines, 1) if needle in l)
    start = max(1, idx - 25)
    end = min(len(lines), idx + 30)
    print(f'=== context for {needle} at file line {idx} ===')
    for i in range(start, end + 1):
        print(f'{i:>4}: {lines[i-1]}')
    print()
PY

Repository: algoscope-hq/AlgoScope

Length of output: 3578


Bump these three finish offsets by 1 src/algorithms/greedy/greedySources.js: huffman.finish 30 → 31, knapsack.finish 24 → 25, and jobsequencing.finish 32 → 33. They currently point at the blank line before each return, so the highlight misses the actual result line.

📍 Affects 1 file
  • src/algorithms/greedy/greedySources.js#L45-L45 (this comment)
  • src/algorithms/greedy/greedySources.js#L183-L183
  • src/algorithms/greedy/greedySources.js#L312-L312
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/algorithms/greedy/greedySources.js` at line 45, Update the finish offsets
in greedySources.js: change huffman.finish from 30 to 31 at lines 45-45,
knapsack.finish from 24 to 25 at lines 183-183, and jobsequencing.finish from 32
to 33 at lines 312-312 so each highlight includes the result line instead of the
preceding blank line.

Comment on lines +411 to +416
export const resolveGreedyLine = (algo, language, lineKey) => {
if (!lineKey) return undefined
const source =
greedySources[algo]?.[language] || greedySources[algo]?.javascript
return source?.lineMap?.[lineKey]
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== File list ==\n'
git ls-files 'src/algorithms/greedy/greedySources.js' 'src/**' | sed -n '1,200p'

printf '\n== Outline greedySources.js ==\n'
ast-grep outline src/algorithms/greedy/greedySources.js --view expanded || true

printf '\n== Relevant lines in greedySources.js ==\n'
sed -n '1,260p' src/algorithms/greedy/greedySources.js | nl -ba | sed -n '1,260p'

printf '\n== Search resolveGreedyLine usages ==\n'
rg -n "resolveGreedyLine|lineMap|activeLine|highlight" src -g '!**/node_modules/**' || true

Repository: algoscope-hq/AlgoScope

Length of output: 7310


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== resolveGreedyLine and surrounding code ==\n'
awk 'NR>=360 && NR<=450 {printf "%4d  %s\n", NR, $0}' src/algorithms/greedy/greedySources.js

printf '\n== grep for lineMap in greedySources.js ==\n'
rg -n "lineMap|resolveGreedyLine|greedySources" src/algorithms/greedy/greedySources.js

printf '\n== CodePanel.jsx relevant sections ==\n'
awk 'NR>=1 && NR<=260 {printf "%4d  %s\n", NR, $0}' src/components/visualizer/CodePanel.jsx

printf '\n== Step playback hook usage ==\n'
rg -n "activeLine|highlight|lineKey|resolveGreedyLine|currentLine|lineNumber" src/components/visualizer src/components/greedyAlgo src/algorithms/greedy

Repository: algoscope-hq/AlgoScope

Length of output: 16812


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== Greedy Visualizer language handling ==\n'
awk 'NR>=1 && NR<=420 {printf "%4d  %s\n", NR, $0}' src/components/greedyAlgo/VisualizerPage.jsx

printf '\n== Greedy sources structure around language blocks ==\n'
awk 'NR>=1 && NR<=220 {printf "%4d  %s\n", NR, $0}' src/algorithms/greedy/greedySources.js

printf '\n== Greedy sources later blocks ==\n'
awk 'NR>=220 && NR<=360 {printf "%4d  %s\n", NR, $0}' src/algorithms/greedy/greedySources.js

Repository: algoscope-hq/AlgoScope

Length of output: 30230


Fallback to the JS line map when the selected language has no mapping

greedySources[algo]?.[language] exists for Python/C++/Java, but those entries don’t define lineMap. resolveGreedyLine() then returns undefined, so CodePanel can’t highlight the current step for those languages.

🔧 Suggested fix
 export const resolveGreedyLine = (algo, language, lineKey) => {
   if (!lineKey) return undefined
-  const source =
-    greedySources[algo]?.[language] || greedySources[algo]?.javascript
-  return source?.lineMap?.[lineKey]
+  const lineMap =
+    greedySources[algo]?.[language]?.lineMap ||
+    greedySources[algo]?.javascript?.lineMap
+  return lineMap?.[lineKey]
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export const resolveGreedyLine = (algo, language, lineKey) => {
if (!lineKey) return undefined
const source =
greedySources[algo]?.[language] || greedySources[algo]?.javascript
return source?.lineMap?.[lineKey]
}
export const resolveGreedyLine = (algo, language, lineKey) => {
if (!lineKey) return undefined
const lineMap =
greedySources[algo]?.[language]?.lineMap ||
greedySources[algo]?.javascript?.lineMap
return lineMap?.[lineKey]
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/algorithms/greedy/greedySources.js` around lines 411 - 416, Update
resolveGreedyLine to select the language-specific lineMap only when it exists,
otherwise fall back to greedySources[algo]?.javascript.lineMap. Preserve the
existing lineKey guard and return undefined when neither mapping contains the
requested key.

Comment on lines +381 to +387
{/* Greedy Summary Block */}
<div className="mt-6">
<GreedyBlock title="Greedy Algorithm Summary">
This visualizer demonstrates a greedy approach for building Huffman
trees.
</GreedyBlock>
</div>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Duplicate "Greedy Algorithm Summary" block.

This same GreedyBlock is already rendered above at lines 260–263 with identical text, so the summary shows twice. Drop one of them (keep whichever position you prefer).

🧹 Suggested cleanup
-      {/* Greedy Summary Block */}
-      <div className="mt-6">
-        <GreedyBlock title="Greedy Algorithm Summary">
-          This visualizer demonstrates a greedy approach for building Huffman
-          trees.
-        </GreedyBlock>
-      </div>
     </div>
   )
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
{/* Greedy Summary Block */}
<div className="mt-6">
<GreedyBlock title="Greedy Algorithm Summary">
This visualizer demonstrates a greedy approach for building Huffman
trees.
</GreedyBlock>
</div>
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/greedyAlgo/HuffmanVisualizer.jsx` around lines 381 - 387,
Remove one of the duplicate GreedyBlock instances titled “Greedy Algorithm
Summary” in HuffmanVisualizer, keeping the remaining block and its text
unchanged.

const wt = Number(newItemWeight)
if (isNaN(val) || isNaN(wt) || val <= 0 || wt <= 0) return

const nextLetter = String.fromCharCode(65 + knapsackItems.length) // Item A, B, C, D...

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Length-based ID generation collides after removals. Both handlers mint IDs as String.fromCharCode(65 + <array>.length), so once an element is removed the next add reuses an existing letter, yielding duplicate ids → duplicate React keys and filter-by-id deletions that remove the wrong/both entries. Derive the suffix from the highest existing ID (or a monotonically increasing counter kept in state), not the current length.

  • src/components/greedyAlgo/VisualizerPage.jsx#L135-L135: replace 65 + knapsackItems.length with a suffix computed from existing Item ids / a counter.
  • src/components/greedyAlgo/VisualizerPage.jsx#L158-L158: apply the same fix for Job ids (65 + jobs.length).
📍 Affects 1 file
  • src/components/greedyAlgo/VisualizerPage.jsx#L135-L135 (this comment)
  • src/components/greedyAlgo/VisualizerPage.jsx#L158-L158
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/components/greedyAlgo/VisualizerPage.jsx` at line 135, Replace
length-based ID generation in the Item handler at
src/components/greedyAlgo/VisualizerPage.jsx#L135-L135 with a suffix derived
from the highest existing Item id or a monotonic counter, preserving uniqueness
after removals. Apply the same change to Job ID generation at
src/components/greedyAlgo/VisualizerPage.jsx#L158-L158 so both handlers always
produce unique React keys and filter-by-id deletions remain correct.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[[Feature]: Job Sequencing with Deadlines Visualizer for Greedy Algorithms](https://github.com/algoscope-hq/AlgoScope/issues/681#top)

1 participant