Alerting data specifics inside array - javascript

I'm running into a javascript beginner's problem. I have this data stored in an array, and I'm trying to alert the data to see if it checks out.
I want to alert myself the average of the distance of all, not both planets even though both is all in this case, but I eventually want to have an array that keeps a lot more than just two. Right now, it just alerts the distance of the last record in the array list, which is weird. I thought it'd be an average for all.
Also, how do I program the least and highest numbers of the "Distance" property in the array, and then alert the "Host name" with it. So, if I have a button and I click on "Closest", the Host name of the lowest number in "Distance [pc]" will be alerted. I only need an example of the code for "Distance", so I'll know how to do the same for all other variables.
Thank you if you're willing to help out!
Btw, the list is JSON data. Maybe important to mention this.
// this array holds the json data, in this case stastics of exoplanets retrieved from nasa's website
var arr= [ {
"rowid": 684,
"Host name": "K2-15",
"Number of Planets in System": 1,
"Planet Mass or M*sin(i)[Jupiter mass]": null,
"Planet Radius [Jupiter radii]": 0.221,
"Planet Density [g": {
"cm**3]": null
},
"Distance [pc]": 437,
"Effective Temperature [K]": 5131,
"Date of Last Update": "7/16/2015"
},
{
"rowid": 687,
"Host name": "K2-17",
"Number of Planets in System": 1,
"Planet Mass or M*sin(i)[Jupiter mass]": null,
"Planet Radius [Jupiter radii]": 0.199,
"Planet Density [g": {
"cm**3]": null
},
"Distance [pc]": 134,
"Effective Temperature [K]": 4320,
"Date of Last Update": "7/16/2015"
}];
//every record is put in a variable
var rowid;
var hostName;
var numberOfPlanetsInSystem;
var planetMass;
var planetRadius;
var distance;
var effectiveTemperature;
for(var i=0;i<arr.length;i++){
rowid= arr[i]["rowid"];
hostName= arr[i]["Host name"];
numberOfPlanetsInSystem= arr[i]["Number of Planets in System"];
planetMass= arr[i]["Planet Mass or M*sin(i)[Jupiter mass]"];
planetRadius= arr[i]["Planet Radius [Jupiter radii]"];
distance= arr[i]["Distance [pc]"];
effectiveTemperature= arr[i]["Effective Temperature [K]"];
};
//alert to test it out
alert(distance);

let totalDistance = maxDistance = 0;
let minDistance = arr[0]["Distance [pc]"];
let closestHost = farthestHost = "";
for(let i = 0; i < arr.length; i ++) {
totalDistance += arr[i]["Distance [pc]"]
if (arr[i]["Distance [pc]"] < minDistance) {
minDistance = arr[i]["Distance [pc]"];
closestHost = arr[i]["Host name"];
}
if (arr[i]["Distance [pc]"] > maxDistance) {
maxDistance = arr[i]["Distance [pc]"];
farthestHost = arr[i]["Host name"];
}
}
let meanDistance = totalDistance/arr.length;

In your cycle you are always overwrite your variable distance, not adding them.
Use distance += arr[i]["Distance [pc]"]
+= measn distance = distance + arr[i]["Distance [pc]"]
EDIT
Here is a working jsFiddle
You need to init var distance = 0;
var distance = 0; //Important!
var arr = [{
"rowid": 684,
"Host name": "K2-15",
"Number of Planets in System": 1,
"Planet Mass or M*sin(i)[Jupiter mass]": null,
"Planet Radius [Jupiter radii]": 0.221,
"Planet Density [g": {
"cm**3]": null
},
"Distance [pc]": 437,
"Effective Temperature [K]": 5131,
"Date of Last Update": "7/16/2015"
},
{
"rowid": 687,
"Host name": "K2-17",
"Number of Planets in System": 1,
"Planet Mass or M*sin(i)[Jupiter mass]": null,
"Planet Radius [Jupiter radii]": 0.199,
"Planet Density [g": {
"cm**3]": null
},
"Distance [pc]": 134,
"Effective Temperature [K]": 4320,
"Date of Last Update": "7/16/2015"
}];
for (var i = 0; i < arr.length; i++) {
distance += arr[i]["Distance [pc]"];
};
alert('Total distance: ' + distance + "\n" + 'Number of planets: ' + arr.length + "\n" + 'Average: ' + distance / arr.length);

