How do you create a JS code that randomly spreads objects - javascript

I am making a simple code that you will have to put in the password and I would like to know how to make a code that will randomly distribute text. I have tried to use the push and pop methods.
let sumbit;
let input;
let element;
function setup() {
createCanvas(400,400);
sumbit = createButton('Submit');
sumbit.mousePressed(button);
input = createInput();
input.position(20, 60);
element = createElement('h2', 'What is the password : ');
element.position(5, 10);
textSize(32);
}
function button() {
const password = input.value();
if(password == "2010") {
element.html('Your Correct! ' + ' The password was ' + password);
} else {
element.html('Your incorrect the password was : 2010');
}
input.value('');
html, body {
margin: 0;
padding: 0;
}
canvas {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sketch</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="libraries/p5.min.js"></script>
<script src="libraries/p5.sound.min.js"></script>
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>
I would like the code to make the letters look something like this. I would appreciate some advice, Thank you in advance.

You can use:
text() to render each character
random() to pick a random position and angle (within a range)
use other text related functions to adjust the look of the characters such as textFont() to set a serif font and textSize()
Here's a basic example with comments:
let stringOfCharacters = 'The quick brown fox jumped over the lazy dog.';
let numLetters = 1000;
function setup() {
createCanvas(400, 400);
background(255);
fill(0);
// set serif font
textFont('Times New Roman');
for(let i = 0 ; i < numLetters; i++){
// pick the next character from the string above, looping from the start when the i counter is greater or equal to the number of characters in the string
let character = stringOfCharacters.charAt(i % stringOfCharacters.length);
// 50-50 change of pick a case
character = random(0.0, 1.0) > 0.5 ? character.toUpperCase() : character.toLowerCase();
// pick a random position
let randomX = random(0, width);
let randomY = random(0, height);
// pick a random size
let size = random(12, 24);
// pick a random angle (rember, by default, angles in p5 are in radians (though can be changed with angleMode(DEGREES)))
let randomAngle = random(0, TWO_PI);
// isolate the coordinate system to apply the rotation
push();
rotate(randomAngle);
textSize(size);
text(character, randomX, randomY);
pop();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.3.1/p5.min.js"></script>
Instead of the 50-50 random condition you could go for a dice roll, starting off with a rectangular grid and slightly offsetting positions (which would reduce the likelihood of intersections), or any other random method.
There a few more options in p5 you could explore for randomness such as Perlin noise() or randomGaussian() distribution

Related

Random number generator wont work with parseInt?

I've got this function that does a random number between 100 and 1 in JS and it adds it to the Score keeper, but the score keeper wont work. I even added parseInt for it to convert it from a string to an actually numbers int but it gives me NaN. But when I remove parseInt it gives me stacked numbers. Example: 50 + 100 will become 50100 not 150. Is there something wrong with the code? Here is the HTML and JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="pets.css">
</head>
<body>
<div>
<h1>Score Keeper</h1>
<button onclick="randGen()">Random Numbers</button>
<p id="paragraph"></p>
</div>
<h2 id="score"></h2>
<script src="pets.js"></script>
</body>
</html>
const scoreKeeper = document.getElementById('score');
scoreKeeper = 0;
function randGen() {
const p = document.getElementById('paragraph');
const generatedNumber = Math.floor(Math.random() * 100) + 1;
let currentNumber = parseInt(scoreKeeper.innerText) ?? 0
if (generatedNumber > 0) {
p.innerHTML = `Your number is: ${generatedNumber}`
currentNumber += generatedNumber;
scoreKeeper.innerText = currentNumber;
return scoreKeeper;
}
}
Its a simple javaScript mistake. You are overwriting const. The aspect of const is that the value can NOT be overwritten. change it to let.
Also, you get an element document.getElementById("score") but then automatically overwrite it as 0. Also also, doing parseInt(scoreKeeper.innerText) ?? 0 checks if you can parseInt the innerText rather then if the innerText exist. You should check if it exist first and then parseInt it.
let scoreKeeper = document.getElementById("score");
function randGen() {
let p = document.getElementById("paragraph");
const generatedNumber = Math.floor(Math.random() * 100) + 1;
let currentNumber = scoreKeeper.innerText
? parseInt(scoreKeeper.innerText)
: 0;
if (generatedNumber > 0) {
p.innerHTML = `Your number is: ${generatedNumber}`;
currentNumber += generatedNumber;
scoreKeeper.innerText = currentNumber;
}
}
Also, the return in this case in not needed. You do not return a value to any other function or place. You are modifying your h2 and p inner text directly from the function.
EDIT
You can make the code more readable and using less global variables by making an if check to check if the value is what you do not want and just do an empty return, and move the let scoreKeeper inside the function. Declare all other variables, besides the generatedNumber, after the check and return to only create variables and use up memory if the conditions are met.
function randGen() {
const generatedNumber = Math.floor(Math.random() * 100) + 1;
if (generatedNumber <= 0) return;
let scoreKeeper = document.getElementById("score");
let p = document.getElementById("paragraph");
let currentNumber = scoreKeeper.innerText
? parseInt(scoreKeeper.innerText)
: 0;
p.innerHTML = `Your number is: ${generatedNumber}`;
currentNumber += generatedNumber;
scoreKeeper.innerText = currentNumber;
}

Basic javascript solving quadratic equations

Very new programmer, trying to make a quadratic equation solver in javascript.
//QuadSolver, a b c as in classic ax^2 + bx + c format
function quadsolve(x, a, b, c) {
var sol = (
((a * (x * x)) + (b * x)) + c
)
}
//Test
console.log(quadsolve(1, 1, 1, 0))
In the console, it outputs "undefined". Would this be the correct way to go about solving the problem? If so, how would I get a value instead of undefined? Thanks!
Like the others said you need to use the "return" keyword to return a value. Are you trying to find the zeros of the equation? If so here is the numeric solution:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script id="MathJax-script" async
src="https://cdn.jsdelivr.net/npm/mathjax#3/es5/tex-mml-chtml.js">
</script>
</head>
<body>
<h2>Quadratic Equation</h2>
<p>This is an example of the numerical solution of a quadratic equation using Ceres.js</p>
<p>
Problem Statment: find x when \(f(x)=0\)
\[f(x) = a*x^2+b*x+c\]
</p>
<textarea id="demo" rows="40" cols="170">
</textarea>
<script type="module">
import {Ceres} from 'https://cdn.jsdelivr.net/gh/Pterodactylus/Ceres.js#master/Ceres-v1.5.3.js'
var fn1 = function(x){
let a = 1
let b = -1
let c = 1
return a*x[0]*x[0]+b*x[0]+c //this equation is of the form f(x) = 0
}
let solver = new Ceres()
solver.add_function(fn1) //Add the first equation to the solver.
solver.promise.then(function(result) {
var x_guess = [1] //Guess the initial values of the solution.
var s = solver.solve(x_guess) //Solve the equation
var x = s.x //assign the calculated solution array to the variable x
document.getElementById("demo").value = "The solution is x="+x+"\n\n"+s.report //Print solver report
solver.remove() //required to free the memory in C++
})
</script>
</body>
</html>

show random number < 0.8 not working properly

Hi I'm kinda new on JS so I tried to do this, I made this to test the random function and I want to show only random numbers below 0.8, but sometimes it shows above 0.8 also more than one time in a row, how do I fix it ?
This is my first post ever here, so sorry if I did something wrong.
Thanks. :)
function rn() {
var a = Math.random()
return a
}
function writerandon() {
var x = 0
while (x < 100) {
if (rn() < 0.8) {
document.write(rn() + "<br>")
}
if (rn() > 0.8) {
x = 100
}
x++
}
}
//
document.getElementById("11").innerHTML = writerandon()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>exp</title>
</head>
<body id="bd">
<h1 id="11"></h1>
</body>
<script src="exp.js"></script>
</html>
Your code makes two random number calls, each of which may have a different value. The fix is to use else to ensure only one branch fires:
let n = Math.random();
if (n < 0.8) {
document.write(n + "<br>")
}
else {
x = 100
}
Just because you've wrapped Math.random() in a function doesn't mean it fires only once. Each and every call to rn() will return a new value. The local variable a is initialized anew with each function call. It does not persist between calls.
In your original code around 16% of the time (80% x 20%) you'd fluke out and trigger both branches.
Assign the return value to a variable in order to hold the same value over different conditions.
function rn() {
var a = Math.random()
return a
}
function writerandon() {
var x = 0
while (x < 100) {
const randomNumber = rn();
if (randomNumber < 0.8) {
document.write(randomNumber + "<br>")
}
if (randomNumber > 0.8) {
x = 100
}
x++
}
}
//
document.getElementById("11").innerHTML = writerandon()
The problem is that you're calling rn() multiple, and it returns different numbers each time. The result you test in if is not the same one that you display with document.write(), or the one that you test in the second if.
You need to save the number to a variable so you can test and display the same number.
Also, use else when you want to do something when the previous test failed.
function rn() {
var a = Math.random()
return a
}
function writerandon() {
var x = 0
while (x < 100) {
var num = rn();
if (num < 0.8) {
document.getElementById("bd").innerHTML += (num + "<br>")
} else {
break;
}
x++
}
}
//
document.getElementById("11").innerHTML = writerandon()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>exp</title>
</head>
<body id="bd">
<h1 id="11"></h1>
</body>
<script src="exp.js"></script>
</html>

How to generate set of arrays when clicking button, without disappearing the first one?

Im trying to learn js. Im starting playing with array by generating 6 combination numbers. This is working but i dont know how to output another combinations when I click the button. Any comment is appreciated. THanks
function getRandomNumber() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
var arr = [];
while(arr.length < 8){
var myrandomnumber = Math.floor(Math.random(x) * y + 1);
if(arr.indexOf(myrandomnumber) === -1) arr.push(myrandomnumber);
}
if (x==""){
alert("Please enter a number");
}
else if (y==""){
alert("Please enter a number");
}
else{
document.getElementById("ok").innerHTML = arr;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>RANDOM NUMBER JS</title>
<meta name="" content="">
<link rel="stylesheet" href="css/css/bootstrap.css">
<link rel="stylesheet" href="css/cssextra/csse1.css">
<script src="customscript.js"></script>
</head>
<body class="bg-light">
<br>
<p id="demo">Random Number</p>
<br><br>
<input type="number" id="num1" name="one"/ >
<input type="number" id="num2" name="two"/ >
<button onclick="getRandomNumber();">Generate random number</button >
<p id="ok"></p><br>
<p id="okok"></p>
</body>
</html>
Accumulate results
A easy yet crude solution would be appending the current text with <br> for line breaks:
const p = document.getElementById("ok");
p.innerHTML = p.innerHTML + (p.innerHTML === "" ? "" : "<br>") + arr.join(", ");
But this approach will notoriously perform badly as the text grows larger.
If you change the p elements into:
<div id="ok" class="text-container">
And replace the script's document.getElementById("ok").innerHTML = arr; into:
const p = document.createElement("p");
p.textContent = arr.join(", ");
document.getElementById("ok").appendChild(p);
And add css:
.text-container {
margin-top: 1em;
}
.text-container > p {
margin: 0;
}
Then you should have something working.
Also there are some things to address:
Math.random()
The function Math.random() does not take arguments, so your variable x does not have any effect.
If the intention is to x and y as a minimum and maximum value, try this from Math.random() - JavaScript | MDN:
function getRandomInt(min, max) {
var min = Math.ceil(min);
var max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
The min is inclusive and the max is exclusive. If x = 0 and y = 10, and you want the range to be [0-10], you can do getRandomInt(x, y + 1).
Make sure min is not greater than max.
Prevent infinite loop
Your loop will get stuck if the amount of possible unique integers is smaller than the number of array elements required for it to end.
More user input semantics
Variables x and y are tested before writing out the numbers, but after they have already been used to generate the numbers. In other words, the number creation process should be moved into the else block.
innerHTML expects a string and you are setting the array.
use document.getElementById("ok").innerHTML = arr.join(' ');
this will concatenate each element in the array with a space as glue

Request for help: setting up a grid using nested if loops (JavaScript)

I was having some difficulties setting up a grid using nested if statements. It's a relatively simple task but I seem to be stuck!
This is a school assignment. The instructions are below:
"If the user enters 8 in the text input and clicks the button, you should draw eight rows and columns of little squares. To do this, you will need two for loops nested inside each other like this:
for ( row=1; ... ) {
for ( col=1; ... ) {
...
}
}
In the (inner-most) loop body, draw a little square on the paper with an x and y value calculated from the loop counters so the squares end up in a grid pattern.
Your page will look something like this (depending on the number the user enters, obviously). Don't worry about the coloured boxes yet: that is the next part."
The outcome should look something like this:
image
You can ignore the fact that some of squares are colored. So far I'm come up with this:
generate = function() {
n = 0
x = 0
y = 0
n = $('#squares').val()
for (row = 1; row <= n; row += 1) {
for (col = 1; col <= n; col += 1) {
r = paper.rect(x, y, 10,10)
x = x + 20
}
y = y + 20
}
}
setup = function() {
paper = Raphael('container', 400, 400)
$('#number').click(generate)
}
jQuery(document).ready(setup)
Thank you in advance!
The starting value for the rows and column in the for loops can be set with the start variable 0 and the condition check row < n.
Here is an example using javascript and canvas without an external library.
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<label>Grid size:</label>
<input type="number" name="go" type="text" name="" id="">
<button class="button">go</button>
<canvas id="canvas" width="400" height="400"></canvas>
</body>
</html>
js:
var c = document.getElementById("canvas");
var ctx = c.getContext("2d");
document.getElementsByClassName('button')[0].onclick = function() {
var value = document.querySelector('input[name="go"]').value;
ctx.clearRect(0, 0, canvas.width, canvas.height);
var space = 400 / (value);
for (row = 0; row < value; row += 1) {
for (col = 0; col < value; col += 1) {
ctx.fillRect(row * space, col * space, space - 10, space - 10)
}
}
}

Categories

Resources