How to optimize algorithm which tries to get the lowest sum for a task

I have a puzzle game which I am not sure how to prove that I have the right answer. I am sure that a code can be written to get all the possible solutions and find the best one from them. However, I am not sure what logic this code should follow. I managed to write a code which can follow my logic, but it does not try all options and therefor maybe a better option exists

The Puzzle is the following:

We have a wizard which makes very special jewelry. However, because they are so special there are some rules that he should follow when creating them.

He has 30 types of beads and unlimited count from each type. Every bead has different color but for simplicity lets name them (B1, B2, B3, B4 … B30 because this is not important). The important part is that every bead type costs different amount of gold coins

B1 -> 1 gold coin

B2 -> 2 gold coins

B3 -> 3 gold coins

B30 -> 30 gold coins

There are three special operations that he can use when creates a jewelry:

  1. He can buy beads, but every time when he buys a bead he should put it at the end of the jewelry.

For example:

  • When he starts the jewelry no bead is added, so he can buy for example B4 for 4 gold coins and put it on the first place

  • After that he can buy another bead, for example B6 for 6 gold coins and he should put it at the end.

    Now he has jewelry from B4 – B6

  • After that he can buy another bead, for example B11 for 11 gold coins and he should put it at the end.

    Now he has jewelry from B4 – B6 – B11

The total amount of gold coins that he used for creation of this jewelry is 21

  1. He is so good that if he has jewelry from some beads he can cast a magic and he can increment all the beads with one. However, this magic costs 2 gold coins.

For example:

  • If we continue with the jewelry from the previous point B4 – B6 – B11, he can cast this magic and the result will be a new jewelry B5 – B7 – B12. This operation will cost for him 2 gold coins.

  • If he continue incrementing one more time, the jewelry will become: B6 – B8 – B13. This will cost him 2 gold coins.

From these two steps he spend 4 more gold coins and the total amount of the jewelry at the moment is 25

  1. The third and the last operation that he can use is to switch position of two adjacent beads. This will cost him 1 gold coin.

For example if we continue with the jewelry from previous step B6 – B8 – B13:

  • He can change the position of the second and third beads and the new jewelry will become B6 – B13 – B8 and the cost for this operation is 1 gold coin.

  • Now he can change the position of the second and first beads and the new jewelry will become B13 – B6 – B8 and the cost for this operation is 1 gold coin.

From these two steps he spend 2 more gold coin and the total amount of the jewelry at the moment is 27

The question is what is the smallest amount of gold coins that he should use to create the following jewelry:

B18 – B1 – B16 – B19 – B6 – B22 – B14 – B15 – B2 – B12 – B27 – B18 – B11 – B1 – B14 – B9 – B23 – B1

One thing to notice. The start and end bead of the jewelry are not connected. So there is no easy way to swap their positions with one move. You should move through all other beads.

The general approach of solving that I took is:

Instead of starting from 0, I start from the complete jewelry. If I have B1 at last position, I just remove it (this conforms to buy B1 action). If it is not a last position I move it to the last position and then remove it. If I do not have B1, I decrease until I have B1 and repeat all the other steps. If we are left with 2 beads just use them.

var final = [18, 1, 16, 19, 6, 22, 14, 15, 2, 12, 27, 18, 11, 1, 14, 9, 23, 1]; var totalSum = 0; var resultTable = [];  function sum() {     return final.reduce((acc, el) => acc + el, 0); }  function removeOne(arr, indexOfOne) {     if (indexOfOne === arr.length - 1) {         totalSum += 1;         arr.pop();         resultTable.push({ action: "remove last", arr: arr.toString(), cost: 1, totalCost: totalSum });        } else {         var nextOfOne = indexOfOne + 1;         var temp = arr[indexOfOne];         arr[indexOfOne] = arr[nextOfOne];         arr[nextOfOne] = temp;         totalSum += 1;         resultTable.push({ action: "swap", arr: arr.toString(), cost: 1, totalCost: totalSum });       } }  function decrementAll(arr) {     final = arr.map(el => el - 1);     totalSum += 2;     resultTable.push({ action: "decrement", arr: arr.toString(), cost: 2, totalCost: totalSum }); }  var i = 2;  while (sum() > 0) {     var indexOfOne = final.lastIndexOf(1);      if (final.length === 2) {         totalSum += final.pop();         totalSum += final.pop();         resultTable.push({ action: "sell", arr: final.toString(), totalCost: totalSum });         break;     }      if (indexOfOne !== -1) {         removeOne(final, indexOfOne);     } else {         decrementAll(final);     } }  console.table(resultTable);  

