Combine 2 arrays of different lengths and sort date - javascript

I have 2 arrays with different lengths
let daysArray = ['09-20', '09-21', '09-22', '09-23', '09-24', '09-25', '09-26']
let weekNameArray = ['Mi', 'Do', 'Fr', 'Sa + So', 'Mo', 'Di' ]
combined them with _.zipWith:
let weakDateArr = _.zipWith(weekNameArray, daysArray , function(first, second) {
return first + " " + second
});
How I can combine them to get the next array:
['Mi 09-20', 'Do 09-21', 'Fr 09-22', 'Sa + So', 'Mo 09-25', 'Di 09-26']
'Sa + So' must be undated *

Hmm, not sure lodash has support for this out of box...
You could apply a simple custom solution using Array.map() and an index offset for the daysArray:
days_offset = 0;
let combined = weekNameArray.map( (name, index) => {
if(name.length <= 2) {
return name + ' ' + daysArray[ index - days_offset ];
} else {
days_offset += 1;
return name;
}
});

Related

How to randomize the order of buttons in a div?

I'm making a education website and I need some help.
I have this code:
challenge1 = num1*num2;
challenge2 = num1*2+Math.floor(Math.random() *3) + 1;;
challenge3 = num1*num2+Math.floor(Math.random() *9) + 1;
challenge4 = num2+Math.floor(Math.random() *9) + 1;
makeButton(challenge1);
makeButton(challenge2);
makeButton(challenge3);
makeButton(challenge4);
function makeButton(number) {
btncount = btncount+1;
/* create a button */
var b = document.createElement('button');
b.setAttribute('class', 'pure-button');
b.setAttribute('onclick', `check(${number})`);
b.setAttribute('id', btncount);
b.textContent = number;
var buttons = document.getElementById("buttons");
buttons.appendChild(b);
}
<div id='buttons' class="pure-button-group" role="group"></div>
and it works but it's very easy to spot that the correct answer will always be the first button.
Is there a way to randomize the order of those? Thanks.
It's about shuffling a list. you should create an array of elements first(without appending them to the parent), shuffle it, and then parent.append(...list).
You can find out how to shuffle a list here:
How to randomize (shuffle) a JavaScript array?
following your snippet you can swap first and last randomly
let btncount = 0;
function makeButton(number) {
btncount = btncount+1;
/* create a button */
var b = document.createElement('button');
b.setAttribute('class', 'pure-button');
b.setAttribute('onclick', `check(${number})`);
b.setAttribute('id', btncount);
b.textContent = number;
var buttons = document.getElementById("buttons");
buttons.appendChild(b);
//randomly swap first and last
if(Math.round(Math.random())) {
// swap first and last
buttons.appendChild(buttons.firstElementChild);
}
}
const num1 = 1, num2 = 2;
const challenge1 = num1*num2;
const challenge2 = num1*2+Math.floor(Math.random() *3) + 1;;
const challenge3 = num1*num2+Math.floor(Math.random() *9) + 1;
const challenge4 = num2+Math.floor(Math.random() *9) + 1;
makeButton(challenge1);
makeButton(challenge2);
makeButton(challenge3);
makeButton(challenge4);
<div id="buttons">
</div>
You could make an array of challenges and sort this array with a custom comparator:
challenges = [
num1*num2,
num1*2+Math.floor(Math.random() *3) + 1,
num1*num2+Math.floor(Math.random() *9) + 1,
num2+Math.floor(Math.random() *9) + 1
]
function randomizer () { return Math.random() > 0.5 }
challenges.sort(randomizer)
for (challenge of challenges) makeButton(challenge)
EDIT
To have a better randomization you can make a list of object with a random index and sort it normally:
challenges = [
{ challenge: num1*num2, index: Math.random() },
{ challenge: num1*2+Math.floor(Math.random() *3) + 1, index: Math.random() },
{ challenge: num1*num2+Math.floor(Math.random() *9) + 1, index: Math.random() },
{ challenge: num2+Math.floor(Math.random() *9) + 1, index: Math.random() }
]
function compare(a,b) { return a.index == b.index ? 0 : a.index > b.index ? 1 : -1 }
challenges.sort(compare)
for (i in challenges) makeButton(challenges[i].challenge)
Put the "challenges" into an array and shuffle it. You can shuffle in plain javascript as described in this answer, but I prefer to shuffle with rando.js, like this:
console.log( randoSequence(["a", "b", "c"]) );
<script src="https://randojs.com/2.0.0.js"></script>
Apply that shuffle to your buttons, and you have this:
var num1 = 2;
var num2 = 4;
var btncount = 0;
challenge1 = num1 * num2;
challenge2 = num1 * 2 + Math.floor(Math.random() * 3) + 1;;
challenge3 = num1 * num2 + Math.floor(Math.random() * 9) + 1;
challenge4 = num2 + Math.floor(Math.random() * 9) + 1;
//------------CHANGED PART------------
var shuffledChallenges = randoSequence([challenge1, challenge2, challenge3, challenge4]);
makeButton(shuffledChallenges[0].value);
makeButton(shuffledChallenges[1].value);
makeButton(shuffledChallenges[2].value);
makeButton(shuffledChallenges[3].value);
//--------END OF CHANGED PART.--------
function makeButton(number) {
btncount = btncount + 1;
/* create a button */
var b = document.createElement('button');
b.setAttribute('class', 'pure-button');
b.setAttribute('onclick', `check(${number})`);
b.setAttribute('id', btncount);
b.textContent = number;
var buttons = document.getElementById("buttons");
buttons.appendChild(b);
}
<script src="https://randojs.com/2.0.0.js"></script>
<div id='buttons' class="pure-button-group" role="group"></div>

