i´m getting crazy with this...I need to loop 10 times (automaticaly) a random number between 1-4 (both included), and this numbers must obtain a colour from switch cases', printed in the console.I tried to separate the switch cases, random function & the loop of that random function but....Any suggest???
//colours to assiged(depending on random number)
function getColor(colorNumber=0)
{
colorNumber = parseInt(colorNumber);
switch(colorNumber){
case 1: return "red";
break;
case 2: return "yellow";
break;
case 3: return "blue";
break;
case 4: return "green";
break;
default: return "black";
break;
}
}
//var with random generated
function getAllStudentColors(){
var getAllStudentColors = Math.floor(Math.random(4-1)*10) + 1;
}
//looping for function of random numbers
function loop() {
var exampleColor = 0;
while (exampleColor = 1) {
getAllStudentColors();
exampleColor++;
}
}
var exampleColor = getColor();
getAllStudentColors();
You could take a loop function with paramters for the count of loops and the function which should be called for every iteration and collect the result in an array.
I simplified the getColor fuunction by using an array and a fefault value for handing over an unknown property.
//colours to assiged(depending on random number)
function getColor(colorNumber = 0) {
return ["black", "red", "yellow", "blue", "green"][colorNumber] || "black";
}
//var with random generated
function getRandomColor() {
return getColor(Math.floor(Math.random() * 5));
}
//looping for function of random numbers
function loop(n, fn) {
let colors = [];
while (n--) colors.push(fn());
return colors;
}
console.log(...loop(10, getRandomColor));
Related
I can't implement the function tipPercentage that takes the argument rating as a string and return the values:
terrible or poor, then returns 3
good or great, then returns 10
excellent, returns 20
none of the above, returns 0
the input format for custom testing must be that the first line contains a integer, n, denoting the value of rating
HELP FOR A BEGGINNER!!!
You can use a switch statement to do this relatively easily, we check the input rating, then return the relevant tip percentage.
If we don't have a tip percentage for the rating, we'll fall back to the default condition, and return 0.
One could also use a map, though a switch statement is probably more flexible.
// Takes rating as a string and return the tip percentage as an integer.
function tipPercentage(rating) {
switch ((rating + "").toLowerCase()) {
case "terrible":
case "poor":
return 3;
case "good":
case "great":
return 10;
case "excellent":
return 20;
default:
return 0;
}
}
let ratings = ["excellent", "good", "great", "poor", "terrible", "meh", null];
for(let rating of ratings) {
console.log(`tipPercentage(${rating}):`, tipPercentage(rating))
}
function tipPercentage(rating) {
switch(rating) {
case "terrible":
case "poor":
return 3; break;
case "good":
case "great":
return 10; break;
case "excellent":
return 20; break;
default:
return 0;
}
}
Instead of a switch statement you could simply use an object:
const tipPercentage = {
'excellent': 20,
'good': 10,
'great': 10,
'terrible': 3,
'poor': 3,
}
const myRatings = [
"excellent",
"good",
"great",
"terrible",
"whatever",
undefined
];
for (let rating of myRatings) {
// Tip percentage, or 0 if it doesn't exist
console.log(rating, tipPercentage[rating] || 0)
}
I recently started to study javascript
I'm currently watching Javascript course in Udemy.
While code challenging, There's something I cant get it about parameter of 'switch'
let john = {
fullName: 'John Smith',
bills: [124, 48, 268, 180, 42],
calcTips: function() {
this.tips = [];
this.finalValues = [];
for (let i = 0; i < this.bills.length; i++) {
let percentage;
let bill = this.bills[i]
switch (bill) { // If I put parameter as 'bill' variation, The result is only defalut.
case bill < 50:
percentage = 0.2;
break;
case bill >= 50 && bill < 200:
percentage = 0.15;
break;
default:
percentage = 0.1;
}
this.tips[i] = bill * percentage;
this.finalValues[i] = bill + bill * percentage;
}
}
}
john.calcTips();
console.log(john);
However
let john = {
fullName: 'John Smith',
bills: [124, 48, 268, 180, 42],
calcTips: function() {
this.tips = [];
this.finalValues = [];
for (let i = 0; i < this.bills.length; i++) {
let percentage;
let bill = this.bills[i]
switch (true) { // If I put 'ture' as a parameter, It work's. Why?
case bill < 50:
percentage = 0.2;
break;
case bill >= 50 && bill < 200:
percentage = 0.15;
break;
default:
percentage = 0.1;
}
this.tips[i] = bill * percentage;
this.finalValues[i] = bill + bill * percentage;
}
}
}
john.calcTips();
console.log(john);
I've searched in google about this problem.
But I can't find specific way to solve this issue.
I'll appreciate your help.
Switch statements compare values strictly. Which means that you can compare for the exact value of the switch variable.
switch (x) {
case 1: console.log(1); break;
case 2: console.log(2); break;
}
You can do a trick however if you want to make the switch statement work on numerical ranges like this:
var x = this.dealer;
switch (true) {
case (x < 5):
alert("less than five");
break;
case (x < 9):
alert("between 5 and 8");
break;
case (x < 12):
alert("between 9 and 11");
break;
default:
alert("none");
break;
}
The implementation works on the strict comparison of booleans. The switch statement is for true and will match wherever the case is true.
Related question: Switch on ranges of integers in JavaScript
The switch statement tests the value of a variable and compares it with multiple cases. Once the case match is found, a block of statements associated with that particular case is executed. So in this case you switching on a constant value.
More detail :
javascript: using a condition in switch case
I would like to turn this:
let nums = [1, 2, 3];
let syms = ["+", "*"];
let result;
Into a math expression:
result = 1 + 2 * 3;
console.log(result); // 7
Without using eval(), because it returns weird stuff like i.e. "6.3 + 0.6" = 6.8999999999999995
Most bug free answer so far......
var nums=[1,0],syms=['/']
const rulesyms = ['/','*']; //do not change sequence of this one.
var res, count=0,power=0;
solve_nonsumoperator().then(()=>{
summing().then(()=>{
console.log(nums[nums.length-1])
})
})
function getnums(j,operator){
power=0
if(Math.floor(nums[j])!=nums[j])
power=nums[j].toString().split('.')[1].length
else{ //if not a float then forcing float point
nums[j]=nums[j].toFixed(1)
power=1
}
if(Math.floor(nums[j+1])!=nums[j+1]){
if(power<nums[j+1].toString().split('.')[1].length){
power=nums[j+1].toString().split('.')[1].length
}
}
else{
nums[j+1]=nums[j+1].toFixed(1)
if(power<1)
power=1
}
//adding decimal 0s to match floating point
for(let i = nums[j].toString().split('.')[1].length;i<power;i++)
nums[j]=nums[j].toString()+'0'
for(let i = nums[j+1].toString().split('.')[1].length;i<power;i++)
nums[j+1]=nums[j+1].toString()+'0'
nums[j]=parseInt(nums[j].toString().split('.').join(''),10)
nums[j+1]=parseInt(nums[j+1].toString().split('.').join(''),10)
switch(operator){
case '/':res=nums[j]/nums[j+1]
break;
case '*':res=nums[j]*nums[j+1]/Math.pow(10,2*power)
break;
default:if(operator==='+')
res=(nums[j]+nums[j+1])/Math.pow(10,power)
else if(operator==='-')
res=(nums[j]-nums[j+1])/Math.pow(10,power)
break;
}
}
function redundant(j){
nums[j+1]=res //replacing the result into array position
for(var k = j;k>0;k--){
//loop to replace the used nums, syms to begin of array
nums[k]=nums[k-1]
syms[k]=syms[k-1]
}
syms[count]='$' //has to be below for loop
count++
}
function summing(){
syms.forEach((g,j)=>{
if(g==='+'||g==='-'){
getnums(j,g)
redundant(j)
}
})
return Promise.resolve()
}
function solve_nonsumoperator(){
rulesyms.forEach(f=>{
syms.forEach((g,j)=>{
if(g===f){
getnums(j,f)
redundant(j)
}
})
})
return Promise.resolve()
}
I'm working on a Word Search puzzle game, and I'm struggling with generating the grid with letters. At the moment, I'm able to generate the grid, but the performance is very slow (way too slow for a decent usage, it can take up to 30-40 seconds before generating the grid).
To fit words into the grid, I'm using a recursive function that tries to fit the last word from a given list, then the one before it, etc, and if it doesn't fit, backtracks to the previous word and changes its place, then tries again. I guess I'm not doing this right, because it keeps going back and forth.
I tried to use weighed probabilities for directions, so that the generating is made in a "smarter" way, but I'm not getting any results yet.
My question :
How can I optimize this code to make it more performant and reliable? I accept any suggestions, even if it makes me do a lot of changes (if there is an iterative solution for example instead of a recursive one, or if I'm not reasoning correctly in the function...).
Here is the function:
function tryWord(grid, wordList, index, gridLength){
var valid = false;
var clear = false;
if(index==(wordList.length-1)){
/* Clear grid for current index */
for(var j=0; j<gridLength.x; j++){
grid[index][j] = [];
for (var k=0; k<gridLength.y; k++){
grid[index][j][k] = '';
}
}
var nbIterations = 0;
// Try current word
while(valid == false){
// Impossible to resolve this grid
if(nbIterations>500){
return false;
}
nbIterations++;
var initX = Math.floor(Math.random() * gridLength.x); // x coord of first letter of the word
var initY = Math.floor(Math.random() * gridLength.y); // y coord of first letter of the word
var direction = Math.floor(Math.random() * 8); // direction of the word (0=top-left; 1=top; 2=top-right; 3=right; 4=bottom-right; 5=bottom; 6=bottom-left; 7=left)
valid = checkValidWord(wordList[index].length, initX, initY, direction, gridLength);
}
clear = checkClearWord(wordList[index], initX, initY, direction, grid[index]);
if(!clear){
return false;
}
var x = initX;
var y = initY;
for(var j=0; j<wordList[index].length; j++){
grid[index][x][y] = wordList[index].charAt(j);
switch(direction){
case 0:
x--;
y--;
break;
case 1:
y--;
break;
case 2:
x++;
y--;
break;
case 3:
x++;
break;
case 4:
x++;
y++;
break;
case 5:
y++;
break;
case 6:
x--;
y++;
break;
case 7:
x--;
break;
default:
break;
}
}
return grid;
}
else if(index!=(wordList.length-1)){
var emptyGrid = true;
for(var p=0; p<grid[index].length; p++){
for(var q=0; q<grid[index][p].length; q++){
if(grid[index][p][q]!=''){
emptyGrid = false;
}
}
}
if(emptyGrid || $scope.nbIterations>50){
$scope.nbIterations=0;
grid = tryWord(grid, wordList, index+1, gridLength);
}
/* Prepare grid for current index */
grid[index] = grid[index+1];
if(grid!=false){
// Try current word
while(valid == false){
var initX = Math.floor(Math.random() * gridLength.x); // x coord of first letter of the word
var initY = Math.floor(Math.random() * gridLength.y); // y coord of first letter of the word
var direction = Math.floor(Math.random() * 8); // direction of the word (0=top-left; 1=top; 2=top-right; 3=right; 4=bottom-right; 5=bottom; 6=bottom-left; 7=left)
valid = checkValidWord(wordList[index].length, initX, initY, direction, gridLength); // Check that word fits in the grid
}
clear = checkClearWord(wordList[index], initX, initY, direction, grid[index]);
// If word is obstructed by other words
if(!clear){
$scope.nbIterations++;
return tryWord(grid, wordList, index, gridLength); // Try again
}
else{
var x = initX;
var y = initY;
for(var j=0; j<wordList[index].length; j++){
grid[index][x][y] = wordList[index].charAt(j);
switch(direction){
case 0:
x--;
y--;
break;
case 1:
y--;
break;
case 2:
x++;
y--;
break;
case 3:
x++;
break;
case 4:
x++;
y++;
break;
case 5:
y++;
break;
case 6:
x--;
y++;
break;
case 7:
x--;
break;
default:
break;
}
}
return grid;
}
}
else{
return false;
}
}
}
Parameters of the function :
grid : at the beginning, just a 10x11x11 array filled with '' string.
wordList : an array of words to put in the grid
index : 0 when calling the function for the first time, then it's used to check how deep we are in the wordList
gridLength : an array : {x:11, y:11}, giving the grid length
Some more precisions about the function :
The function checkValidWord checks if a given word going to a given direction fits in a grid with a given size. Returns true or false.
The function checkClearWord checks if a given word going to a given direction fits in the grid with other words already in it (no obstruction etc). Returns true or false.
The function tryWord is supposed to output a 3-dimensional array of size [wordList.length;11;11]. I then use the grid[0] as my 2 dimensional grid for the game.
I need a random object generator in JavaScript that generates a variety of objects with different fields and values. Any ideas where I can find such tool?
I need to generate random objects with various complexity.. My goal is to use JSON in order to serialize these objects and fuzz test my application http api.
function createRandomObj(fieldCount, allowNested)
{
var generatedObj = {};
for(var i = 0; i < fieldCount; i++) {
var generatedObjField;
switch(randomInt(allowNested ? 6 : 5)) {
case 0:
generatedObjField = randomInt(1000);
break;
case 1:
generatedObjField = Math.random();
break;
case 2:
generatedObjField = Math.random() < 0.5 ? true : false;
break;
case 3:
generatedObjField = randomString(randomInt(4) + 4);
break;
case 4:
generatedObjField = null;
break;
case 5:
generatedObjField = createRandomObj(fieldCount, allowNested);
break;
}
generatedObj[randomString(8)] = generatedObjField;
}
return generatedObj;
}
// helper functions
function randomInt(rightBound)
{
return Math.floor(Math.random() * rightBound);
}
function randomString(size)
{
var alphaChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
var generatedString = '';
for(var i = 0; i < size; i++) {
generatedString += alphaChars[randomInt(alphaChars.length)];
}
return generatedString;
}
It will create a obj with X paramenters, all with a integer, float, string, boolean or null value.
I just made it :B
You can use hasard library
Random variables and random nested objects manipulation in javascript
const h = require('hasard');
const randomInteger = h.integer({type: 'poisson', lambda: 4});
const randomString = h.string({
size: h.add(randomInteger, 5),
value: h.value('abcdefghijklmnopkrstuvw'.split(''))
});
const randomNumber = h.number([0, 100]);
const randomKeys = h.array({
size: randomInteger,
value: randomString
});
// we first define it, to use it as reference into randomObject
const randomValue = h.value();
const randomObject = h.object(
randomKeys,
randomValue
);
// And we set recursivity by setting his values afterward
randomValue.set([
randomString,
randomObject,
randomNumber,
randomInteger
]);
Results will looks like
[
{
"vbmujvv": "rfigcpcvpj",
"sjmcgvvk": 3,
"efdarehl": {
"odinthsuca": "rwjhmbfus",
"noihjtjen": 27.73332043042913,
"brspkaagb": "lnuiabcfd"
},
"febtungjhfokf": 49.28625818957401,
"eoemrkgi": {
"jkcuwrpsh": "ekjoltm",
"cincs": {
"fcovbwk": {
"whsgmjh": 48.00843935524626,
"agsjflef": 46.700796253998014
},
"ovkdfudgfm": 84.83383163217746,
"fpfetl": "djuvfjbjptf",
"kobmkstj": {
"wskgkkerk": 9,
"kvnptptek": 37.63655947554132,
"dsloun": 4
}
},
"krirwk": {
"sjgftomu": 51.663884142674775,
"hpjgibnli": 4
},
"pkhkgruls": "isuodwjrg"
},
"ortomnue": 71.71303423929236
}
]
DISCLAIMER i'm the author of hasard library