Related

Select a random element out of an object/array based on the percent chance of it showing up [duplicate]

This question already has answers here:
How to choose a weighted random array element in Javascript?
(7 answers)
Closed 1 year ago.
I have an object that looks like this:
"rarity": {
"Common": "60",
"Uncommon": "25",
"Rare": "10",
...
"Legendary": "0.01",
"Mythical": "0.001",
}
The object is set up as 'Name': '% chance', so Common has a 60% chance of showing up, whereas Mythical has a 1 in 100,000 chance of showing up (0.001%)
I want to be able to (Quickly) select a random element based on the percentage chance of it showing up, but I have zero ideas where to begin.
If this is in the wrong StackExchange please let me know, it's programming-related but heavily math-based.
Let's start by taking a random number between 0 and 100000:
const rnd = Math.random() * 100000;
Now, you need to divide the number by 1000 since you want to take into account up to 3 decimals after comma for "Mythical": "0.001"
const percent = rnd / 1000;
Last, just take the key of the number that contains the percent variable.
Example
const rarity = {
"Common": "60",
"Uncommon": "25",
"Rare": "10",
"More rare": "4.989", // to fill the rest of percentage
"Legendary": "0.01",
"Mythical": "0.001"
}
const rnd = Math.random() * 100000;
const percent = rnd / 1000;
let result = null, acc = 0;
Object.keys(rarity).forEach(key => {
if (result === null && percent > 100 - rarity[key] - acc)
result = key;
acc += parseFloat(rarity[key]);
});
console.log(percent + " %", result);
Here you can test how many times each possibility appears in a 100000 loop
const rarity = {
"Common": "60",
"Uncommon": "25",
"Rare": "10",
"More rare": "4.989", // to fill the rest of percentage
"Legendary": "0.01",
"Mythical": "0.001"
}
let testNumber = 100000;
const testResults = {};
while (0 < testNumber--) {
const rnd = Math.random() * 100000;
const percent = rnd / 1000;
let result = null, acc = 0;
Object.keys(rarity).forEach(key => {
if (result === null && percent > 100 - rarity[key] - acc)
result = key;
acc += parseFloat(rarity[key]);
});
if (!testResults[result])
testResults[result] = 0;
testResults[result]++;
}
console.log(testResults);
You can achieve that by:
dividing the 0 to 1 segment into sections for each element based on their probability (For example, an element with probability 60% will take 60% of the segment).
generating a random number and check in which segment it lands.
STEP 1
make a prefix sum array for the probability array, each value in it will signify where its corresponding section ends.
For example:
If we have probabilities: 60% (0.6), 30%, 5%, 3%, 2%. the prefix sum array will be: [0.6,0.9,0.95,0.98,1]
so we will have a segment divided like this (approximately): [ | | ||]
STEP 2
generate a random number between 0 and 1, and find it's lower bound in the prefix sum array. the index you'll find is the index of the segment that the random number landed in
Here's how you can implement this method:
let obj = {
"Common": "60",
"Uncommon": "25",
"Rare": "10",
"Legendary": "0.01",
"Mythical": "0.001"
}
// turning object into array and creating the prefix sum array:
let sums = [0]; // prefix sums;
let keys = [];
for(let key in obj) {
keys.push(key);
sums.push(sums[sums.length-1] + parseFloat(obj[key])/100);
}
sums.push(1);
keys.push('NONE');
// Step 2:
function lowerBound(target, low = 0, high = sums.length - 1) {
if (low == high) {
return low;
}
const midPoint = Math.floor((low + high) / 2);
if (target < sums[midPoint]) {
return lowerBound(target, low, midPoint);
} else if (target > sums[midPoint]) {
return lowerBound(target, midPoint + 1, high);
} else {
return midPoint + 1;
}
}
function getRandom() {
return lowerBound(Math.random());
}
console.log(keys[getRandom()], 'was picked!');
hope you find this helpful. If you need any clarifications please ask
Note:
(In Computer Science) the lower bound of a value in a list/array is the smallest element that is greater or equal to it. for example, array:[1,10,24,99] and value 12. the lower bound will be the element with value 24.
When the array is sorted from smallest to biggest (like in our case) finding the lower bound of every value can be done extremely quickly with binary searching (O(log(n))).
EDIT: added code example