Javascript adding multiple arrays in a loop

I am trying to add multiple arrays in javascript.
Here are my arrays I have made, and are working.
function getAmountSpent(){
var amountSpent = ((Math.random() * 500) + 1);
return amountSpent.toFixed(2)
}
function getGift(){
var gift = ((Math.random()* 50) + 1);
return gift.toFixed(2)
}
var names = ["Jeremy","Arun","Alisa","Rohan","Dana"];
var spent = [];
for (let i = 0; i < 5; i++) {
spent.push(getAmountSpent());
}
var gifts = [];
for (let i = 0; i<5; i++) {
gifts.push(getGift());
}
What I need help with is adding these arrays in a new function. I have began writing the code, and I am not sure what is wrong.
var totals =[];
for (let i=0; i<5; i++) {
totals.push(getSumTotals())
}
function getSumTotals(a){
totals= spent+(spent * gifts);
return totals.toFixed(2)
}
From what you can see, I am trying to add up the totals much like this:
totals[0] = spent[0] + (spent[0] * gifts[0]);
totals[1] = spent[1] + (spent[1] * gifts[1]);
totals[2] = spent[2] + (spent[2] * gifts[2]);
totals[3] = spent[3] + (spent[3] * gifts[3]);
totals[4] = spent[4] + (spent[4] * gifts[4]);
if it helps, the professor added guided instructions for function getSumTotals(a) stating:
This function will return the sum of the elements in array a.
You will be passing the array that holds your totals to
the parameter a. Be sure to treat the values in a as numbers.
I am not sure if this helps but here is the output to my document.
Current Total should equal (spent) + (spent * gifts). For instance, for Jeremy in this example, current total should equal:
$36.55 + ($36.55*0.0626) = $38.83. Since there are many variables involved, I am not 100% sure what I should write for function getSumTotals(a)
The parameter "a" is a placeholder because I am not sure how many parameter values I need, and the proper format I need to use.
As for the code...
You're both
not passing an index to getSumTotals
not using this parameter within getSumTotals to access your spent and gifts arrays
var totals =[];
for (let i=0; i<5; i++) {
totals.push(getSumTotals(i)) // you were missing i
}
function getSumTotals(idx) { // I took liberties to rename this
totals = spent[idx] + (spent[idx] * gifts[idx]);
return totals.toFixed(2);
}
Now for the Math...
All that said, this math of spent[i] + spent[i] * gifts[i] doesn't make much sense either. Was this specified in the problem?
you may use like this
defined gifts
gifts=[45,43,32];
defined spends
spends=[43,32,21];
this is the getSumTotal funtion
getSumTotal=(x)=>(x.a+x.b)
this is where added
totals=gifts.map((d1,i)=>{
return fu({a:gifts[i],b:spends[i]})
})
I understand this is your assignment, however - if the idea is to both generate arrays, and then add them together, it is a redundant step. Just use the name array to iterate once and do all your calculations within that single loop.
Here, I had some fun and took some liberties, but hopefully you see why multiple arrays are redundant.
function getSumTotals() {
const getAmountSpent = () => Math.random() * 500 + 1;
const getGift = () => Math.random() * 50 + 1;
const names = ["Jeremy", "Arun", "Alisa", "Rohan", "Dana"];
let totals = []
names.forEach((name, i) => {
let spent = getAmountSpent()
let gifts = getGift()
let $$$ = (spent + spent * gifts).toFixed(2);
totals[i] = $$$
console.log(`${name} cost me $${$$$}${'!'.repeat(($$$/1000) | 1)}`)
});
return totals;
}
getSumTotals()
Note, that toString returns a type of "String", but not "Number".
When you try to sum a number with string, you get a concatenated string "1" + 2 = "12"
To turn a string into Number, you must use a Number("str") function, or just a bunary + before the string:
console.log( "1" + 2 );
console.log( Number("1") + 2 );
console.log( +"1" + 2 );
Also, you use the same loop 3 times, but can use just one loop instead, and call all functions inside the one loop. And use your array.length instead of fixed number 5:
let names = ["Jeremy", "Arun", "Alisa", "Rohan", "Dana"];
let spent = [];
let gifts = [];
let totals = [];
for (let i = 0; i < names.length; i++) {
spent.push( getAmountSpent() );
gifts.push( getGift() );
totals.push( getSumTotals(i) );
}
console.log( totals );
function getAmountSpent() {
return rand(1, 500, 2);
}
function getGift() {
return rand(1, 50, 2);
}
function getSumTotals(i) {
return +( spent[i] * ( 1 + gifts[i] ) ).toFixed(2);
}
function rand(from, to, fixed = 0){
return +(Math.random()*( to - from ) + from).toFixed(fixed);
}
P.s. Math.random() returns a number between 0 (included) and 1 (not included). If you need a random number between (example) 20 and 100, Math.random()*(100-20) will give a number between 0 and 80. After adding +20 to the result, you get a number from 20 to 100. That's what does this formula Math.random()*( to - from ) + from
P.P.s. Another way, to get the same thing:
var names = ["Jeremy", "Arun", "Alisa", "Rohan", "Dana"].reduce( (prev, elem) => {
let spent = rand(1, 500, 2);
let gift = rand(1, 50, 2);
prev[elem] = new UserData( spent, gift );
return prev;
}, {});
console.log( "Jeremy spent: " + names.Jeremy.spent );
console.log( names );
function rand(from, to, fixed = 0){
return +(Math.random()*( to - from ) + from).toFixed(fixed);
}
function UserData(spent, gift){
this.spent = spent;
this.gift = gift;
this.total = +(spent * ( 1 + gift )).toFixed(2);
}
/* Google → Array reduce, Constructor functions */
function getAmountSpent(){
let amountSpent = ((Math.random() * 500) + 1);
return Number(amountSpent.toFixed(2))
}
function getGift(){
let gift = ((Math.random()* 50) + 1);
return Number(gift.toFixed(2))
}
let names = ["Jeremy","Arun","Alisa","Rohan","Dana"];
let spent = [];
let gifts = [];
let totals =[];
for (let i = 0; i < names.length; i++) {
spent.push(getAmountSpent());
gifts.push(getGift());
totals[i] = (spent[i]+(spent[i] * gifts[i])).toFixed(2);
totals[i] = parseFloat(totals[i])
}
Hi there
I don't think you need a function to add the totals. you just need to loop through and assign totals[i] to spent[i] + (spent[i] * gifts[i]).
then you can use the parseFloat and toFixed function to change the string to a number. remember toFixed() function turns numbers to string. so you need to use the parseFloat to change it to number again as shown in the code above. or you can come up with an easy way of changing it to number. I hope this helps!

