JSFiddle - React, Tailwind, and code Playground

by Robert Mochel

HTML

<div id="wrapper">
  <h3>Module 1 (1 and 2)</h3>
  <br/> Value:
  <input type="textbox" id="value" value="22" />
  <br/> Index:
  <input type="textbox" id="index" value="11" />
  <br/> Number of operations:
  <div id="operations"></div>
  <input type="button" value="Array" onClick="fillArray();" />
  <input type="button" value="Search the Array" onClick="searchArray();" />
  <br/>
  <input type="button" value="Insert into Array" onClick="insertIntoArray();" />
  <br/>
  <div id="output"></div>
  <div id="result"> - This algorithm is O(n)</div>
</div>

CSS

#wrapper {
  width: 280px;
  overflow: auto;
}

#output {
  float: left;
  width: 40%; 
}

#result {
  margin: 0 0 0 118px;
}

JavaScript

//Assignment 1 and 2
var array = []; // Global array 
var d = ""; // Global string 
var o = "0"; //Counter
var n = "10" //Global variable 
var s = "not searched yet"; //Variable for search output


function fillArray() {
  //function to clear the display values
  clearDisplay();
  // simple loop hard coded to 1000 to set array values
  for (var i = 0; i < n; i++) {
    array[i] = Math.floor(Math.random() * 100 + 1);
    o++;
  }
  // call function to display the array
  displayArray();
  // call function to display the number of operations
  displayOperations();
}

function clearDisplay() {
  //Global string d is used to hold display
  d = "";
  // The div element named output is used to display output
  document.getElementById("output").innerHTML = "";
}


function displayArray() {
  // simple loop to add array values to string d
  for (var i = 0; i < array.length; i++) {
    d += i + ' : ' + array[i] + "<br/>";
    o++;
  }
  document.getElementById("output").innerHTML = d;
}

function displayOperations() {
  //clear the old value
  document.getElementById("operations").innerHTML = "";
  //display the new count
  document.getElementById("operations").innerHTML = o;
}

function searchArray() {
  var i = parseInt(document.getElementById("index").value);
  var v = parseInt(document.getElementById("value").value);
  for (var i = 0; i < array.length; i++) {
    o++;
    if (array[i] == v) {
      s = "Last " + v + " found at # " + i + "<br/>";
      displaySearchResults(s);
      o++;
    }
    displayOperations();
  }
}

function displaySearchResults() {

  document.getElementById("result").innerHTML = s;
}

function insertIntoArray() {
  clearDisplay();
  // get value of index of value to insert
  var i = parseInt(document.getElementById("index").value);
  // get actual value to insert at index i
  var v =
    parseInt(document.getElementById("value").value);
  //new index
  var ni = i;
  var nv = v;
  d = "Inserting " + v + " at " + i + " " + "<br/>";
  for (var...