javascript/node JSON parsing issue

Here is my example data:
http://api.setlist.fm/rest/0.1/setlist/4bf763f6.json
I'm just writing a node app that prints out the details of this page. What I'm concerned with are sets, set and song.
var sets = setlist.sets
res.write(JSON.stringify(sets)) // THIS SHOWS THE CORRECT DATA
var numSets = Object.keys(sets).length;
for(var i = 0; i < numSets; i++){
res.write("\nsets " + i);
var set = sets.set[i];
console.log(Object.getOwnPropertyNames(set))
var numSet = Object.keys(set).length;
res.write(JSON.stringify(set))
for(var j = 0; j < numSet; j++){
res.write("\nset " + (j+1) + " of " + numSet);
var song = set.song;
console.log(Object.getOwnPropertyNames(song))
numSong = Object.keys(song).length;
for(var k = 0; k < numSong; k++){
res.write("\n song " + j + "-" + k);
res.write("\n "+JSON.stringify(song[k]["#name"]));
}
}
}
what I get is:
set 1 of 1
song 0-0
"Lift Me Up"
song 0-1
"Hard to See"
song 0-2
"Never Enough"
song 0-3
"Got Your Six"
song 0-4
"Bad Company"
song 0-5
"Jekyll and Hyde"
song 0-6
"Drum Solo"
song 0-7
"Burn MF"
song 0-8
"Wrong Side of Heaven"
song 0-9
"Battle Born"
song 0-10
"Coming Down"
song 0-11
"Here to Die"
There are TWO song elements in set: (sorry no code block or it won't wrap)
{
"set": [{
"song": [{
"#name": "Lift Me Up"
}, {
"#name": "Hard to See"
}, {
"#name": "Never Enough"
}, {
"#name": "Got Your Six"
}, {
"#name": "Bad Company",
"cover": {
"#disambiguation": "British blues-rock supergroup",
"#mbid": "0053dbd9-bfbc-4e38-9f08-66a27d914c38",
"#name": "Bad Company",
"#sortName": "Bad Company",
"#tmid": "734487",
"url": "http://www.setlist.fm/setlists/bad-company-3bd6b8b0.html"
}
}, {
"#name": "Jekyll and Hyde"
}, {
"#name": "Drum Solo"
}, {
"#name": "Burn MF"
}, {
"#name": "Wrong Side of Heaven",
"info": "Acoustic"
}, {
"#name": "Battle Born",
"info": "Acoustic and Electric"
}, {
"#name": "Coming Down"
}, {
"#name": "Here to Die"
}]
}, {
"#encore": "1",
"song": [{
"#name": "Under and Over It"
}, {
"#name": "Burn It Down"
}, {
"#name": "The Bleeding"
}]
}]
}
In Swift I just make set a Dictionary and it works just fine. Javascript is not my forte. Why can't I get that second song element?
setlist.set is an array of two objects, one containing the "regular"(?) songs and the other containing the encore information.
It looks like you are mixing up loop variables with other objects/arrays and not iterating what you think you're iterating.
Here's a simplified version that should show what you're expecting:
// `sets` is an object containing (at least) `set` and `url` properties
var sets = setlist.sets;
// `set` is an array containing (in your example, two) objects
var set = sets.set;
for (var i = 0; i < set.length; ++i) {
console.log('Set %d/%d', i+1, set.length);
// `curSet` is an object containing a `song` property
var curSet = set[i];
// `songs` is an array of objects
var songs = curSet.song;
for (var j = 0; j < songs.length; ++j) {
// `song` is an object containing properties like `#name` and possibly others
var song = songs[j];
console.log(' - Song: %s', song['#name']);
}
}
The line
var numSets = Object.keys(sets).length;
Should be
var numSets = sets.set.length;
May I also suggest that you use a forEach loop rather than a for loop (a .map() would be even better). for loops are much more prone to bugs than the alternatives.

Cannot read undefined property error - building object properties in JavaScript

I am taking an online JavaScript class and am stuck on a problem involving objects. In the following code, my assignment is to output a string that retrieves the name of each ranger (e.g. lighthouseRock.ranger1.name) and match their station to the corresponding item in the superBlinders array.
If I hard-code the ranger1 property, the output format is in the right ballpark. However, if I try to be creative and build a variable (thisRanger) to dynamically insert the appropriate ranger into my object, the routine returns an error "TypeError: Cannot read property 'name' of undefined". My thisRanger variable builds OK but whenever I try to insert it into my chain after lightHouseRock it causes the undefined problem. Here is my code:
var superBlinders = [ ["Firestorm", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ];
var lighthouseRock = {
gateClosed: true,
weaponBulbs: superBlinders,
capacity: 30,
secretPassageTo: "Underwater Outpost",
numRangers: 0
};
function addRanger(location, name, skillz, station) {
location.numRangers++;
location["ranger" + location.numRangers] = {
name: name,
skillz: skillz,
station: station
};
}
addRanger(lighthouseRock, "Nick Walsh", "magnification burn", 2);
addRanger(lighthouseRock, "Drew Barontini", "uppercut launch", 3);
addRanger(lighthouseRock, "Christine Wong", "bomb defusing", 1);
var dontPanic = function () {
var message = "Avast, me hearties!\n";
message += "There be Pirates nearby! Stations!\n";
for (var i = 1; i <= lighthouseRock.numRangers; i++) {
var thisRangerNumber = i;
var thisRanger = "ranger" + thisRangerNumber;
// message += lighthouseRock.ranger1.name + ", man the " + superBlinders[lighthouseRock.ranger1.station][0] + "!\n";
message += lighthouseRock.thisRanger.name + ", man the " + superBlinders[lighthouseRock.thisRanger.station][0];
};
console.log(message);
}
The expected output should look something like this:
Avast, me hearties!
There be Pirates nearby! Stations!
<name>, man the <superblinder>!
<name>, man the <superblinder>!
<name>, man the <superblinder>!
How can I insert thisRanger into my code so that it gives me the expected output? Thank you very much for your help!
Working code!
It outputs all you want it todo!
UPDATE you have an error in your code I fixed that also..
Ranger2 will always be stationed on undefined since there aren't 3 stations when counting as an array, remember array in javascript starts counting from 0(zero). I changed Drew barontini to "0"
addRanger(lighthouseRock, "Nick Walsh", "magnification burn", 2);
addRanger(lighthouseRock, "Drew Barontini", "uppercut launch", 0);
addRanger(lighthouseRock, "Christine Wong", "bomb defusing", 1);
CODE OUTPUT
Avast, me hearties!
There be Pirates nearby! Stations!
Nick Walsh, man the Supernova,12000 Drew Barontini, man the Firestorm,4000Christine Wong, man the Solar Death Ray,6000
I didn't do much to change your code. But what I did is that I change your code into
message += lighthouseRock[thisRanger].name + ", man the " + superBlinders[lighthouseRock[thisRanger].station] +"\n";
Its important to know with javascript that you can use brackets [] to get to an object property if you build the stirng dynamicly.
var superBlinders = [ ["Firestorm", 4000], ["Solar Death Ray", 6000], ["Supernova", 12000] ];
var lighthouseRock = {
gateClosed: true,
weaponBulbs: superBlinders,
capacity: 30,
secretPassageTo: "Underwater Outpost",
numRangers: 0
};
function addRanger(location, name, skillz, station) {
location.numRangers++;
location["ranger" + location.numRangers] = {
name: name,
skillz: skillz,
station: station
};
}
addRanger(lighthouseRock, "Nick Walsh", "magnification burn", 2);
addRanger(lighthouseRock, "Drew Barontini", "uppercut launch", 0);
addRanger(lighthouseRock, "Christine Wong", "bomb defusing", 1);
var dontPanic = function () {
var message = "Avast, me hearties!\n";
message += "There be Pirates nearby! Stations!\n";
for (var i = 1; i <= lighthouseRock.numRangers; i++) {
var thisRangerNumber = i;
var thisRanger = "ranger" + thisRangerNumber;
// message += lighthouseRock.ranger1.name + ", man the " + superBlinders[lighthouseRock.ranger1.station][0] + "!\n";
message += lighthouseRock[thisRanger].name + ", man the " + superBlinders[lighthouseRock[thisRanger].station] +"\n";
};
console.log(message);
}
dontPanic();

How to create random data but with meaningful relation?

var lc_relationship={"sensor1":[
{
"ObjectID":"sens1_001",
"Parent":null,
"child": sens2_050
"z cordinate": -5
},
{
"ObjectID":"sens1_002",
"Parent":null,
"child": sens2_072
"z cordinate": -5
}
.
.
.
uptill ObjectID : sens1_100
],
"sensor2":[
{
"ObjectID":"sens2_001",
"Parent":sens1_068,
"child": sens3_010
"z cordinate": 0
},
{
"ObjectID":"sens2_002",
"Parent":sens1_040,
"child": sens3_080
"z cordinate": 0
}
.
.
.
uptill ObjectID : sens2_100
],
"sensor3":[
{
"ObjectID":"sens3_001",
"Parent":sens2_055,
"child": null
"z cordinate": 5
},
{
"ObjectID":"sens3_002",
"Parent":sens2_029,
"child": null
"z cordinate": 5
}
.
.
.
uptill ObjectID : sens3_100
]
}
I need to store the relationship of geometry in some data structure so that later should be helpful to track either wise to access the derived geometry. I made a detail picture, so that one could get the better idea. Could someone help..?
If I understood your question, you have very concrete data (100 cones placed in 3 layers), and what you want to randomize is the relationship between them.
If so, then next code may give you what you need: It randomly picks a cone from first layer, then sets a relation to a randomly selected cone from the second layer, for which also sets a relation to a randomly selected cone from the third layer (no cone is selected twice in any layer, as in your description). Here is a jsFiddle with a working implementation: http://jsfiddle.net/roimergarcia/j2uLE.
NOTES:
The 10x10 grid that is on the drawing may be easily generated form the indexes of the sensor arrays.
If you are going to generate more than 100 cones per layer (100000?) or a lot of layers, you may need to optimize this algorithm.
//A helping function
function rightPad(number) {
var tmpStr = number.toString();
return ("000" + tmpStr).substring(tmpStr.length, tmpStr.length+3);
}
//The generator function
function generateData(){
var nSize = 100,
lc_relationship,
aSensor1 = [],
aSensor2 = [],
aSensor3 = [],
lc_relationship = {
"sensor1":[],
"sensor2":[],
"sensor3":[]
}
for(i=1; i<=nSize; i++){
aSensor1.push(i);
aSensor2.push(i);
aSensor3.push(i);
}
for(n=0; n<nSize; n++){
var pos1 = Math.floor(Math.random() * (nSize-n));
var pos2 = Math.floor(Math.random() * (nSize-n));
var pos3 = Math.floor(Math.random() * (nSize-n));
var int1 = aSensor1[pos1]; aSensor1.splice(pos1,1);
var int2 = aSensor2[pos2]; aSensor2.splice(pos2,1);
var int3 = aSensor3[pos3]; aSensor3.splice(pos3,1);
lc_relationship.sensor1[int1-1] = {
"ObjectID" : "sens1_" + rightPad(int1),
"Parent":null,
"child": "sens2_" + rightPad(int2),
"z cordinate": -5
}
lc_relationship.sensor2[int2-1] = {
"ObjectID" : "sens2_" + rightPad(int2),
"Parent":"sens1_" + rightPad(int1),
"child": "sens3_" + rightPad(int3),
"z cordinate": 0
}
lc_relationship.sensor3[int3-1] = {
"ObjectID" : "sens3_" + rightPad(int3),
"Parent":"sens2_" + rightPad(int2),
"child": null,
"z cordinate": 5
}
}
return lc_relationship;
}
console.log(generateData());

First Javascript program. What am I doing wrong?

I have finally gotten around to creating my first little practice program in Javascript. I know it's not elegant as it could be. I have gotten most of this code to work, but I still get an "undefined" string when I run it a few times. I don't know why. Would someone be kind enough to explain to me where this undefined is coming from?
var work = new Array();
work[1] = "product design";
work[2] = "product system design";
work[3] = "product social media post x5";
work[4] = "product Agent Recruitment system design";
work[5] = "product profile system design";
work[6] = "product Agent testing design";
work[7] = "product customer support";
work[8] = "product promotion";
var course = new Array();
course[1] = "javascript";
course[2] = "mandarin";
course[3] = "javascript practical-Code Academy";
course[4] = "javascript practical-learn Street";
course[5] = "mandarin practical-memrise";
course[6] = "new stuff with audiobooks";
var activity = new Array();
activity[1] = "listen to podcasts";
activity[2] = "chat online";
activity[3] = "Exercise";
activity[4] = "take a walk";
activity[5] = "call a friend";
var picker1 = Math.floor(Math.random()*3+1);
var picker2 = Math.floor(Math.random()*work.length+1);
var picker3 = Math.floor(Math.random()*course.length+1);
var picker4 = Math.floor(Math.random()*activity.length+1);
var group_pick = function(){
if(picker1 === 1){
return "Time to work on ";
} else if(picker1 === 2){
return "Time to learn some ";
} else if (picker1 === 3){
return "Lets relax and ";
} else {
return "error in group_pick";
}
};
var item_pick = function() {
if (picker1 === 1) {
return work[picker2] ;
} else if (picker1 === 2) {
return course [picker3] ;
} else if (picker1 === 3) {
return activity[picker4] ;
} else {
return "error in item_pick";
}
};
var task = group_pick() + item_pick();
document.write(task);
Array's start with an index of zero. When you assign a value to the 1 index, a 0 index is created you, with no value (undefined).
var arr = new Array();
arr[1] = 'hi!';
console.log(arr); // [undefined, "hi!"]
console.log(arr.length) // 2
Length is 2, check that out. You thought you had one item in that array but length is 2.
Usually it's easier to not manage the array indices yourself. And the array literal syntax is usually preferred for a number of reasons.
var arr = [];
arr.push('hi!');
console.log(arr); // ["hi!"]
console.log(arr.length) // 1
Or just create the array with the items in it directly, very handy.
var arr = [
"hi",
"there!"
];
console.log(arr); // ["hi", "there"]
console.log(arr.length) // 2
Once you are making the arrays properly, you can get a random item with simply:
var arr = ['a','b','c'];
var index = Math.floor(Math.random() * arr.length);
console.log(arr[index]); // "a", "b" or possibly "c"
This works because var index will be calculated by a random value of between 0.0 and up to but not including 1.0 times 3 (the length of the array). Which can give you a 0, 1 or a 2.
So this arr right here, has 3 items, one at 0, one at 1, and one at 2.
Learning to address arrays from zero can be mentally tricky. You sort of get used to it. Eventually.
A working example using these tips here: http://jsfiddle.net/du5Jb/
I changed how the arrays are declared, and removed the unneeded +1 from var pickerX calculations.
The problem is that the .length attribute for arrays counts the number of elements in the array starting from zero. So for example activity has elements 1 through 5, so according to Javascript the .length is actually 6. Then your random number calculation will choose a number from 1 through 7, past the end of the array. This is where the undefined comes from.
You can fix this by starting your index numbering at 0 instead of 1, so activity would have elements 0 through 4, with a .length of 5. Also remove the +1 from your choice calculations.
When you use your "pickers", you don't want to have the +1 inside of the `Math.floor functions.
Consider this array:
var array = [ "one", "two", "three" ];
array.length; // 3
The length is 3 -- makes sense, there are 3 items inside.
But arrays are zero-based.
array[0]; // "one"
array[1]; // "two"
array[2]; // "three"
array[3]; // undefined
So when you add that + 1, you're:
a) making it impossible to pick the first thing in the array
b) making it possible to pick a number that is exactly 1 higher than the last element in the array (undefined)
The problem here as i see it is that when you generate your random variables you're doing PickerX + 1...
So the right way to do it would be PickerX without the +1.
Also Off topic you shouldn't use if commands, try using switch case...
Here's the fixed code-
var work = new Array()
work[0] = "product design";
work[1] = "product system design";
work[2] = "product social media post x5";
work[3] = "product Agent Recruitment system design";
work[4] = "product profile system design";
work[5] = "product Agent testing design";
work[6] = "product customer support";
work[7] = "product promotion";
var course = new Array();
course[0] = "javascript";
course[1] = "mandarin";
course[2] = "javascript practical-Code Academy";
course[3] = "javascript practical-learn Street";
course[4] = "mandarin practical-memrise";
course[5] = "new stuff with audiobooks";
var activity = new Array();
activity[0] = "listen to podcasts";
activity[1] = "chat online";
activity[2] = "Exercise";
activity[3] = "take a walk";
activity[4] = "call a friend";
var picker1 = Math.floor(Math.random() * 3 +1 );
var picker2 = Math.floor(Math.random() * work.length );
var picker3 = Math.floor(Math.random() * course.length );
var picker4 = Math.floor(Math.random() * activity.length );
var group_pick = function(){
switch(picker1){
case 1:
return "Time to work on ";
case 2:
return "Time to learn some ";
case 3:
return "Lets relax and ";
default:
return "error in group_pick";
}
};
var item_pick = function() {
switch(picker1){
case 1:
return work[picker2] ;
case 2:
return course [picker3] ;
case 3:
return activity[picker4] ;
default:
return "error in item_pick";
}
};
var task = group_pick() + item_pick();
document.write( task );​
Don't work so hard. Zero is your friend. Let's go golfing...
var work = [
"product design", "product system design",
"product social media post x5",
"product Agent Recruitment system design",
"product profile system design",
"product Agent testing design",
"product customer support", "product promotion",
], course = [
"javascript", "mandarin",
"javascript practical-Code Academy",
"javascript practical-learn Street",
"mandarin practical-memrise", "new stuff with audiobooks",
], activity = [
"listen to podcasts", "chat online", "Exercise",
"take a walk", "call a friend",
];
function rint(cap) {
return (Math.random() * cap) | 0;
}
function pick(item) {
switch (item) {
case 0: return "Time to work on " +
work[ rint(work.length) ];
case 1: return "Time to learn some " +
course[ rint(course.length) ];
case 2: return "Lets relax and " +
activity[ rint(activity.length) ];
default: return "error";
}
}
document.write(pick(rint(3)) + '<br>');

Categories

Resources