random no generate(1-9) using 9 <div> without no repitation,,,,, - javascript

I have tried to generate rnadom number(1-9) in 9 div's. How to avoid number repitations? But it's not working, why i cant get output? Thanks in advance.
Here is my code:
<html>
<head>
<title>Random_No</title>
<link rel="stylesheet" type="text/css" href="rno.css">
<script src="rno.js" ></script>
</head>
<body class="outer" onload=random()>
<div id="input1" ></div>
<div id="input2" ></div>
<div id="input3" ></div>
<div id="input4" ></div>
<div id="input5" ></div>
<div id="input6" ></div>
<div id="input7" ></div>
<div id="input8" ></div>
<div id="input9" ></div>
<script>
function random()
{
var a=new Array("input1","input2","input3","input4","input5","input6","input7","input8","input9");
x=a.length;
var ran=new Array();
for(var i=0;i<x;i++)
{
ran[i]=Math.floor(Math.random()*9);
}
for(var i=0 ; i<x ; i++)
{
document.getElementById("a[i]").innerHTML=ran[i];
}
}
</script>
</body>
</html>

Replace
document.getElementById("a[i]").innerHTML=ran[i];
By
document.getElementById(a[i]).innerHTML=ran[i];
And... why 2 loops ?

Because you only want a small set of items randomised with no repeats and to take each one, a Fisher-Yates shuffle would be very efficient here.
var inputs = [], i;
for (i = 1; i < 10; ++i) // get each input
inputs.push(document.getElementById('input' + i));
function shuffleArray(a) { // Fisher-Yates shuffle, no side effects
var i = a.length, t, j;
a = a.slice();
while (--i) t = a[i], a[i] = a[j = ~~(Math.random() * (i+1))], a[j] = t;
return a;
}
inputs = shuffleArray(inputs); // shuffle
for (i = 0; i < 9; ++i) // give values (already shuffled)
inputs[i] = i + 1; // there will be no repeats because we're counting up

Another way to generate randoms from a set-
<!doctype html>
<html lang="en">
<head>
<meta charset= "utf-8">
<title>Random_No</title>
</head>
<body >
<div id= "input1"></div>
<div id= "input2"></div>
<div id= "input3"></div>
<div id= "input4"></div>
<div id= "input5"></div>
<div id= "input6"></div>
<div id= "input7"></div>
<div id= "input8"></div>
<div id= "input9"></div>
<script>
function random_no(){
var i=0, ran=[1,2,3,4,5,6,7,8,9];
while(i<9){
document.getElementById("input"+(++i)).innerHTML=
ran.splice(Math.floor(Math.random()*ran.length),1);
}
}
onload=random_no;
</script>
</body>
</html>

You need to change
document.getElementById("a[i]").innerHTML = ran[i];
to
document.getElementById(a[i]).innerHTML = ran[i];
because putting quotes around a[i] makes it look for an element whose id is actually "a[i]"

You can map the elements in another array, shuffle it and inject the random number in basically one chained operation using some array methods:
var divs = document.getElementsByTagName('div');
[].map.call(divs, function(e, i) {
return i;
}).sort(function() {
return (Math.round(Math.random())-0.5);
}).forEach(function(r, i) {
divs[i].innerHTML = r;
});
DEMO: http://jsfiddle.net/EsGL3/

You can use Array.sort() with a random comparator to re-order the values:
JSFIDDLE
function random()
{
var x = 9,
ids = [ 'input1', 'input2', 'input3',
'input4', 'input5', 'input6',
'input7', 'input8', 'input9'
],
values = [1,2,3,4,5,6,7,8,9],
i = 0;
Array.sort( values, function(a,b){ return Math.random() < 0.5 ? 1 : -1; });
for( ; i < x; ++i)
{
document.getElementById( ids[i] ).innerHTML = values[i];
}
}

Related

Pascal Triangle array not showing in HTML? How do i solve it?

