Assignment 2
Assignment 2
by dhizzybusy
HTML
<!DOCTYPE html>
<html lang="en-US">
<head>
<title> Random Numbers</title>
<meta charset="utf-8">
</head>
<body>
Enter Array Size:
<input type="textbox" id="size" value="100" />
<input type="button" value="Create Array" onClick="fillArray();">
<br/>
<br/> Enter Location :
<input type="textbox" id="location" value="" /> Enter Value to Insert:
<input type="textbox" id="value" value="" />
<input type="button" value="Insert into Array" onClick="insertIntoArray();" />
<br/>
<br/> Enter Value to Find:
<input type="textbox" id="SearchArray" />
<input type="button" value="Search Array" onClick="searchIntoArray();" />
<br/>
<div id="output">
</div>
</body>
</html>
JavaScript
var array = []; // Global array to hold array
var d = ""; // Global string for output
function fillArray() {
// call function to clear the display values
clearDisplay();
// simple loop hard coded to 100 to set array values
for (var i = 0; i < 100; i++) {
array[i] = Math.floor(Math.random() * 100 + 1);
}
// call function to display the array
displayArray();
}
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/>";
}
document.getElementById("output").innerHTML = d;
}
function insertIntoArray() {
clearDisplay();
// get value of index of value to insert
var i = parseInt(document.getElementById("location").value);
// get actual value to insert at index i
var v =
parseInt(document.getElementById("value").value);
var display = array;
var copyArray = [];
for (var index = 0; index < display.length; index++) {
copyArray[index] = display[index];
}
display[i] = v;
for (var a = i + 1; a < display.length; a++) {
display[a] = copyArray[a - 1]
}
array = display;
displayArray();
}
function searchIntoArray() {
clearDisplay();
var sval = parseInt(document.getElementById("SearchArray").value);
var b = array.indexOf(sval);
if (b == -1) {
d += sval + " Was not found !" + "<br/>";
} else {
d += sval + " Was found at position " + b + " <br/> ";
}
document.getElementById("output").innerHTML = d;
}