Hello, this is an elementary js problem,which is currently simplified until I get the below problem solved.
In function <b>select</b> I select 2 people at random.
In function <b>transfer</b>, there is a transfer of money from poorer to richer .
poorer and richer are calculated in function <b>select</b>
Problem is that richer and poorer are not recognised when control goes to function <b>transfer</b>.
I get "undefined" on line 45.
I know this is a simple matter of var and let, but I have not yet found a simple explanation of var and let and hoist on the web. Simple for a beginner like me, that is.
If I can get this sorted the rest will be easy.
Can anyone help?
Is there a reasonable site which explains var and let for a beginner?
And the significance of "use strict"?
I am retired and self-taught.
I was unable to copy/paste the .html from VSCode so here it is.
In function <b>select</b> I select 2 people at random.
In function <b>transfer</b>, there is a transfer of money from poorer to richer .
poorer and richer are calculated in function <b>select</b>
Problem is that richer and poorer are not recognised when control goes to function <b>transfer</b>.
I get "undefined" on line 45.
I know this is a simple matter of var and let, but I have not yet found a simple explanation of var and let and hoist on the web. Simple for a beginner like me, that is.
If I can get this sorted the rest will be easy.
Can anyone help?
Is there a reasonable site which explains var and let for a beginner?
And the significance of "use strict"?
I am retired and self-taught.
I was unable to copy/paste the .html from VSCode so here it is.
JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>ginaCoeff</title>
</head>
<body>
<script>
var richer;
var poorer;
var N = 10;
var startLevel = 100;
var people = [];
var trials = 100;
var transferFrac = 0.20;
function loadPeople(N) {
for (let i = 0; i <= N - 1; i++) {
people[i] = startLevel;
console.log(i, people[i]);
}
}
function select(N, richer, poorer) {
var x = Math.floor(Math.random() * N) + 1;
var y = Math.floor(Math.random() * N) + 1;
if (x == y) {
x = x + Math.floor(Math.random() * N) + 1;
if (x > N) {
x = x - N;
}
}
richer = Math.max(x, y);
poorer = Math.min(x, y);
console.log("fn select: " + "richer " + richer + " poorer " + poorer);
}
function transfer(richer, poorer, transferFrac) {
var richer;
var poorer;
console.log("fn transfer1: " + "richer " + richer + " poorer " + poorer);
var transferAmount = people[poorer] * transferFrac;
people[richer] = people[richer] + transferAmount;
people[poorer] = people[poorer] - transferAmount;
}
/////////////////////////////////////////////////////
loadPeople(N);
select(N, richer, poorer);
transfer(richer, poorer, transferFrac);
console.log(people[richer] + " " + people[poorer]);
</script>
</body>
</html>