It can be run here: https://repl.it/@SamAAZZ/wizardjewerly

However, without using a code I managed to get answer 129, 128.

Do you have any idea how can I improve the code to get the right answer. Maybe this involves finding all solutions, but I really do not know how I can make it. A general idea how to approach such kind of tasks is also a good start for me.

Any code in different languages is also OK. I can run it and observe how it works to check logic behind finding all possible solutions. I know how to get all solutions if I have only one operation to test, however here there are three operations for 18 positions and I really do not have idea how to approach this problem

Thanks in advanced

Best approach to send 0.5 million emails with lowest cost [closed]

I am from engineering background. I have to send 0.5 million emails to users. I already have email addresses of the users.

I have few confusions

  • Sending mail through sendgrid etc, do I need to buy subscription which can hold 0.5 contacts?

  • I want to send via API, is there any API only approach?

  • What if I send via gmail SMTP?

Any kind of information is highly appreciated.

Greedy algorithm to divide objects into the lowest number of groups of a maximum size

I have n objects of independent size s, and need to group them so that the sum of the sizes of each group is smaller than a given maximum size, and the number of groups is the smallest possible.

I already tried a brute force algorithm that orders the objects in all possible permutations and then, based on their size and the group max size, divides every permutation in groups based on the order. This algorithm is very slow and therefore I want to find a greedy one, but being new to the topic I can’t think of a good way to start.

My idea would be to start building the first group from the largest object, and then adding more so that every time I add a new one, the difference between the max size and the size of all the objects in the group is minimized. Is this a good starting point?

Time complexity – Algorithm to find the lowest common ancestor of all deepest leaves

This is the problem statement I came across today.

Given a binary tree, find the lowest common ancestor of all deepest leaves.

I came up with a correct algorithm, but I would like to confirm the running time of this approach.

The algorithm is as follows:

  1. Traverse the tree and find the deepest level of the tree, dmax.
  2. Traverse the tree and find all leaves at depth dmax.
  3. Given that LCA(A,B,C) = LCA(LCA(A,B),C), traverse all nodes found at step 2 and calculate LCA.

The subroutine for LCA(A,B) is simple. Starting at A, go all the way up to the root and store each visited node in a hashset. Then, starting at B, go up until you find a node which is contained in the hashset.

I know the first two steps of the algorithm are both O(n), where n corresponds to the number of nodes in the tree. However, I am uncertain about the last step.

LCA(A,B) subroutine has a linear complexity. But how many nodes, in the worst scenario, can be found at step 2?.

Intuitively, I would argue that it has to be far less than n nodes.

What is the lowest level that an adventuring party can safely make enough money to take care of a city-state?

Lets say that a party has recently decided to retire from adventuring to focus their efforts in caring for a city-state in need of benefactors. I want to know what the lowest level a party can be and still safely make enough money to provide the required financial support to care for a city-state’s population, without their risking life or limb adventuring.

This isn’t an easy question since the economy of 3.5 is so screwed up that it’s difficult to determine how much a gold piece is worth, much less how many it takes to equal a nations GDP. So Let’s be a bit more exact on what I mean. Let’s say the party is in charge of a City-State the size of Rome, with a population of 35,000. They want to generously provide for it’s citizens by ensuring that each and every person can live a wealthy lifestyle, which costs 50gp/week/person. That means they need to provide 1,750,000 gp/week.

The adventuring party consists of 5 members, all at or below the party level you chose for your answer, of whatever classes you deem appropriate. The party can work any ‘safe’ job necessary to help earn the income required. At the time of their retirement they have at their disposal an amount of money expected for a party of their level, based off of wealth/level guidelines, to spend on purchasing items or equipment which would assist in providing for the City State.

