im currently doing an assignment where we have a certain amount of people play a game and each player have an attempt of scoring. The scores will be randomly generated from 1-3. The only problem i have is to store the randomly generated value into the array and then summing them up. This way, i can produce a leader board that say something like "congrats (player name) your total score is (total score)). Any suggestion on how to do these's would be great or better yet, any other alternatives would be appreciated as well. So far i've been using a incremental counter to generate the total score but it keeps generating the same number over and over again e.g. (2,2,2,2...) (1,1,1,1,....)
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function main()
{
randomnumber()
totalscore()
}
function randomnumber()
{
var randomnumber;
randomnumber = Math.random()*3;
return(Math.floor(randomnumber+0.5));
}
function totalscore()
{
var n;
var score = 0;
number = randomnumber();
for (n = 0 ; n < 11 ; ++n)
{
if (number == 0)
{
score = score + 0;
}
else if (number == 2)
{
score =score + 2;
}
else if (number == 3)
{
score =score + 3;
}
}
document.write(score)
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> main() </SCRIPT>
<INPUT NAME = "dobutton" TYPE = "button" value = "Start game" on Click = "game()">
<INPUT NAME = "dobutton" TYPE = "button" value = "Leaderboard" on Click = "leader()">
</BODY>
</HTML>
This may help, although you should try first before posting for solutions.
Create an empty array:
var myArray = [];
Add values to array (from your randomnumber() generator):
myArray.push(randomnumber());
myArray.push(randomnumber());
myArray.push(randomnumber());
Function to sum the values of some array (this is perhaps the most primitive but faster/efficient way to do it):
var sumElements = function(someArray) {
if (someArray == null) return false;
var sum = 0;
for (var i = 0, len = someArray.length; i < len; i++) {
sum += someArray[i];
}
return sum;
}
Call sumElements to find the sum:
sumElements(myArray);
Here is the simplest way to do what you need
var randomArray = [];
var randomSum = 0;
randomArray.push(randomnumber());
randomArray.push(randomnumber());
randomArray.push(randomnumber());
for(var i=0; i<randomArray.lenth; i++){
randomSum += randomArray[i];
}
Related
I'm a noob, and I'm having a really hard time understanding how to do this with my limited learning so far. The assignment is to sort inputed gpas highest to lowest, to give an average, to pull the highest & lowest, and to separate and output all the gpas above 3.4. I can accomplish this. My problem is that I am trying to have a string outputted stating "no good students this year" if there are NO gpas above 3.4 and I am beating my head against the wall for hours. Can anyone help?
Here is the code and my notes:
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="output">
</div>
<script>
var gpasOut = [];
var gpas = [];
while (gpasOut != "XXX")
{
gpasOut = prompt("Enter a GPA or XXX to Stop");
if (gpasOut != "XXX")
{
gpas.push(parseFloat(gpasOut));
}
}
// This sets the vars as empty and prompts the user for integers and allows a break with "XXX";
// gpas.push pushes the values from the prompt (gpasOut) into gpas &
// parseFloat turns the strings into floating decimals;
length = gpas.length;
// This gets the number of integers entered at prompt.
function totalArray(total, num)
{
return total + num;
}
var total = gpas.reduce(totalArray);
// This gets the sum of all numbers in array. Not sure I understand this code, but I was able to make it work.
// I think it brings the numbers from the right (num) into the number on the left (total), thus "reducing" it.
//
// I'm sure there is a better way.
var average = total / length;
// This gives the average GPA
var sorted = gpas.sort(function (a, b)
{
return b - a
});
// This sorts the GPAs highest to lowest. Not sure I understand how it works.
var badGpas = "<p>There were no good students this year. Try again next year!</p>";
let goodGpas = [];
for (let i = 0; i < gpas.length; i++)
{
if (gpas[i] >= 3.4)
{
goodGpas.push(gpas[i]);
}
else {
badGpas
}
}
// Here I want to print the string in BadGpas if there were NO gpas above 3.4!
document.getElementById('output').innerHTML =
"<h2>GPAs</h2><h3>Sorted Highest to Lowest: </h3>" + sorted.join("<br>")
+"<h3>Class Average GPA is</h3>" + average + "<br>"
+ "<h3>The Highest is:</h3>" + gpas[0]
+ "<h3>The Lowest is:</h3>" + gpas[gpas.length-1]
+ "<h3>Outstanding GPAs (above 3.4)</h3>" + goodGpas.join("<br>")+badGpas;
</script>
</body>
</html>
Building on what you have, you could initialize the badGpas variable as an empty string:
let badGpas = '';
Then, after you have checked the gpas in the loop and pushed all the ones that are above 3.4 into the goodGpas array, you could check if the array is empty. If the array is empty, then set the badGpas value to the text that you want to display:
let badGpas = '';
let goodGpas = [];
for (let i = 0; i < gpas.length; i++)
{
if (gpas[i] >= 3.4)
{
goodGpas.push(gpas[i]);
}
}
if (goodGpas.length === 0) {
badGpas = "<p>There were no good students this year. Try again next year!</p>";
}
Fixed:
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<div id="output">
</div>
<script>
var gpasOut = [];
var gpas = [];
while (gpasOut != "XXX")
{
gpasOut = prompt("Enter a GPA or XXX to Stop");
if (gpasOut != "XXX")
{
gpas.push(parseFloat(gpasOut));
}
}
// This sets the vars as empty and prompts the user for integers and allows a break with "XXX";
// gpas.push pushes the values from the prompt (gpasOut) into gpas &
// parseFloat turns the strings into floating decimals;
length = gpas.length;
// This gets the number of integers entered at prompt.
function totalArray(total, num)
{
return total + num;
}
var total = gpas.reduce(totalArray);
// This gets the sum of all numbers in array. Not sure I understand this code, but I was able to make it work.
// I think it brings the numbers from the right (num) into the number on the left (total), thus "reducing" it.
//
// I'm sure there is a better way.
var average = total / length;
// This gives the average GPA
var sorted = gpas.sort(function (a, b)
{
return b - a
});
// This sorts the GPAs highest to lowest. Not sure I understand how it works.
var foundGpasAbove = false
let goodGpas = [];
for (let i = 0; i < gpas.length; i++)
{
if (gpas[i] >= 3.4)
{
foundGpasAbove = true;
goodGpas.push(gpas[i]);
}
}
// Here I want to print the string in BadGpas if there were NO gpas above 3.4!
if(foundGpasAbove) {
document.getElementById('output').innerHTML =
"<h2>GPAs</h2><h3>Sorted Highest to Lowest: </h3>" + sorted.join("<br>")
+"<h3>Class Average GPA is</h3>" + average + "<br>"
+ "<h3>The Highest is:</h3>" + gpas[0]
+ "<h3>The Lowest is:</h3>" + gpas[gpas.length-1]
+ "<h3>Outstanding GPAs (above 3.4)</h3>";
} else {
document.getElementById('output').innerHTML = '<p>There were no good students this year. Try again next year!</p>'
}
</script>
</body>
</html>
Explanation:
I putted a flag foundGpasAbove initialed at false before the loop that you add gpas if its more than 3.4. if you add even one then i make this flag true. after with this flag if false i print the message that you want "There were no good students this year. Try again next year!"
So I am trying to create a function that takes the first input as a number and the second input as a string. the function should then change the innerHTML of the div with the characters of the second input. For example. if the first input was number 2 and second input was hello the innerHTML should change to:
h
ee
if the first was number 5 all else being the same:
h
ee
lll
llll
ooooo
I know I must use str.charAT and possibly a for loop (probably any loop) but just cant seem to piece it together in my head. I have been stuck on this for 6 hours now and I have no idea how to do it. So here I am asking for help XD, help my please! If any hints are out there I would gladly take them, this is just a random exercise to help me get used to js. If you would rather like to give the entire that is fine too, I mean it helps alot more than a hint considering i can learn from it.
the number cannot go past the amount of characters within the string. So far here is the html and javascript that I made.
<html>
<head>
<script src="q2.js" type="text/javascript"></script>
</head>
<body>
<div> Input1<input id="input1" type="text"></div>
<div> Input2<input id="input2" type="text"></div>
<div> Result<div id="result"></div></div>
<button onclick="compute()">Compute</button>
</body>
<html>
JAVASCRIPT:
function compute(){
var n = Number(document.getElementById("input1").value);
var v = document.getElementById("input2").value;
var answer = document.getElementById("result");
var i,j;
answer.innerHTML = "";
if(n){
}else{
alert("whatever is in input 1 is not a number ya fookin cheeky buggah");
}
if(n>v.length){
alert("number 1 bigger than word 2");
}
for(i=0;i<n;i++){
for(j=0;)
}
}
This does what you need, however it may be using some array functions you're not familiar with
function compute() {
var n = Number(document.getElementById("input1").value);
var v = document.getElementById("input2").value;
var answer = document.getElementById("result");
if (!n) {
alert("whatever is in input 1 is not a number ya fookin cheeky buggah");
}
if (n > v.length) {
alert("number 1 bigger than word 2");
}
answer.innerHTML = [].slice.call(v, 0, n).map(function(letter, index) {
return new Array(index+2).join(letter);
}).join('<br />');
}
slice - we only want the first n characters
map - for each character, run the callback function
the callback function creates an Empty array which is 2 larger than the current index (0 based index)
joins this array on the letter - which produces index + 1 letters
the mapped array is joined by <br />
the result of this is output to answer.innerHTML
the answer.innerHTML code in ES2015 (ES6) would be
answer.innerHTML = [].slice.call(v, 0, n).map((letter, index) => letter.repeat(index+1)).join('<br />')
The answer using nested for loops and charAt
function compute() {
var n = Number(document.getElementById("input1").value);
var v = document.getElementById("input2").value;
var answer = document.getElementById("result");
var i, j, c, s = "";
if (n) {
}
else {
alert("whatever is in input 1 is not a number ya fookin cheeky buggah");
}
if (n > v.length) {
alert("number 1 bigger than word 2");
}
for (i = 0; i < n; i++) {
c = v.charAt(i);
if (i > 0) {
s += "<br />";
}
for (j = 0; j <= i; j++) {
s += c;
}
}
answer.innerHTML = s;
}
function compute() {
var n = Number(document.getElementById("input1").value);
var v = document.getElementById("input2").value;
var answer = document.getElementById("result");
if (!n) {
alert("whatever is in input 1 is not a number ya fookin cheeky buggah");
}
if (n > v.length) {
alert("number 1 bigger than word 2");
}
var res ="";
for(var i=1; i<=v.length; i++){
res = res +"\n"+ Array(i+1).join(v.charAt(i));
}
answer.innerHTML = res;
}
Whoever finds this answer to be useful or valid or wrong, please post ur comments or click the up/down arrow. Just to improve myself further.
Does anyone know how do i generate a new random number so i can store them into different variables? (into temp1 and temp2) I want the program to rerun the "randomnumber" function each time for each new variable so i can store the new random value into them.
<HTML>
<!Foundation Page for building our Javascript programs>
<HEAD>
<TITLE>The Foundation Page </TITLE>
<SCRIPT LANGUAGE = "JavaScript">
function main()
{
totalscore()
leaderboard()
}
function randomnumber()
{
var randomnumber;
randomnumber = Math.random()*3;
return(Math.floor(randomnumber+0.2));
}
function totalscore()
{
var n;
var p;
var total;
var temp1;
var temp2;
var score;
score = 0;
total=0
for (n=0; n<10; n=n+1)
{
number = randomnumber();
if (number == 0)
{
score =score+0;
}
else if (number == 2)
{
score =score+2;
}
else if (number == 3)
{
score =score+3;
}
total=total+score;
}
temp1= total
temp2= total
document.write(total)
document.write(total)
}
</SCRIPT>
<HEAD>
<BODY>
<BODY BGCOLOUR = "WHITE">
<H2>The Foundation Page </H2>
<HR>
<SCRIPT LANGUAGE = "Javascript"> main() </SCRIPT>
<INPUT NAME = "dobutton" TYPE = "button" value = "Start game" on Click = "game()">
<INPUT NAME = "dobutton" TYPE = "button" value = "Leaderboard" on Click = "leader()">
</BODY>
</HTML>
I think I know what you are asking and I'll post working code below as well as an explanation of why you are getting the same random number.
You have a for loop is generating the score and and returning a value that you are storing into total. The problem is you are assigning that number to both temp1 AND temp 2, so they are now the same number, then you are writing both numbers to the page. What you need to do is have 2 different calculations. the below code will fix it and give you 2 different numbers for you totals...
function totalscore()
{
var total1 = 0;
var total2 = 0;
for (var n=0; n<10; n++)
{
total1 = total1 + randomnumber();
total2 = total2 + randomnumber();
}
document.write(total1);
document.write(total2);
}
Now I was a little confused at your code because the score is compounding on itself every time it recalculates in the for loop. (ie if the first 5 scores were 1, 2, 2, 1, 3, then the total score would be 24, and not the expected 9. If that was intentional, the put in this code instead.
function totalscore()
{
var total1 = 0;
var total2 = 0;
var score1 = 0;
var score2 = 0;
for (var n=0; n<10; n++)
{
score1 = score1 + randomnumber();
total1 = total1 + score1;
score2 = score2 + randomnumber();
total2 = total2 + score2;
}
document.write(total1);
document.write(total2);
}
Good luck with your project and learning coding!
Issues I am noticing
No semicolons behind most statements
You are returning Math.floor on randomnumber + 0.2, which makes + 0.2 do nothing.
You are calling onclick='game()' on button click, but there is no game(), but maybe that's in code we can't see.
You are setting both temp1 and temp2 = total, and using document.write on total twice
Now, the question is how to generate a random number. You are doing that correctly, although you could simplify it and use Math.floor(Math.random()*3) or return Math.floor(Math.random()*3). Of course, you can switch out 3 and replace it now with whatever cap you wish.
For the sake of learning (I am very much a beginner), I am trying to write a function with that will generate random numbers according to three user inputed variables. The user can input how many random numbers to generate
var count = 10;
which numbers to avoid generating (seperated by commas)
var doNotInclude = (document.getElementById("doNotIncludeInput").value).split(",");
and what the highest number possible should be
var highestNumber = 10;
In theory, if the user inputed "1,2" for the doNotInclude variable, the function should create an array containing those two numbers and then each time it generates a random number, check it against the array to see if the number it generated is one of the numbers it isn't supposed to generate.
Unfortunately, it doesn't work. It creates the array as it should which I verified via console.log(), but it will still generate the numbers it isn't supposed to. Here's the full script:
document.getElementById("button").onclick = function() {
var total = 0,
average = 0,
random = 0,
count = parseInt(document.getElementById("countInput").value),
doNotInclude = document.getElementById("doNotIncludeInput").value).split(","),
highestNumber = parseInt(document.getElementById("highestNumberInput").value);
document.getElementById("text1").innerHTML = "";
for (var i = 0; i < count; i++) {
var proceed = false;
for (random = Math.floor(((Math.random()) * (highestNumber + 1))); proceed == false;) {
if (doNotInclude.indexOf(random)===-1) {
proceed = true;
}
}
document.getElementById("text1").innerHTML = document.getElementById("text1").innerHTML + "<br />" + (i + 1) + ". " + random;
total = total + random;
if (i == (count - 1)) {
total / count;
document.getElementById("text").innerHTML = "Mean average = " + (Math.round(total / count));
}
}
}
The part that isn't working
if (doNotInclude.indexOf(random)===-1) {
proceed = true;
}
the indexOf function, is something I read about on here, but I guess I don't fully understand it. By my understanding, it should check to see if any of the array values are the same as the random variable, and if not, then return "-1" and execute my code. It doesn't seem to be doing that though. I am super confused...would love some help. Is it possible the array is storing the numbers as strings instead of integers, and that is the problem?
Your if statement doesn't work because of coercion.
===-1
The array doNotInclude contains strings, but random is an integer value, === always compares value and type both.
You should either use ==. Or have the both types same.
Try this Fiddle
HTML
Count: <input id="countInput" value="10" /><br />
Do not include: <input id="doNotIncludeInput" value="0,1,2,3,4,5" /><br />
Highest Number: <input id="highestNumberInput" value="10" /><br />
<br />
<button type="button" id="button">Click to Run!</button><br />
<br />
Results:<br />
<div id="text1"></div>
Js
document.getElementById("button").onclick = function() {
var currentCount = 0;
var randomNumbers = [];
var count = parseInt(document.getElementById("countInput").value);
var doNotIncludeInput = document.getElementById("doNotIncludeInput").value.split(",");
var highestNumberInput = parseInt(document.getElementById("highestNumberInput").value);
var resultsElement = document.getElementById("text1");
resultsElement.innerHTML = "";
while(currentCount < count) {
var random = -1;
while(random === -1){
random = Math.floor((Math.random()) * (highestNumberInput + 1));
for(var i in doNotIncludeInput) {
if(parseInt(doNotIncludeInput[i]) === random){
random = -1;
}
}
if(random !== -1){
randomNumbers.push(random);
}
}
currentCount += 1;
}
resultsElement.innerHTML = randomNumbers.join(', ');
}
So I have this code now, and in input I have in ascending order my name's letters "ahimrsu". I need to show up the right number for "mariush" from all combinations which should to be 2170. For now it only show ahimrsu, ahimrus, ahimsru, ahimsur, ahimurs, ahimusr, ahirmus, ahirmsu.... etc How can I do this?
<!DOCTYPE HTML>
<html>
<head>
<!--Script Function Start Here-->
<script type="text/javascript">
function perms(data) {
if (!(data instanceof Array)) {
throw new TypeError("input data must be an Array");
}
data = data.slice(); // make a copy
var permutations = [],
stack = [];
function doPerm() {
if (data.length == 0) {
permutations.push(stack.slice());
}
for (var i = 0; i < data.length; i++) {
var x = data.splice(i, 1);
stack.push(x);
doPerm();
stack.pop();
data.splice(i, 0, x);
}
}
doPerm();
return permutations;
}
var input = "ahimrsu".split('');
var result = perms(input);
for (var i = 0; i < result.length; i++) {
result[i] = result[i].join('');
}
console.log(result);
</script>
<!--Header start here-->
</head>
<body>
<!--Script Result-->
<script type="text/javascript">
document.write(result);
</script>
</body>
</html>
Your question is of mathematics nature - combinations and permutations. You are actually asking the number of possible permutation for string length 7.
The formula is factorial(numOfchar).
In this case 7! = 7x6x5x4x3x2x1 = 5040.
public static void main(String[] args) {
String str = "ABCDEFH";
System.out.println("Number of permutations for " + str + " is : " + factorial(str.length()));
}
public static int factorial(int n)
{
if (n == 0)
return 1;
int result = factorial(n-1)*n;
return result;
}
Program Output:
Number of permutations for ABCDEFH is : 5040
Since you tagged Java, this is one way you can get the it done with Java.