Random Testomonial Selection JS - javascript

I am working on randomising reviews/testomonials in a website i'm working on.
I am using JS to randomise the testomonials that are on the index page onLoad. In my code, I am using an array to store the testomonials and then when the page loads I want it to just randomly select 3 reviews from the array and write them to "review-1", "review-2" and "review-3" respectively.
The issue I am having with my code is that idk the best way to select 3 different reviews without it repeating the same one twice.
var reviews = [
"Thank you Anne for fitting me in yesterday when you realised I was desperate to get the house cleaned before the blinds and curtains were fitted. Marie and Michaela did a great job, leaving it sparkling clean. I will certainly recommend you to anyone who needs a cleaner. That you are so approachable, helpful and friendly is a bonus. - <strong>Rosemary OBoyle</strong>",
"Great job on all the awkward hate to do Jobs! Came home from my holidays and my house was sparkling, highly recommended!! - <strong>Lynne Gardiner</strong>",
"Domestic Angels are angels to me, just left lovely Kelly cleaning my house in preparation for mums arrival, while I chill at hairdressers, thank you to Anne & her team, can\'t recommend them enough - <strong>Julie Magee</strong>"
]
var max = reviews.length;
var id1;
var id2;
var id3;
function getRandomReview(max) {
id1 = Math.floor(Math.random() * Math.floor(max));
id2 = Math.floor(Math.random() * Math.Floor(max));
id3 = Math.floor(Math.random() * Math.Floor(max));
}
function randomJS() {
getRandomReview(max);
document.getElementById("review-1").innerHTML = id1;
document.getElementById("review-2").innerHTML = id2;
document.getElementById("review-3").innerHTML = id3;
}
Any advice and help would be appreciated. Thanks in advance

Thanks!
Just shuffled it and it's working! :)
var reviews = [
"Thank you Anne for fitting me in yesterday when you realised I was desperate to get the house cleaned before the blinds and curtains were fitted. Marie and Michaela did a great job, leaving it sparkling clean. I will certainly recommend you to anyone who needs a cleaner. That you are so approachable, helpful and friendly is a bonus. - <strong>Rosemary OBoyle</strong>",
"Great job on all the awkward hate to do Jobs! Came home from my holidays and my house was sparkling, highly recommended!! - <strong>Lynne Gardiner</strong>",
"Domestic Angels are angels to me, just left lovely Kelly cleaning my house in preparation for mums arrival, while I chill at hairdressers, thank you to Anne & her team, can\'t recommend them enough - <strong>Julie Magee</strong>",
]
var max = reviews.length;
var id1;
var id2;
var id3;
function shuffle(reviews) {
reviews.sort(() => Math.random() - 0.5);
}
function randomJS() {
shuffle(reviews);
document.getElementById("review-1").innerHTML = reviews[0];
document.getElementById("review-2").innerHTML = reviews[1];
document.getElementById("review-3").innerHTML = reviews[2];
}

Related

Balance Chemistry Equations

Lore:
Now that my chemistry class has gone past memorizing equations and whatnot and begun with, example, balancing chemical equations. I could sit down all day long balancing equations, but as programming is my passion I would love to get a program working for me to solve these. This is more or less a pet-project and more for fun rather than giving me an edge in chemistry class. But the more I dwelt into it the more complex it became.
I don't really know how to begin this crusade and have instead worked on the parser and data set, which is in pretty good set to have my head wrapped around it right.
Question:
What I don't know is how to utilize matrices to solve equations (balance equations to conserve mass*) and convert that into whole numbers valid in chemistry.
Code/objects:
class Element {
constructor(name,quantity) {
this.name = name;
this.quantity = quantity;
if (this.quantity == 0) {
this.quantity = 1;
}
}
}
class Molecule {
constructor() {
this.elements = [];
this.multiplier = 1;
}
addElement(newEl) {
this.elements.push(newEl);
}
list() {
this.elements.forEach(el => {
console.log(el.name,el.quantity);
});
}
getMultiplier() {
return this.multiplier;
}
getElements() {
var a = [];
this.elements.forEach(el => {
a.push([el.name,el.quantity*this.multiplier]);
});
return a;
}
}
Code/data structure:
printFormula(moleculeList);
for (var i=0;i<moleculeList[0].length;i++) {
console.log("Mol "+(i+1))
moleculeList[0][i].list();
}
console.log("==>");
for (var i=0;i<moleculeList[1].length;i++) {
console.log("Mol "+(i+1))
moleculeList[1][i].list();
}
Code/output:
'C6H14 + O2 ==> CO2 + H2O'
Mol 1
C 6
H 14
Mol 2
O 2
==>
Mol 1
C 1
O 2
Mol 2
H 2
O 1
I am a chemist and have exactly zero familiarity with Javascript so as to explain it in detail. But the method is fairly simple to show by hand. This link nails it down in a clean manner.
The only reason why I am linking to it without going through the steps in detail is because Stackoverflow does not have LaTeX math in order to make the text easy to follow, so I think you'll benefit better from the text in the link.
Also, I don't think this is a full answer, but I do not have enough reputation to put this on a comment, where it belongs.
I think the hardest bit is finding/coding the appropriate subroutine for row-echelon reduction of the matrix in step-5. But I also believe that there is a vast number of algorithms appropriate for doing that which you can find in the internet. Very handily, this very website has a question related to just that with a python code to sweeten the deal.
I hope this helps you at least wrap your head around it enough to implement the code you need.
Cheers

javascript, getting a random number result in each singular array

I'm not sure how to word the question and i'm still quite new at javascript.
So I've got a random quote generator that has each quote result as an array. I'd like to add in two items in the array which I've got so far but having one result be a random number generated eg "2 quote" but having 2 be randomised each time. The end result is for a browser based text game. So it could be "2 zombies attack" or "7 zombies attack." The code I have so far is:
var quotes = [
[x, 'Zombies attack!'],
[x, 'other creatures attack'],
['next line'],
]
function newQuote() {
var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quote').innerHTML = quotes[randomNumber];
}
Ideally need x(or i however it's going to work) to be the result of a random number between a set range, each differently each array.
Thank you
p.s I forgot to mention that not all the quotes require a number. Thats why I've done it as a double array.
If I understand your goal correctly, you want to have a set of similar-ish message templates, pick one of them at some point and fill it with data, correct? There's a lot of ways to tackle this problem, depending on how varying can your templates be. For a simple case in my head where you just need to prepend a number to a string I'd do something like this:
var messages = [" zombies attack",
" other creatures attack"], // define your messages
messageIndex = Math.floor(Math.random() * messages.length), // pick one of them
numberOfMonsters = Math.floor(Math.random() * 10 + 1), // get your random number
result = numberOfMonsters + messages[messageIndex]; // construct a resulting message
document.getElementById('quote').textContent = result;
If you'd rather have more complex strings where you don't necessarily add a number (or any string) to the beginning, like ["There's X things in the distance", "X things are somewhere close"], then I'd recommend to either come up with some sort of string formatting of your own or use a library to do that for you. sprintf.js seems to be just right for that, it will let you do things like this:
var messages = ["%d zombies attack",
"A boss with %d minions attacks"], // define your messages
messageIndex = Math.floor(Math.random() * messages.length), // pick one of them
numberOfMonsters = Math.floor(Math.random() * 10 + 1), // get your random number
result = sprintf(messages[messageIndex], numberOfMonsters) // format a final message
document.getElementById('quote').textContent = result;
EDIT: Your task is much more complex than what is described in the original question. You need to think about you code and data organization. You have to outline what is finite and can be enumerated (types of actions are finite: you can loot, fight, move, etc.), and what is arbitrary and dynamic (list of monsters and loot table are arbitrary, you have no idea what type and amount of monsters game designers will come up with). After you've defined your structure you can come up with some quick and dirty message composer, which takes arbitrary entities and puts them into finite amount of contexts, or something. Again, I'm sort of shooting in the dark here, but here's an updated version of the code on plunkr.
I solved it to do what I want and still have the numbers different. The issue was I should have had the number generator within the quote function. Also can create multiple variables to use too for different number generators. The plan is to then integrate it with php to add content dynamically. Which I can do. Thanks Dmitry for guiding me in the right direction.
function newQuote() {
var MonsterOne = Math.floor((Math.random() * 14) + 0);
var MonsterTwo = Math.floor((Math.random() * 14) + 0);
var MonsterThree = Math.floor((Math.random() * 14) + 0);
var MonsterFour = Math.floor((Math.random() * 14) + 0);
var quotes = [
['Test', MonsterOne, 'One'],
['Test', MonsterOne,'Two'],
['Test', MonsterThree, 'Three'],
[MonsterFour, 'Four'],
['Five'],
]
var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quote').innerHTML = quotes[randomNumber];
}

Break up a string in JS

I have a script built to grab a quote from an array at random, and display it.
I'm trying to format it so it would split the quote and the author like so:
"Insert quote"
Name of person saying Quote
I've tried using split with \n and <br /> and nothing works, even in an alert.
here is my code:
//Initalize the array
var quotes = [];
//Insert data into the array
quotes[0] = "It doesn't matter how many times you have failed, you only have to be right once." + "Mark Cuban";
quotes[1] = "Video games are bad for you? That's what they said about rock n' roll." + "Shigeru Miyamoto";
quotes[2] = "I'd like to be known as the person who saw things from a different point of view to others." + "Shigeru Miyamoto";
quotes[3] = "Stay hungry, stay foolish, stay crazy." + "Steve Jobs";
quotes[4] = "The future was uncertain, absolutely, and there were many hurdles, twists, and turns to come, but as long as I kept moving forward, one foot in front of the other, the voices of fear and shame, the messages from those who wanted me to believe that I wasn't good enough, would be stilled." + "Chris Gardner";
quotes[5] = "Running a start-up is like eating glass. You just start to like the taste of your own blood." + "Sean Parker";
quotes[6] = "I used to drink cristal, the muh'fucker's racist. So I switched gold bottles on to that Spade shit" + "Shawn Carter (Jay Z)";
quotes[7] = "I think it's better to let my work do the talking" + "Shigeru Miyamoto.";
quotes[8] = "Success is a lousy teacher. It seduces smart people into thinking they can't lose." + "Bill Gates";
quotes[9] = "We need to reengineer companies to focus on figuring out who the customer is, what's the market and what kind of product you should build." + "Eric Ries";
quotes[10] = "I have no friends and no enemies - only competitors." + "Aristole Onassis";
quotes[11] = "Working 24 hours a day isn't enough anymore. You have to be willing to sacrifice everything to be successful, including your personal life, your family life, maybe more. If people think it's any less, they're wrong, and they will fail." + "Kevin O'Leary";
quotes[12] = "My hope is to the see the benefits of my labour spread out in the community." + "W. Brett Wilson";
quotes[13] = "I'm not here to make friends; I'm here to make money." + "Kevin O'Leary";
quotes[14] = "Good artists copy, great artists steal" + "Pablo Picasso";
quotes[15] = "Welcome ladies and gentlemen to the eighth wonder of the world. The flow of the century, always timeless; HOV!" + "Shawn Carter (Jay Z)";
quotes[16] = "Today’s “best practices” lead to dead ends; the best paths are new and untried." + "Peter Thiel";
quotes[17] = "I believe life is an intelligent thing: that things aren't random." + "Steve Jobs";
quotes[18] = "Pretty? You mean like rainbows, unicorns, and sparkles?" + "Michelle Brown";
quotes[19] = ".....and for that reason, I'm OUT!" + "Mark Cuban";
//Splits the quote into two pieces, the quote and the person.
var quoteSplit = function (quotes) {
var split = quotes.split("+").replace("\n");
}
//Displays a quote from the array at random.
var displayQuote = quotes[Math.floor(20 * Math.random())];
document.write(displayQuote);
//END
When you're building your array, you are concatenating the quote with the author. So this:
quotes[0] = "It doesn't matter how many times you have failed, you only have to be right once." + "Mark Cuban";
Ends up with this string being set to quotes[0]
It doesn't matter how many times you have failed, you only have to be right once.Mark Cuban
And your split statement will not work, because the + is not included in the string. This isn't a great way of setting up your array, though. What happens if your quote contains the + symbol, for example?
A better way would be to create an object for each item:
quotes[0] = {
text: "It doesn't matter how many times you have failed, you only have to be right once.",
author: "Mark Cuban"
}
Then you can do:
var displayQuote = quotes[Math.floor(20 * Math.random())];
document.write(displayQuote.text + '<br>' + displayQuote.author);
It's seems that + sign is not in your string. The following code:
console.log("Today’s “best practices” lead to dead ends; the best paths are new and untried." + "Peter Thiel");
will return to you string
Today’s “best practices” lead to dead ends; the best paths are new and untried.Peter Thiel;
So, you just have to include + sig in your strings like that:
"Today’s “best practices” lead to dead ends; the best paths are new and untried.+Peter Thiel"
As Daniel A. White said in the comments section. You are considering + to be part of the string but you are in fact concatenating 2 strings on each index.
quotes[3] = "Stay hungry, stay foolish, stay crazy." + "Steve Jobs";
should be:
quotes[3] = "Stay hungry, stay foolish, stay crazy.+Steve Jobs";
Or you could use regex ( Unfortunately I can't provide a regex example right now ) but those are two of your possible options.
If you output any element of your array, you'll see that each entry is a single string with quote and person. Ex.
console.log(quotes[3]);
Stay hungry, stay foolish, stay crazy.Steve Jobs
That's because + concatenates when applied to strings.
As suggested in the comments, you could use split on punctuation marks, although that would break some of your quotes.
You could do something like
quotes[3]=["Stay hungry, stay foolish, stay crazy.","Steve Jobs"];
and output each element separately.
Try this:
var quotes = {
1: {
quote: 'Hello world.',
author: 'Test test'
},
2: {
quote: 'Hello world 2.',
author: 'Test test 2'
},
};
// Display random quote
function displayQuote(){
var key = Math.floor(Math.random() * Object.keys(quotes).length + 1);
return quotes[key].quote + ' ' + quotes[key].author;
};
document.write(displayQuote());

Function ordering properly working?

I am new to HTML/CSS/JS and not understanding properly or am missing something completely. I am trying to update the Variable of "CitizenCost" by using Math.pow(2, NumCitizens) that part is working. The part that I am having trouble with is updating CitizenCost to the correct number and having the HTML represent it with the correct number. Right now it updates but it's always behind
IE: it should be X = 2^1 then X = 2^2 So on and so forth
However in the HTML it doesn't update accordingly it is always behind one equation so if the real cost is X = 2^2. The text will show X = 2^1. Unless the Player clicks the button again.
function buycitizen(){
CitizenCost = Math.pow(2, NumCitizens);
document.getElementById("CitizenCost").innerHTML = "Cost of Citizen " + CitizenCost;
if(land >= CitizenCost){
land = land - CitizenCost;
eps = eps + 2;
NumCitizens++;
document.getElementById("NumCitizens").innerHTML = NumCitizens;
}
else
document.getElementById("SystemMessage").innerHTML = "You do not have enough Land Resources to provide for more Citizens right now!";
setTimeout(systemclear, 5000)}
Here is a fiddle demonstrating the issue
https://jsfiddle.net/Traberjkt/yaq0rbad/
Here is the Git
https://github.com/Traberjkt/Conquest
I have tried setting a timer so the text of CitizenCost updates every second. I have thought and tried putting the cost equation in a separate function and re-locating it somewhere else in the function. Sadly I have had no luck figuring this out. Any help or pointing me in the right direction would be greatly appreciated!
Maybe you should make a new function called moreCitizens(howMany):
function moreCitizens(howMany) {
NumCitizens += howMany;
document.getElementById("NumCitizens").innerHTML = NumCitizens;
CitizenCost = Math.pow(2, NumCitizens);
document.getElementById("CitizenCost").innerHTML = "Cost of Citizen " + CitizenCost;
}
Then instead of
NumCitizens++;
you can just write
moreCitizens(1);
and that will update the cost and count fields.

Two sliders which are connected to give other values

Trying to create a loan calculator based on two sliders. I feel I'm nearly there but the syntax is letting me down plus one last formula.
I have two sliders, one which represents the loan amount, the other represents the loan length.
Here is a bit of the code to highlight all the calculations. I think there are errors here too.
function update() {
$amount = $("#slider1").slider("values", 100);
$interest = $amount / 100 * 15 ;
$perday = 15 ;
$apr = (($interest / $amount) / ("#slider2"/365) * 10000) / 100;
$amount2 = $amount + $interest;
$("#amount").val($amount1);
$("#amount2").val($amount2);
$("#amount3").val($interest);
}
Interest is charged at 15% of the amount borrowed.
Each day is worth 15p so in order to get my final charge.
[15% of the loan amount total]
– [0.15p per day credit]
I have developed a fiddle but its not correct, hence why I'm here.
Fiddle Here
How can I get both the sliders to work together so that if I move the top or bottom slider, it will affect the overall loan amount and Interest?
Any help will be most appreciated. I'm really struggling with this one.
I believe this is what you want - jsfiddle <- follow link
function update() {
$interest = 0.15 ;
$perday = 15 ;
$amount1 = $("#amount").val();
$dayscount = $("#days").val();
$amount2 = parseInt($amount1) + $interest * parseInt($amount1) + (parseInt($dayscount) * ($perday/100));
$("#amount2").val($amount2);
$("#amount3").val(parseFloat($amount2-$amount1).toFixed(2));
}
Fixed your update algorithm and your slider handlers
I considered that you last 2 fields (Your Loan & Interest) are the final value to be paid and the difference between the value to be paid and the value borrowed respectively. If this interpretation is not what you intended please comment.
UPDATE 1
Here I updated the jsfiddle. Beware that I don't know what the APR is, so validate that my calculation are right. I also did not use any rounding, cause I don't know if you need it like this
UPDATE 2
Updated with new formula here. I still have no idea if this is right or not
If i understood you right, you could do something like this:
function update() {
var interest = 0.15;
var sliderAmount = parseFloat($("#slider1").slider("option", "value"));
var days = parseFloat($("#slider2").slider("option", "value"));
var perday = 15 * days ;
var interestAmount = sliderAmount * interest * days;
$("#amount1").val(sliderAmount);
$("#amount2").val(sliderAmount);
$("#amount3").val(interestAmount+ perday);
}

Categories