If necessary the party can take up to a month’s worth of time, starting at the moment of retirement, to prepare for providing for the city. This could be spent building equipment, training underlings, or saving up money for a large purchase; whatever will help them to best provide for their city.

The lucky members of the city are being cared for without being required to earn the support, meaning they can not be utilized as part of the parties money making scheme. However, the party can employ any underlings or hirelings they would otherwise have access to.

Any solution must be sustainable long term, at least until the original party grows too old to continue providing for the city. Bonus points for minimizing cheese factor (though I’m open to answers with some low degree cheese) or for not requiring every member of the party to be equal to the total party level

What’s the lowest level at which a PC can break through a hewn stone wall in 1 round?

This question asks how PCs can break a stone wall. Aside from the usage of disintigrate to immediately destroy a wall, it seems that a wall can be destroyed by reducing it’s HP to 0. Walls have a hardness which reduces the damage done to them.

What is the lowest level at which a player character can destroy a wall in 1 round? Magical and mundane means are both in scope, and any item which the character has access to. Limit items to the character’s level or lower.

What is the lowest level at which a human could run a marathon in under two hours?

Inspired by What is the lowest level at which a human can beat the 100m world record (or: the presumed human limit) without using magic?, which I read just after finishing the Athens Marathon last November. Earlier in 2019, Kenyan athlete Eliud Kipchoge ran the marathon distance (42.195 km, about 26.2 miles) somewhat an order of magnitude faster than me in an amazing time of just under 2 hours, during the Ineos 1:59 Challenge.

Most D&D optimization attempts are aimed at short periods/distances (focused on combat situations), so for a change I’d like my (human) athlete to perform a feat of endurance: break the marathon distance record. What is the minimum level at which this can be achieved? A level 12 Monk has a base speed of 30ft + 40ft (assuming they’re unarmed) = 70ft, which, extrapolating the ‘Movement and Distance’ table on page 162 of my 3.5e Player’s Handbook translates to a Hustle speed of 14 miles an hour. A second hour of hustling incurs 1 point of nonlethal damage, and makes the character fatigued (I know how that feels) but doesn’t influence movement speed, so this monk should cross the finish line after 1:52 and a bit.

Since, unlike Usain Bolt, Eliud Kipchoge got some help from others (pacemakers, nutrition provided by a horseback bike rider, pacing lasers) during this record attempt, our human athlete character is allowed to invoke the help of their fellow party members, but magic is still out of the question; otherwise, you could just hire a bunch of Sorcerers, located at specific intervals on the track, each casting Expeditious Retreats for a continuous 30ft/round bonus.

Assume D&D 3.5e rules, and any officially rule book is allowed (I only have the Core Rulebooks, which for instance (AFAICT) don’t contain a feat which increases movement). When in doubt, the contest rules in the linked question apply (except for the assistance of up to five party members, which are the same level as the athlete).

Rolling 7 stats of 4d6R1R2-L and dropping lowest one in AnyDice

Rolling an individual (N)PC stat of 4d6, rerolling 1s and 2s, and dropping the lowest gives a modal average of 15 with a range of 9-18.  The AnyDice code to produce the graph for that is simple enough (and there are multiple ways to code this):

output [highest 3 of 4d{3..6}] 

What I’d like to do is roll 7 sets of these and drop the lowest sum (thus obtaining a standard 6 D&D stat scores, but specifically the highest 6 sums out of 7).
     How might I tell AnyDice to show me how this affects the scores in contrast to a standard 6 rolls of 3d6?

Git Merge Lowest common ancestor problem

How does Git find the ‘merge base’ of two branches in a commit graph? From what I understand, this reduces to finding the lowest common ancestor of a directed acyclic graph. After reading up on several algorithms with which one may do this, I am wondering how Git manages to solve the LCA problem.

(Apologies if this is more of a stack overflow question. I am however more interested in the internal algorithm Git uses so it may be appropriate for this forum.)