I'm new here. I have spent the entire day trying to figure out what is wrong with my code. Yes, it might be a simple questions for you, since I just started JavaSript about a month ago. Anyways, your help in identifying the error in my code is greatly appreciated!
==========================================================================
The Question:
Code a function called extremeValue. It takes 2 parameters. The first is an array of integers (you do not need to validate this). The second parameter is either the String “Minimum” or “Maximum”. The function returns the minimum or maximum element value in the array depending on the second parameter’s value.
Do not use Math.min or Math.max. The standard algorithm for finding a minimum value in an array is to assume the first element (at index 0) is the current minimum. Then process the array repetitively from its second element to its last. On each iteration compare the current element being processed with the current minimum. If it’s less than the minimum set it as the current minimum. In this way at the end of processing the current minimum holds the minimum element value in the array. A similar process will work for finding the maximum. Test your code. (1 mark)
This function does two different jobs depending on its second parameter. What are the pros and cons of this approach to coding functions?
My Answer (which doesn't work):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Eng1003 Workshop Code Week 04</title>
<style>
#outputArea{
padding: .25em;
border: solid black 2px;
margin: 3em;
height: 20em;
width: 20em;
overflow-y: scroll;
font-family: arial "sans serif";
font-size: 1em;
color: rgb(50, 50, 250);
background-color: rgb(225,225,225) ;
}
</style>
</head>
<body>
<!-- -->
<div id="outputArea"></div>
<script>
function maximum(setOfValues){
var retVal = "" ;
var length = setOfValues.length ;
var max = 0 ;
for (var i = 0; i < length; i++){
if (setOfValues[i] > max){
max = setOfValues[i] ;
}
}
retVal = max ;
return retVal ;
}
function minimum(setOfValues){
var retVal = "";
var length = setOfValues.length ;
var min = 0 ;
for (var i = 0; i < length; i++){
if (setOfValues[i] < min){
min = setOfValues[i] ;
}
}
retVal = min;
return retVal ;
}
function extremeValue(setOfValues, command){
var outString = "" ;
var retVal = "" ;
if (command = "Maximum"){
outString = "The maximum value is " + maximum(setOfValues) + "." ;
} else if (command = "Minimum"){
outString = "The minimum value is " + minimum(setOfValues) + "." ;
} else {
outString = "Sorry, but your command is unclear. Please ensure that your input is either 'Maximum' or 'Minimum'." ;
}
retVal = outString ;
return retVal ;
}
var target = document.getElementById("outputArea") ;
var inputCommand = prompt("What is your command?") ;
var inputValues = [10,30,500, 1000] ;
var finalAnswer = "" ;
finalAnswer = extremeValue(inputValues, inputCommand) ;
target.innerHTML = finalAnswer ;
</script>
</body>
The problem is the way you're checking your prompted value:
if (command = "Minimum")
if (command = "Maximum")
Here you're assigning strings to command. The code should be (assuming we're using strict equality):
if (command === "Minimum")
if (command === "Maximum")
DEMO
In you HTML page, call the Result function as below:
<script>
Result.init();
</script>
var Result = function () {
var maximum = function (array) {
var val = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] > val) {
val = array[i];
}
}
return val;
}
var minimum = function (array) {
var val = 0;
for (var i = 0; i < array.length; i++) {
val = array[i];
if (array[i] < val) {
val = array[i];
}
}
return val;
}
var start = function () {
var inputValues = [10, 30, 500, 1000];
var min = minimum(inputValues);
var max = maximum(inputValues);
}
return {
init: function () {
start();
}
};
}();
Related
So I wrote a pretty basic code. I'm a real noob. Started JavaScript 3 days back. I want the sorting process to be visualized while the sorting is going on. But when the SORT button is clicked after a while the sorted array is show. But what I want is to show the changes happening to the array in real-time.
Please help me out.
var array = [];
container_content= "";
for (var i=0; i < 50; i++) {
array.push(Math.random() *500)
}
container_content = "";
function myFunction(element) {
container_content += '<div class="array-bar"></div>';
}
array.forEach(myFunction);
$(".container").html(container_content);
function another(element, index){
element.style.height = array[index]
}
$( "div" ).each( function( index, element ){
$( this ).css('height', array[index]);
});
$('button').click(function(){
var i, j, temp;
for(i = 0; i < array.length; i++)
{
for(j = 0; j < array.length-1; j++)
{
if( array[j] > array[j+1])
{
// swap the elements
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
$( "div" ).each( function( index, element ){
$( this ).css('height', array[index]);
});
}
})
I took what you were trying to do and broke it down into 4 basic functions (1 main function and 3 helper functions).
runSort is the main function that uses all the other helper functions to do everything.
makeArrayAndUnsyncedBars generates your random array and basic divs that you'll use as green "bars", but it doesn't set the heights of these divs according to the values in the array.
syncArrayToBars sets the heights of these "bar" divs according to the values in the array
sortUntilNextSwap sorts the array until either a swap occurs or the sort completes. this function returns false if it made a swap (meaning that it's still working its way through the array) or true otherwise.
var FRAMES_PER_SECOND = 50;
var sortInterval = null;
function runSort() {
clearInterval(sortInterval);
makeArrayAndUnsyncedBars(50);
syncArrayToBars();
sortInterval = setInterval(function() {
var finishedSorting = sortUntilNextSwap();
syncArrayToBars();
if (finishedSorting) clearInterval(sortInterval);
}, Math.round(1000 / FRAMES_PER_SECOND));
}
var array = [];
function makeArrayAndUnsyncedBars(numberOfValues) {
var htmlToAdd = "";
array = [];
for (var i = 0; i < numberOfValues; i++) {
htmlToAdd += "<div class=\"bar\"></div>";
array.push(rando(150));
}
$("#bars").html(htmlToAdd);
}
function syncArrayToBars() {
for (var i = 0; i < array.length; i++) $(".bar").eq(i).css({
height: array[i] + "px"
});
}
var i, j, temp;
function sortUntilNextSwap() {
for (i = 0; i < array.length; i++) {
for (j = 0; j < array.length - 1; j++) {
if (array[j] > array[j + 1]) {
// swap the elements
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
return false;
}
}
}
return true;
}
.bar {
width: 5px;
background: #5aedab;
border-radius: 3px;
display: inline-block;
margin: 0px 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://randojs.com/1.0.0.js"></script>
<div id="bars"></div>
<button onclick="runSort();">Run sort</button>
EDIT: I should mention that I used rando.js for the randomness out of habit, but it's not super necessary here given that you use Math.random() very little anyway. Take it out or leave it in according to your preference.
I can get my array to work and display perfectly as a 2d array but the second I attempt to add another element it never shows it always stays undefined. I tried many different methods, in this version I attempted to duplicate the way that I add the 2d elements.
Ultimately I want to save data to the array to make the walls "#" that are displaying correctly to have further data stating "solid" and then I would be able to test for that before moving the "#"
I actually have a working version of this but using a second array which would get very cumbersome if I add further data.
Also as it is right now I am surprised the entire map is not getting overwritten with the letter k
function gameloop(){
var mainArray = [];
var mapSizeX = 32;
var mapSizeY = 128;
var arrayDepth = 10;
var idPos = {x:0, y:0};
function initMap(mainArray, mapSizeX, mapSizeY){
for (var i = 0; i < mapSizeX; i++) {
mainArray.push([0])
for (var j = 0; j < mapSizeY; j++) {
mainArray[i][j] = ".";
if(j == 0){mainArray[i][j] = "#";}
if(j == mapSizeY-1){mainArray[i][j] = "#";}
if(i == 0){mainArray[i][j] = "#";}
if(i == mapSizeX-1){mainArray[i][j] = "#";}
for (var k = 0; k < arrayDepth; k++) {
mainArray[i][j][k] = "k";
}
}
}
}
function nl(){GameScreen.innerText += "\n";}
function render() {GameScreen.innerText = mainArray.map(arr => arr.join("")).join("\n");
nl(); nl();}
function reposition(xChange,yChange,strA){
//mainArray[idPos.x][idPos.y] = ".";
//idPos.x = idPos.x + xChange;
//idPos.y = idPos.y + yChange;
//mainArray[idPos.x][idPos.y] = "#";
if(mainArray[idPos.x+xChange][idPos.y+yChange][1] === "Solid"){GameLog.innerText ="You can not travel in that direction"}
else{
mainArray[idPos.x][idPos.y] = ".";
idPos.x = idPos.x + xChange;
idPos.y = idPos.y + yChange;
mainArray[idPos.x][idPos.y] = "#";
GameLog.innerText = "You take a step to the " + strA
alert(mainArray[0][0][1]);
}
render();
}
//Startup
initMap(mainArray, mapSizeX, mapSizeY);
idPos.x = mapSizeX/2; idPos.y = mapSizeY/2;
mainArray[idPos.x][idPos.y] = "#";
//First Render
render();
document.addEventListener('keydown', function(event) {
if(event.keyCode === 38 ){reposition(-1,0,"North");}
if(event.keyCode === 40 ){reposition(1,0,"South");}
if(event.keyCode === 37 ){reposition(0,-1,"West");}
if(event.keyCode === 39 ){reposition(0,1,"East");}
//alert(event.keyCode);
});
}
gameloop();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Hello</title>
</head>
<body>
<br>
<p style="color:#7d7d7d;font-family:Lucida Console;">Dungeon Valley.<br>
<font style="color:#ABABAB;font-family:Lucida Console;font-size:0.5em";>
Taming the Borderlands.<br>
v0.005 By heromedel. </P></font>
<P>
<section id="GameScreen" style="color:#000000;font-family:Lucida Console;"></section>
<P>
<section id="GameLog" style="color:#000000;font-family:Lucida Console;">Arrow Keys to move.<br></section>
<script src="main.js"></script>
</body>
</html>
If I'm understanding what you're trying to do, this is wrong:
for (var k = 0; k < arrayDepth; k++) {
mainArray[i][j][k] = "k";
}
mainArray is supposed to be a 2d array of strings, right? So why are you using var k to add a 3rd dimension to it? Unless you're trying to append to the string? In Javascript you append to strings with +, not with [].
By the way, this is also wrong:
mainArray.push([0])
You want to push an empty array [], not an array with a 0 in it [0].
Good day. Have patience first of all since I am just a new enthusiast to Javascript and programming in general. The concern about my project is that I want to assign a value to a global variable through input method and run it through. I've tried, researched and nothing more work for me at this time. So I am asking anyone for ideas, how will it be possible. Your assistance will definitely help me in my learning process.
Initially, the code looks likes this: Here the global variable numItems is defined by 30. That variable numItems is also mentioned within two other functions below. What I want to do is change that number through input method. I've tried...
numItems = 30;
var xvalue = [];
var yvalue = [];
for (var i=0; i < numItems; i++) {
xvalue.push(i % 9); yvalue.push((i % 9)+1);
}
followed by several functions....
This is my try, but it seems this is not working... Any assistance will be greatly appreciated.
numItems = document.getElementById("numInput");
numItems.addEventListener("input", whatValue);
function whatValue() {
var num = parseFloat(numItems.value);
document.getElementById("numInput") = num;
}
var xvalue = [];
var yvalue = [];
for (var i=0; i < numItems; i++) {
xvalue.push(i % 9); yvalue.push((i % 9)+1);
}
followed by several functions....
Here is the whole code when I applied Michael's suggestions below: It works, but my concern now are the undefined variables in the output---> undefined + undefined or undefined - undefined
<body>
<input id="numInput">
<select id="processMath">
<option value="add">Addition</option>
<option value="sub">Subtraction</option>
</select>
<button onclick="newExercise()">New Exercise</button>
<button onclick="createExercise()">Create Exercise</button>
<div id="tableOne"></div>
</body>
<script type="text/javascript">
numItems = document.getElementById("numInput");
numItems.addEventListener("input", whatValue);
function whatValue() {
numItems = parseFloat(document.getElementById("numInput").value);
}
xvalue = [];
yvalue = [];
for (var i=0; i<numItems ; i++) {
xvalue.push(i % 9); yvalue.push((i % 9)+1);
}
function tableOne (operator) {
var valtp = '';
var spc = '<table border="1" width="80%"><tr>';
i = 0;
while (i < numItems ) {
a = xvalue[i];
b = yvalue[i];
spc += '<td align="right">'+a;
if (operator == 'add') { spc += '<br>+ '+b; valtp = a+b; }
if (operator == 'sub') { spc += '<br>- '+b; valtp = a-b; }
spc += '<br>_____';
i++;
if ((i % 5) == 0) { spc += '</tr><tr>'; }
}
spc += '</tr></table>';
return spc;
}
function createExercise() {
var a = 0; var b = 0; var spc = '';
var spc = '';
var sel = document.getElementById('processMath').value;
switch (sel) {
case 'add' : spc += tableOne(sel); break;
case 'sub' : spc += tableOne(sel); break;
}
document.getElementById('tableOne').innerHTML = spc;
}
function makeRandom() {
return (Math.round(Math.random())-0.5);
}
function newExercise() {
xvalue.sort(makeRandom);
yvalue.sort(makeRandom);
}
</script>
Unless I've misunderstood you, it looks like your whatValue() function is trying to change the input value, instead of changing the numItems variable, but it's failing on both counts.
function whatValue() {
var num = parseFloat(numItems.value);
document.getElementById("numInput") = num;
}
Should be:
function whatValue() {
numItems = parseFloat(document.getElementById("numInput").value);
}
Now, your numItems variable should change every time numInput changes.
But, even though numItems changes, it won't make the rest of your code run again. So your two arrays will still look like they did when numItems was 30.
I'm trying to find out what characters has the user changed in a string. I luckily can assume there's only one, consequent change block.
I've even failed to find where the changed area begins:
var originalVal, val; //strings
//The ranges
var original = [0,0];
var new_rang = [0,0];
//Old length, new length
var ol = originalVal.length;
var nl = val.length;
//Find where the change begins (that should be the same for both arrays)
for(var i=0; ; i++) {
//If end of string was reached or the strings are different
if((i>=ol||i>=nl) || originalVal[i]!=val[i]) {
original[0] = new_rang[0] = i;
//Set these to i too, assuming there was no change
original[1] = new_rang[1] = i;
break;
}
}
This totally breaks if there's a row of same characters and user deletes one in the middle:
mmmmx
mmmmx
mmmx
Script will say that the change occured at 4, where the x moved. But in fact, it doesn't even seem to be possible to say which m was deleted.
I can however tell where the cursor position was at the beginning and where it is in the end. That way it looks more promising, but I still don't know what to do:
mm|mmx
mm|mmx
m|mmx
This time I can see which m was deleted. But I still don't know how to explain it to a computer.
Here is what I think you might be looking for. Please clarify your question.
var Console = function() {
this.log = function(msg) {
debug(msg)
};
};
var console = new Console();
function diffLengths(longer, shorter) {
var indexes = [];
var isTheSame = true;
for (var i = 0; i < shorter.length; i++) {
if (shorter[i] != longer[i]) {
isTheSame = false;
indexes.push(i);
}
};
if (isTheSame) {
// The shorter string is exactly the same as the longer string
// except for the extra characters in the longer string
indexes.push(shorter.length);
}
return indexes;
}
function getDiffRange(first_string, second_string) {
var indexes = [];
if (first_string.length > second_string.length) {
return diffLengths(first_string, second_string);
} else if (first_string.length < second_string.length) {
return diffLengths(second_string, first_string);
} else {
for (var i = 0; i < first_string.length; i++) {
if (second_string[i] != first_string[i]) {
indexes.push(i);
}
};
}
return indexes;
}
var range = getDiffRange('mmmmx', 'mmmx');
document.getElementById('result-1').innerHTML = range[0] + " - " + range[range.length - 1];
var range = getDiffRange('mmmmx', 'mmmxc');
document.getElementById('result-2').innerHTML = range[0] + " - " + range[range.length - 1];
var range = getDiffRange('mm', 'mmx');
document.getElementById('result-3').innerHTML = range[0] + " - " + range[range.length - 1];
table, th, td {
border-collapse: collapse;
border: 1px solid #ddd;
text-align: left;
padding: 7px;
}
<html>
<body>
<table>
<tr>
<th>input</th>
<th>result</th>
</tr>
<tr>
<td>'mmmmx', 'mmmx':</td>
<td id='result-1'></td>
</tr>
<tr>
<td>'mmmmx','mmmxc':</td>
<td id='result-2'></td>
</tr>
<tr>
<td>'mm','mmx':</td>
<td id='result-3'></td>
</tr>
</table>
</body>
</html>
I want to change the number by chooesing 6 numbers from 49 numbers, so first I declared a div and have six span in it to contain a number.
And I want to change it by getElementByTagName to assign a new number combined with setInterval to make it always changing but it doesn't work.
Where is my wrong place?
Thx.
function computeRandom(){
var value = new Array(49);//declare array
for ( i = 0; i < 49; i++ )//initial array_value
value[i] = i+1;
for ( i = 0 ;i < 100; i++ ) {//random arrange
x = parseInt(Math.random()*49);
y = parseInt(Math.random()*49);
tmp = value[x];
value[x] = value[y];
value[y] = tmp;
}
var color = new Array(49);
for ( i = 0; i < 49; i++ )//store color
color[i] = "rgb(" + parseInt(Math.random()*255) + "," + parseInt(Math.random()*255) + "," + parseInt(Math.random()*255) + ")";
var value_tmp = new Array(6);
for( i = 0; i < 6; i++)
value_tmp[i] = value[i];
document.write("<div style = \"text-align:center;\" >");//center the text by div
for( i = 0; i < 6; i++)
document.write("<span style = \"font-size: 2.5em; display:inline-block; text-align:center; width: 1.5em; background: white; color: " + color[i] + " \" > "
+ value_tmp[i] + "</span>     ");
var spanArray = document.getElementsByTagName("span");
setInterval("keepMove(value,spanArray)",10);
}
function keepMove(val,sp){
var index = parseInt(Math.random()*43);//set a increment to avoid repeatition
for( i = 0; i < sp.length; i++){
sp[i].innerHTML = val[i+index];
document.write(sp[i].innerHTML+" ");
}
}
CSS:
#bg {
background: grey;
opacity: 0.8;
}
#hl {
text-align: center;
color: white;
}
HTML:
sorry I don't know how to post the HTML?
http://codepad.org/IrSOsjg7
I have tried the commentor's advice but still not work but thx for your help!
I very appreciate it!
I think the problem is setInterval("keepMove(value,spanArray)",10)
when you pass a string as the first parameter of setInterval, it's like eval that string, and the code will run in global environment, because there is no variable value and spanArray in the global environment, the code will not run correctly.
For example:
function foo(x, y) {
alert(x + " " + y);
}
function bar() {
var x = 100, y = 200;
setInterval("foo(x, y)", 1000);
}
bar();
this will get the error x is not defined
You can try:
setInterval(function(){
keepMove(value, spanArray);
}, 10);
Try to change the way you use the setInterval. You should use a closure to be able to access the value and spanArray vars.
setInterval(function(value, spanArray) {
return function() {
keepMove(value,spanArray)
}
}(value, spanArray),10);
}
That's because setTimeout will be executed on the global context, and from there you can't access those private vars.