<head>
<title> Pascal’s Triangle </title>
</head>
<body>
<header>
<div id="strong"> Pascal’s Triangle </div>
</header>
<div class="container">
<div>
<span id="enter"> Please enter any number: </span><input id="number" /> <br id="screen"/>
<button id="button" onclick="createPascalTriangle()"> Check »</button>
</div> <br/>
</div>
<div id="show"> </div>
<footer>
<div> ©Technical Challenge </div>
<footer>
<script>
function createPascalTriangle () {
var pascalTriangle = [];
var numRows = document.getElementById("number").value;
for (var i = 0; i < numRows; i++) {
pascalTriangle[i] = new Array(i+1);
for (var j = 0; j < i+1; j++) {
if (j === 0 || j === i) {
pascalTriangle[i][j] = 1;
} else {
pascalTriangle[i][j] = pascalTriangle[i-1][j-1] + pascalTriangle[i-1][j];
}
}
}
return pascalTriangle;
pascal = JSON.Stringify(pascalTriangle);
document.getElementById("show").innerHTML = pascal;
}
</script>
</body>
Pascal Triangle array not displaying in expected 'div'
How do i display these array of Pascal Triangle in HTML?
Here is my code. The 'div 'is not displaying anything
i tried the innerHTML property. the pascalTriangle output is an Array. But i'm unable to display the output in html
The problem might be:
its JSON.stringify (capitalization)
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
You are doing actions after your function returns a value. The function stops being executed as soon as the return statement is reached. You should write at the end of the function:
pascal = JSON.stringify(pascalTriangle);
document.getElementById("show").innerHTML = pascal;
return pascalTriangle;

Sort number javascript array

I need to sort the numbers that are drawn here from smallest to largest in the tables so that the table does not delete. How do I do that?
<html>
<head>
<title> Numery losowania </title>
<script>
var n1= new Array (9);
for(var i=0; i<n1.length;i++)
{
var rand= Math.floor(Math.random()*70);
n1[i] = rand;
}
document.writeln("<table border = \"1\"");
for(var i=0; i < n1.length;i++)
{
document.writeln("<tr><td>" + n1[i] + "</td></tr>");
}
document.writeln("</table>");
</script>
<form>
<input type="button" value="Odśwież" onclick="location.reload()">
</form>
</head>
Just add n1.sort(); before the loop.
The default sort order is according to string Unicode code points.
So you need to pass a function to it for sorting:
n1.sort((a,b) => a-b);
This will make sure that the lower numbers are first
For filling the array, use Array.from() this will save you some code
<html>
<head>
<title> Numery losowania </title>
<script>
var n1= Array.from({length: 9}, () => Math.floor(Math.random() * 70));
document.writeln("<table border = \"1\"");
n1.sort((a,b) => a-b); // sort the array
for(var i=0; i < n1.length;i++)
{
document.writeln("<tr><td>" + n1[i] + "</td></tr>");
}
document.writeln("</table>");
</script>
<form>
<input type="button" value="Odśwież" onclick="location.reload()">
</form>
</head>
<html>
<head>
<title> Numery losowania </title>
<script>
var n1= new Array (9);
for(var i=0; i<n1.length;i++)
{
var rand= Math.floor(Math.random()*70);
n1[i] = rand;
}
document.writeln("<table border = \"1\"");
n1.sort(function(a, b){return a - b});
for(var i=0; i < n1.length;i++)
{
document.writeln("<tr><td>" + n1[i] + "</td></tr>");
}
document.writeln("</table>");
</script>
<form>
<input type="button" value="Odśwież" onclick="location.reload()">
</form>
</head>
</html>

javascript - how to use a text box input in a for loop

I am trying to write a solution for a javascript application that takes a number input & depending on that number is how many times it runs a specific function. I am using a text box for input field & a button to process the number of times the user wants the function to run. It is for a game of dice game. User enters how many games he wants to play and clicks button to run the roll_dice function that many times. I'm not sure if I am going the right way with using a for loop to take users numeric input and loop through its value until it ends for example
function games() {
var num = document.getElementById("inp").vale;
var i;
for (i = 0; i < num; i++) {
roll_dice();
}
}
You have a typo. It's .value.
You can convert a string to a number by using * 1.
Something like this:
function games() {
var num = document.getElementById("inp").value * 1; // Convert the string value a number.
var i;
for (i = 0; i < num; i++) {
roll_dice();
}
}
function roll_dice() {
console.log("Test.");
}
var btnRun = document.getElementById("btnRun");
btnRun.onclick = function() {
games();
};
<input id="inp" type="text" />
<button id="btnRun" type="button">Run</button>
The value you get from input box is string you need to convert it into int . If you are using int in loop .
var num = parseInt(document.getElementById("inp").value);
function games() {
var num = document.getElementById("inp").value;
var i;
for (i = 0; i < Number(num); i++) {
roll_dice();
}
}
**<label>Game:</label><input type="text" id="input" value="0" />
<button id="btn">Submit</button>
<script>
document.getElementById("btn").addEventListener("click",function(){
var inputVal=document.getElementById("input").value*1;
rollDice(inputVal);
});
function rollDice(dice){
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<label>Game:</label><input type="text" id="input" value="0" />
<button id="btn">Submit</button>
<script>
document.getElementById("btn").addEventListener("click",function(){
var inputVal=document.getElementById("input").value*1;
rollDice(inputVal);
});
function rollDice(dice){
for(var i =0;i<dice;i++){
var x = Math.random()*100;
console.log(x);}
}
</script>
</body>
</html>
for(var i =0;i<dice;i++){
var x = Math.random()*100;
console.log(x);}
}
</script>**

