Last active
April 9, 2021 12:06
-
-
Save eamonwoortman/677ca9822bd8e725c9a2c786a730aa71 to your computer and use it in GitHub Desktop.
algorith-visualizer-intervaltree-insert-range
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// import visualization libraries { | |
const { Tracer, LogTracer, Array1DTracer, Randomize, Layout, VerticalLayout } = require('algorithm-visualizer'); | |
// } | |
// define tracer variables { | |
const arrayTracer = new Array1DTracer('Array'); | |
const logTracer = new LogTracer("LogTracer"); | |
const insertArrayTracer = new Array1DTracer('InsertArray'); | |
Layout.setRoot(new VerticalLayout([arrayTracer, insertArrayTracer, logTracer])); | |
// } | |
// define input variables | |
const N = 8; // the size of an array | |
const array = [5,7,6,4,0,0,0,0]; | |
const itemsToInsert = [3,9,1,2]; | |
const Capacity = 8; | |
let Count = 4; | |
(function main() { | |
// find the maximum value that will decide the size of counts array | |
const max = Math.max(...array); | |
// visualize { | |
arrayTracer.set(array); | |
insertArrayTracer.set(itemsToInsert); | |
Tracer.delay(); | |
// } | |
function InsertRange(index, items) | |
{ | |
// TODO: This should get the bounds checking conditional compilation too: | |
if (Count + 4 > Capacity) { | |
logTracer.print("Count is outside capacity\n"); | |
return; | |
} | |
logTracer.print("Shifting elements...\n"); | |
//Shift Elements [index..] forward by 4 | |
for (oldIndex = Count - 1; oldIndex >= index; oldIndex--) { | |
// visualize { | |
const fromIndex = oldIndex; | |
const toIndex = oldIndex + 4; | |
const newNumber = array[fromIndex]; | |
const oldNumber = array[toIndex]; | |
arrayTracer.select(toIndex); | |
Tracer.delay(); | |
// set the value in the array | |
arrayTracer.patch(toIndex, newNumber); | |
Tracer.delay(); | |
arrayTracer.depatch(toIndex); | |
arrayTracer.deselect(toIndex); | |
// } | |
// this[oldIndex + 4] = this[oldIndex]; | |
} | |
logTracer.print("Inserting elements...\n"); | |
//Add the range of items into the list | |
for (i = 0; i < 4; i++) { | |
// visualize { | |
const toIndex = index + i | |
const newNumber = items[i]; | |
insertArrayTracer.select(i); | |
arrayTracer.select(toIndex); | |
// set the value in the array | |
arrayTracer.patch(toIndex, newNumber); | |
Tracer.delay(); | |
arrayTracer.depatch(toIndex); | |
arrayTracer.deselect(toIndex); | |
insertArrayTracer.deselect(i); | |
// } | |
// array[index+i] = items[i]; | |
} | |
//Increment the count | |
//Count += 4; | |
} | |
InsertRange(0, itemsToInsert); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment