How to generate random number and print shiny if equals - javascript

I am learning to code and I am currently stuck on JavaScript object methods. I am trying to write a code to print 'shiny' if the random number generates = 5. How can I achieve that? Also, is it printing undefined which I do not know where it is coming from. Thank you for reading.
const pokemonGoCommunityDay = {
wildEncounters: ['machop','roselia','swablu','gible','snivy','fletchling'],
currentEncounter() {
while (this.currentEncounter) {
this.currentEncounter = this.wildEncounters[Math.floor(Math.random() * 6)];
console.log(this.currentEncounter);
if (/* How to make it generate a certain number and if =5 log shiny*/ === 5){
console.log('Shiny!');
}break;
}
}
}
console.log(pokemonGoCommunityDay.currentEncounter());

You already had the necessary piece in your code :)
Here's how you can do it:
if (Math.floor(Math.random() * 6)==5){
console.log('Shiny!');
}

Related

When trying to call a function in JavaScript I get the error: Cannot read properties of undefined (reading 'target')

I posted earlier but I'm stuck again. I'm a beginner so excuse my ignorance please and if I explain some things a bit weird. I tried to give as much information as possible though.
Goal: I've written a bunch of calculations that all needs to come together and calculate the cost of a solar power system
Expected result: The system cost field needs to get a value based on the existing calculations
Actual results: System Cost shows 0. Also, some of the other values that should feed into the Sytem Cost number is showing 0 as well in console.
Error messages: Cannot read properties of undefined (reading 'target')
What I've tried: I think it's a scoping problem because when I moved some of the other calculations into functions with other calculations I get the right values on the console for those values. But when I do that the function that calculates system cost can't read those values because now they are in other functions (I'll give example shortly)
I think the variables that are needed are globally declared but that didn't fix it. I've also tried to call the function but then I get this error: Cannot read properties of undefined (reading 'target'). At the moment I have that with no parameters but I have tried with the parameters that is in the function declaration as well as using the variable I want to get out of the function but got similar errors.
Here's a section of the html:
Approximate percentage of monthly bill you
would like to save:
<input
type="text"
min="1"
max="100"
value="0"
step="1"
onchange="CalcKwhSavings(event)"
style="width:400px;"
id="inputSaveOnBill"
/>
<h2>Required Kwh Savings Per Month <span id="outputKwhSavings"></span></h2>
Here's the variables and function I'm using to get the result:
let outputKwhSavings = document.getElementById('outputKwhSavings');
let inputSaveOnBill = document.getElementById('inputSaveOnBill');
var reqKwhSavingsPerMonth = 0;
function CalcKwhSavings(event) {
inputSaveOnBill = event.target.value;
inputSaveOnBill.innerHTML = inputSaveOnBill ;
reqKwhSavingsPerMonth = Math.round ((inputSaveOnBill * .01)* monthlyBillToKwhConversion);
outputKwhSavings.innerHTML = reqKwhSavingsPerMonth;
console.log("reqKwhSavingsPerMonth:" + reqKwhSavingsPerMonth);
}
Here's some other variables that are dependent on the values in the above function (These function are showing 0 in the console which they shouldn't be doing):
let numberOfPanels = Math.round (reqKwhSavingsPerMonth / kwhPerPanelPerMonth);
console.log("numberOfPanels:" + numberOfPanels);
let sizeOfPanelArray = Math.round (numberOfPanels * panelPeakPower / 1000);
console.log("sizeOfPanelArray:" + sizeOfPanelArray);
And here's the function that needs the above variables (amongst others) to get to the the system cost result (I'm also not sure whether the below is written correctly to get the values from the radio buttons but I thought I'd start with trying to resolve the scoping problem):
function calcSystemCost(event) {
let singlePhase = document.getElementById("singlePhase").value;
let threePhase = document.getElementById("threePhase").value;
let systemCost = 0;
let phase = 0;
if ([phase.singlePhase].checked == true) {
if (sizeOfPanelArray > 6.5) {systemCost = Math.round ((singlePhaseBaseCost + eightKwSinglePhaseInverter) + (numberOfPanels * panelCost) + (numberOfBatteries * batteryCost))
}
else if (sizeOfPanelArray < 6.5) {
systemCost = Math.round ((singlePhaseBaseCost + fiveKwSinglePhaseInverter) + (numberOfPanels * panelCost) + (numberOfBatteries * batteryCost))
}
console.log("System cost:" + systemCost);
}
else if ([phase.threePhase].checked == true) {
systemCost = Math.round ((threePhaseBaseCost + twelveKwThreePhaseInverter) + (numberOfPanels * panelCost) + (numberOfBatteries * batteryCost))
console.log("sytemCost:" + systemCost);
}
outputSystemCost.innerHTML = systemCost;
}
And here's the codepen with everything in
Any help would be very much appreciated. I've watched so many videos and read on so many places on how to handle scoping but I'm not getting anything to work.

How do I change a single quote of an array.element (that is inside an object) into a double quote without creating a new array?

I was told to try and use a certain code for one of the problems I solved a while ago. I'm trying to figure it out but am coming up with nada.
Using replace(), map() etc..
This is all supposed to be done using replit and not changing the whole array as part of the 'For Fun' challenge.
const products = [
{
priceInCents: 3995,
},
{
priceInCents: 2500,
},
{
priceInCents: 8900,
},
{
priceInCents: 12500,
},
];
/* Now trying to use:
products[i].priceInDollars = $${(products[i].priceInCents * .01).toFixed(2)}
*/
/*
New
Code
*/
function addPriceInDollarsKeyToProducts(pricey)
{ for (let i = 0; i < products.length; i++)
{ for (let product = products[i];
product.priceInDollars = `$${(product.priceInCents * .01).toFixed(2)}`; )
break;
}
}
addPriceInDollarsKeyToProducts();
console.log(products)
Running this snippet btw makes it seem like it's okay.
For example: I want products[0].priceInDollars to be "$39.95",
but instead I get '$39.95',
Snippet runs it as "$39.95"
I'm not supposed to recreate the whole entire array.
If the code doesn't match the double quote requirements I get TypeError: Cannot read property '0' of undefined
edited for clarification purposes
Alright, a friend caught the problem.
I never reinserted my return like a dumb dumb.
Here I was going crazy trying to make a '"$39.95"' into a "$39.95" via replace(), map(), creating a replace function and what not when it was simply that I needed to add
return products;
at the end between the ending }

Bigquery javascript UDF with array

I'm trying to run below query in bigquery using standard SQL and javascript UDF. The query takes forever to run, thus I'm not even able to verify if the function is working or not. Can you please let me know if there is anything wrong with the query that makes it run forever? I tried to change the function call
from IRRCalc(Array<FLOAT64> [cash_flow], ARRAY<INT64> [date_delta]) as IRR to IRRCalc(array(select cash_flow from input),array(select date_delta from input)) as IRR and it resolved the issue. Though I don't understand what's wrong with IRRCalc(Array<FLOAT64> [cash_flow], ARRAY<INT64> [date_delta]) as IRR. Can someone please have a look and shed some light? Many thanks.
Here's the query:
CREATE TEMPORARY FUNCTION IRRCalc(cash_flow ARRAY<FLOAT64>, date_delta ARRAY<INT64>)
RETURNS FLOAT64
LANGUAGE js AS """
min = 0.0;
max = 1.0;
do {
guess = (min + max) / 2;
NPV = 0.0;
for (var j=0; j<cash_flow.length; j++){
NPV += cash_flow[j]/Math.pow((1+guess),date_delta[j]/365);
}
if (NPV > 0){
min = guess;
}
else {
max = guess;
}
} while (Math.abs(NPV) > 0.00000001);
return guess * 100;
""";
WITH Input AS
(
select
cash_flow_date,
date_diff(cash_flow_date, min(cash_flow_date) over (),day) as date_delta,
cash_flow as cash_flow
from cash_flow_table
)
SELECT
cash_flow,
date_delta,
IRRCalc(Array<FLOAT64> [cash_flow], ARRAY<INT64> [date_delta]) as IRR
FROM Input;
And here's the table containing the raw data:
Row cash_flow_date date_delta cash_flow
1 2017-09-08 0 -159951.78265102694
2 2017-09-08 0 -9.272567110204461
3 2017-09-08 0 -1000.0
4 2017-09-08 0 -159951.78265102694
5 2017-09-27 19 3552.8711640094157
6 2017-09-27 19 -544.122218768042
7 2018-03-28 201 -576.4290755116443
8 2018-03-28 201 3763.8202775817454
9 2018-04-02 206 437225.5536144294
Can someone please have a look and shed some light?
to see the difference - just run your SELECT w/o UDF
SELECT
cash_flow,
date_delta,
ARRAY<FLOAT64> [cash_flow],
ARRAY<INT64> [date_delta]
FROM Input
As you can see here - for each row you create array with just one element in it - so actually two arrays with one element in each - that element that respectively belong to same row
when you do ARRAY(SELECT cash_flow FROM input), ARRAY(SELECT date_delta FROM input) you actually create arrays which with respective elements from all rows
finally - when you pass ARRAY with just one element in it - it looks like your while (Math.abs(NPV) > 0.00000001) always true thus loop runs forever
Something along these lines I think
Note: above answers your exact question - but you still most likely have issue with logic - if so - ask new specific question

Checking an input against a specific array string

I am trying to create a quiz that randomly selects a question from pool of questions in an array, which is answered in an input box that is to be checked against the corresponding answer string in the array. I used math.floor(math.random() *); to get my random number. The random number is intended to be used to find both the question and answer, which are arranged in order to correspond to one another, e.g. ['question1','question2'] and ['answer1','answer2'].
I am having difficulty with trying to get my input to properly be checked against the corresponding answer value from the array. I am fairly novice at Javascript, so I am not sure as to how to do this. I tried using the document.getElementById command to compare the two. I suspect it has something to do with the fact that ansNum doesn't get the value of questNum because of the fact that questNum is only given its value inside the generateQuiz function. (I realize ansNum is likely redundant, but I was just playing around to see if anything would happen)
Javascript:
const questions = ['What do young Roman males wear?','Who is the Roman god of the smith?','Who is the 6th king of Rome?'];
const answers = ['toga praetexta','vulcan','servius tullius'];
function getQuestNum() {
questNum = Math.floor(Math.random() * 3);
};
function getAnsNum() {
ansNum = questNum();
}
function generateQuiz() {
getQuestNum();
document.getElementById("question").innerHTML = questions[questNum];
};
function checkCorrect() {
getAnsNum();
if (answer[ansNum] = document.getElementById("input").innerHTML) {
document.getElementById("verification").innerHTML = "Correct!";
}
};
Codepen Link
An image of the code
Based on your code, I fixed it with some changes. It is not the best way to do this i think. I posted the js part here.
const questions = ['What do young Roman males wear?','Who is the Roman god of the smith?','Who is the 6th king of Rome?'];
const answers = ['toga praetexta','vulcan','servius tullius'];
var questNum;
function getQuestNum() {
questNum = Math.floor(Math.random() * 3);
};
function getAnsNum() {
ansNum = questNum;
}
function generateQuiz() {
getQuestNum();
document.getElementById("question").innerHTML = questions[questNum];
};
function checkCorrect() {
getAnsNum();
if (answers[ansNum] = document.getElementById("input").value) {
document.getElementById("verification").innerHTML = "Correct!";
}
};
First you need a global variable questNum then you can use it in all of your functions.
The function getAnsNum() is redundant, at least i think so, just use questNum in your checkCorrect() function.
For getElementByID function, insert an ID attribute to your input
<input id="input" type="text" name="input">
For input, if you want to take the value of the input field, use document.getElementById("input").value instead of innerHTML.
If you not sure about any result, console.log it or use Chrome dev debug tool to check the result. In the checkCorrect function, your array name should be answers instead of answer.
Shorter ver:
const questions = ['What do young Roman males wear?','Who is the Roman god of the smith?','Who is the 6th king of Rome?'];
const answers = ['toga praetexta','vulcan','servius tullius'];
var questNum;
function getQuestNum() {
questNum = Math.floor(Math.random() * 3);
};
function generateQuiz() {
getQuestNum();
document.getElementById("question").innerHTML = questions[questNum];
};
function checkCorrect() {
if (answers[questNum] = document.getElementById("input").value) {
document.getElementById("verification").innerHTML = "Correct!";
}
};
It would be simpler to create an array of objects that each contain both a question and an answer - and create a function that generates your random number and returns the object at the corresponding index.
Then you'll have access to everything you need without worrying about whether or not you can maintain access to the original randomly selected number, or matching up indices between two different arrays.

Check for prime in a list using sieve of Eratosthenes

I have an array as an input and i want to print the prime numbers that exist in that list. I was able to do that using trial division method. But I am struck at a point while trying to do the same thing using sieve of Eratosthenes method.
I tried it with below code, but got confused on how to compare the end result array with my input array list and return only those values that matches the input list. ( Detailed answer would be helpful as am a beginner in javascript).
var arr=[4,7,10,12,13,19,22,37];
function checkPrime(arr)
{
var output=[],primes=[];
var x=arr.length;
for(i=2;i<=arr[x-1];i++)
primes[i]=1;
for(i=2;i<=arr[x-1];i++)
for(j=2;j<=Math.sqrt(arr[x-1]);j++)
primes[i*j]=0;
for(i=0;i<=arr[x-1];i++){
if(primes[i]==1){
output.push(i);
}
}
return output;
}
console.log(checkPrime(arr));
When creating your output list, you want to compare against the values in arr, not the indices, so you need to replace primes[i] with primes[arr[i]].
So this:
if (primes[i] == 1) {
output.push(i);
}
Becomes this:
if (primes[arr[i]] == 1) {
output.push(arr[i]);
}

Categories

Resources