Take the values of a text input and store them into an array

My code can be found here: https://www.w3schools.com/code/tryit.asp?filename=FHC2UOT0RQX6
The program accepts an array var array=[1,0,1,0,1,1,0,0,0] and solves the pseudoternary encoding scheme. All i want to do is simple. Insead of changing the elements of the array(when i want to insert a different input), i want to use the input text and take the values from it and when i press enter or the submit button, it will solve the problem depending on the user inputs. Is that possible to take the values of the text input and make them act as an array ?
Here is the script below but it is better to see the whole code, use the link above.
<script type="text/javascript">
var array=[1,0,1,0,1,1,0,0,0]; //input here
var text="";
for(var b=0;b<array.length;b++)
{
text+=array[b];
}
document.getElementById('enc').innerHTML=text;
pseudo(array);
function pseudo(a) //function pseudo
{
var pulse = false;
var count = 0;
for(var b=0;b<array.length;b++)
if(a[b]===1)
{
count++;
document.write('<img src="http://i.imgur.com/30DU9iC.png">');
}
else if(a[b]===0)
{
count++;
pulse=!pulse; //toggles boolean value each time it finds zero
if(pulse===true) //pulse shows up
{
document.write('<img src="http://i.imgur.com/Ghtajy7.png">');
}
else{
document.write('<img class="down" src="http://i.imgur.com/uObQjTA.png">');
}
}
}
</script>
Actually you want to write your code inside a function and call the function onload and onclick respectively. Try this, http://www.w3schools.com/code/tryit.asp?filename=FALV2XZQ7V36
var array = [1, 0, 1, 0, 1, 1, 0, 0, 0]; //input here
var text = "";
function loading() {
for (var b = 0; b < array.length; b++) {
text += array[b];
}
document.getElementById('enc').innerHTML = text;
pseudo(array);
}
function pseudo(a) //function pseudo
{
var pulse = false;
var count = 0;
var output = '';
var b = 0;
for (b = 0; b < a.length; b++)
if (a[b] === 1) {
count++;
//document.write('<p class="w3-center w3-text-red">'+'Step '+count+': No line'+'<br>'+'</p>');
//document.write('<img src="http://i.imgur.com/30DU9iC.png">');
output += '<img src="http://i.imgur.com/30DU9iC.png">';
} else if (a[b] === 0) {
count++;
pulse = !pulse; //toggles boolean value each time it finds zero
if (pulse === true) //pulse shows up
{
//document.write('<p class="w3-center w3-text-red">'+'Step: '+count+' goes up'+'<br>'+'</p>');
//document.write('<img src="http://i.imgur.com/Ghtajy7.png">');
output += '<img src="http://i.imgur.com/Ghtajy7.png">';
} else {
// document.write('<p class="w3-center w3-text-red">'+'Step: '+count+' goes down'+'<br>'+'</p>');
//document.write('<img class="down" src="http://i.imgur.com/uObQjTA.png">');
output += '<img class="down" src="http://i.imgur.com/uObQjTA.png">';
}
}
document.getElementById("js").innerHTML = output;
}
function gettext() {
var inputText = document.getElementById("tf").value;
var inparray = [inputText.length];
for (i in inputText) {
inparray[i] = parseInt(inputText[i]);
}
document.getElementById('enc').innerHTML = inputText;
pseudo(inparray);
}
body {} .pad {
padding-top: 20%;
}
.inline {
display: inline;
}
.down {
margin: 0 -2 -65 -3;
}
<html>
<head>
<title>Pseudoternary Encoding</title>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<!-- <link rel="stylesheet" href="style.css" type="text/css"/>-->
<h4>Use this input </h4>
<input type="text" id="tf"></input>
<input type="button" style="width:50px;" value="solve" onclick="gettext()" id="tf"></input>
</head>
<body onload="loading()" ;>
<h1>Illustration of pseudoternary encoding scheme </h1>
<h1 class="pad w3-center">Encode <span id="enc" class="w3-text-red"> </span></h1>
<div id="js" class="w3-center">
</div>
</body>
</html>
Note, <input> element is self-closing. <input> element should be child nodes of <body> element instead of <head> element. id of element in document should be unique. Replace duplicate "tf" id at input elements with unique values. Remove <script> element from being child node of div element. Place <script> element before closing </body> tag. Substitute concatenating .innerHTML for document.write()
Attach click event to input type="button", use String.prototype.split() with parameter "" to create an array from input type="text" .value, Array.prototype.map() with parameter Number to convert String to Number values. Assign resulting array to array variable. Set #js .innerHTML to empty string before calling function again with array as parameter.
<!DOCTYPE html>
<html>
<head>
<style>
body {}
.pad {
padding-top: 20%;
}
.inline {
display: inline;
}
.down {
margin: 0 -2 -65 -3;
}
</style>
<title>Pseudoternary Encoding</title>
<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<link rel="stylesheet" href="style.css" type="text/css" />
</head>
<body>
<h4 style="margin-top:240px;position:absolute">Use this input </h4>
<h1>Illustration of pseudoternary encoding scheme </h1>
<input type="text" style="position:relative" id="tf">
<input type="button" style="position:relative;width:50px;" value="solve" id="button">
<h1 class="pad w3-center">Encode <span id="enc" class="w3-text-red"> </span></h1>
<div id="js" class="w3-center"> </div>
<script>
var array = [1, 0, 1, 0, 1, 1, 0, 0, 0]; //input here
var text = "";
var enc = document.getElementById("enc");
var button = document.getElementById("button");
var tf = document.getElementById("tf");
var center = document.getElementById("js");
for (var b = 0; b < array.length; b++) {
text += array[b];
}
enc.innerHTML = text;
pseudo(array);
function pseudo(a) {
var pulse = false;
var count = 0;
for (var b = 0; b < array.length; b++)
if (a[b] === 1) {
count++;
center.innerHTML += '<img src="http://i.imgur.com/30DU9iC.png">';
} else if (a[b] === 0) {
count++;
pulse = !pulse; //toggles boolean value each time it finds zero
if (pulse === true) //pulse shows up
{
center.innerHTML += '<img src="http://i.imgur.com/Ghtajy7.png">';
} else {
center.innerHTML += '<img class="down" src="http://i.imgur.com/uObQjTA.png">';
}
}
}
button.onclick = function() {
array = tf.value.split("").map(Number);
enc.innerHTML = array.join("");
console.log(array, enc);
center.innerHTML = "";
pseudo(array)
}
</script>
</body>
</html>