Is my javascript implementation of a DP solution to Knapsack properly utilizing a memoization table?

This is my javascript implementation for the knapsack problem. In this problem, you are given a list of items with weights and values, and a knapsack with a weight capacity. The object is to determine how to maximize the value of objects you can hold in the knapsack without exceeding the weight capacity. My function below takes two parameters, items (an array of item objects, each containing a weight and value field, and a capacity integer representing the knapsack weight capacity. I use a memo table in which each index:weight is stored for repeated access to avoid duplicate calculations of getMax(). Is my implementation good? Can it be improved?
function knapsackMaxValue(items, capacity) {
const memo = {}
function getMax(i, weight) {
if (i == items.length) {
return 0;
}
if (memo[i + ':' + weight] != undefined) {
console.log('memo found')
return memo[i + ':' + weight]
}
if (items[i].weight + weight > capacity) {
memo[i + ':' + weight] = getMax(i + 1, weight)
return memo[i + ':' + weight]
} else {
let maxValue = Math.max(getMax(i + 1, weight), items[i].value + getMax(i + 1, weight + items[i].weight))
memo[i + ':' + weight] = maxValue
return maxValue
}
}
return getMax(0, 0)
}

Look up tables and integer ranges - javascript

So I am looking to create look up tables. However I am running into a problem with integer ranges instead of just 1, 2, 3, etc. Here is what I have:
var ancient = 1;
var legendary = 19;
var epic = 251;
var rare = 1000;
var uncommon = 25000;
var common = 74629;
var poolTotal = ancient + legendary + epic + rare + uncommon + common;
var pool = general.rand(1, poolTotal);
var lootPool = {
1: function () {
return console.log("Ancient");
},
2-19: function () {
}
};
Of course I know 2-19 isn't going to work, but I've tried other things like [2-19] etc etc.
Okay, so more information:
When I call: lootPool[pool](); It will select a integer between 1 and poolTotal Depending on if it is 1 it will log it in the console as ancient. If it hits in the range of 2 through 19 it would be legendary. So on and so forth following my numbers.
EDIT: I am well aware I can easily do this with a switch, but I would like to try it this way.
Rather than making a huge lookup table (which is quite possible, but very inelegant), I'd suggest making a (small) object, choosing a random number, and then finding the first entry in the object whose value is greater than the random number:
// baseLootWeight: weights are proportional to each other
const baseLootWeight = {
ancient: 1,
legendary: 19,
epic: 251,
rare: 1000,
uncommon: 25000,
common: 74629,
};
let totalWeightSoFar = 0;
// lootWeight: weights are proportional to the total weight
const lootWeight = Object.entries(baseLootWeight).map(([rarity, weight]) => {
totalWeightSoFar += weight;
return { rarity, weight: totalWeightSoFar };
});
console.log(lootWeight);
const randomType = () => {
const rand = Math.floor(Math.random() * totalWeightSoFar);
return lootWeight
.find(({ rarity, weight }) => weight >= rand)
.rarity;
};
for (let i = 0; i < 10; i++) console.log(randomType());
Its not a lookup, but this might help you.
let loots = {
"Ancient": 1,
"Epic": 251,
"Legendary": 19
};
//We need loots sorted by value of lootType
function prepareSteps(loots) {
let steps = Object.entries(loots).map((val) => {return {"lootType": val[0], "lootVal": val[1]}});
steps.sort((a, b) => a.lootVal > b.lootVal);
return steps;
}
function getMyLoot(steps, val) {
let myLootRange;
for (var i = 0; i < steps.length; i++) {
if((i === 0 && val < steps[0].lootVal) || val === steps[i].lootVal) {
myLootRange = steps[i];
break;
}
else if( i + 1 < steps.length && val > steps[i].lootVal && val < steps[i + 1].lootVal) {
myLootRange = steps[i + 1];
break;
}
}
myLootRange && myLootRange['lootType'] ? console.log(myLootRange['lootType']) : console.log('Off Upper Limit!');
}
let steps = prepareSteps(loots);
let pool = 0;
getMyLoot(steps, pool);

user input - Javascript

I have a code that I am working on , it is for ordering pizza. I have been coding for 7 days and I want to find out how can I make the pizza prices bigger by the size of the pizza
For example , small pizza is 15.75$ medium is 16.75 and big is 17.75
Each time I run the code , the output is 15.75
(Look at the bottom portion)
employee = confirm("Are you ready to take an order?");
if (employee === true) {
console.log("Here is the order");
} else {
console.log("Ask another employee to take the order. If there is no one, then please take the order ");
}
let orderCount = 0;
const takeOrder = (topping, crustType) => {
orderCount++;
console.log("Order: " + crustType + " pizza topped with " + topping);
};
//
// Order comes here like this - takeOrder('pepperoni', //'texas style');
takeOrder('pepperoni', 'texas style');
//
const getSubTotal = (itemCount) => {
return itemCount * 14.5;
};
//const ^^
console.log("The Sub-Total is " + getSubTotal(orderCount) + "$");
const getTax = (itemCount) => {
return itemCount * 1.25;
};
console.log("The tax is " + getTax(orderCount) + "$");
const getTotal = () => {
return getSubTotal(orderCount) + getTax(orderCount);
};
console.log("And the final total is " + getTotal() + "$");
console.log("Thank you for taking this order.")
As for one of the comments, the price relative to size is not in your logic:
let priceBySize = {
'S': 15.75,
'M': 16.75,
'L': 14.5,
}
// size of order required - might consider also to pass quantity
takeOrder('pepperoni', 'texas style', 'M');
takeOrder('margherita', 'clasic style', 'L');
const getSubTotal = (itemCount, size) => {
return itemCount * priceBySize[size];
};
Also instead of fixed prices for size maybe you'll prefer to have multipliers for sizes and base price per type of pizza.

Categories

Resources