Push value to array onclick and loop to add array values. Javascript

So i am pretty new at this and want to be able to add a dollar to the "deposit" text box every time I click the button. I'm going to have to do this with a quarter, dime, and nickel, button as well. This is what I have so far.
<input type="button" value="Dollar" id="dollar" />
$<input type="text" id="deposit" />
And the javascript is:
var $ = function (id) { return document.getElementById(id); }
var item = [];
var total = 0;
for (i=0; i < item.length; i++){
total += item[i];
$("deposit").value = total;
}
$("dollar").onclick = item.push(1);
Whatever help you can give is much appreciated!
Don't you mean
Live Demo
var $ = function (id) { return document.getElementById(id); }
var add = function(fld,val) {
return (parseFloat(fld.value)+val).toFixed(2);
}
window.onload=function() {
$("dollar").onclick=function() {
$("deposit").value = add($("deposit"),1);
}
$("dime").onclick=function() {
$("deposit").value = add($("deposit"),.1);
}
$("nickel").onclick=function() {
$("deposit").value = add($("deposit"),.05);
}
$("refund").onclick = function() {
$("deposit").value = "0.00";
}
}
Try this:
HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#1.9.1" data-semver="1.9.1" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="script.js"></script>
</head>
<body>
<input type="button" value="Dollar" id="dollar" />
$ <input type="text" id="deposit" />
</body>
</html>
JavaScript:
$(function() {
var item = [];
$("#dollar").click(function() {
item.push(1);
var total = 0;
for (var i = 0; i < item.length; i++) {
total += item[i];
$("#deposit").val(total);
}
});
});
Plunker example

Categories

Resources