## Finds a Character based on distance and health

I need to improve the efficiency of my program and, using the profiler, have narrowed the problem down to 2 key areas, but I am having trouble coming up with ways to make the program run better.

Based on my profiler’s report, it seems to be telling me that my if functions are inefficient. Whats a better way to achieve a better result?

Character* FindAttackTarget() const         {             float weakestHp = FLT_MAX;             Character* weakestEnemy = nullptr;             uint64_t weakestCharId = INT64_MAX;              //Only attack characters that are within attack range             auto& gameChars = m_pGame->m_gameCharacters;               for (size_t i = 0; i < gameChars.size(); ++i)             {                 auto& c = gameChars[i];                 if (Location.Dist(c.GetLocation()) <= AttackRange &&                     c.HP > 0 &&                     c.Team != Team)                 {                     //We want the weakest with the lowest ID number - this keeps consistent results when re-playing the same part of the game (eg. after a load game)                     if (c.HP < weakestHp || (c.HP == weakestHp && c.ID < weakestCharId))                     {                         weakestEnemy = &gameChars[i];                         weakestHp = c.HP;                         weakestCharId = c.ID;                     }                 }             }              return weakestEnemy;         } 

## What is the longest distance a player character can jump?

After asking What is the longest distance a 13th-level monk can jump while attacking on the same turn?, my curiosity got piqued.

By RAW, what is the longest distance a player character can jump?

The jumping rules state:

Long Jump.

When you make a long jump, you cover a number of feet up to your Strength score if you move at least 10 feet on foot immediately before the jump. When you make a standing long jump, you can leap only half that distance. Either way, each foot you clear on the jump costs a foot of movement.

This rule assumes that the height of your jump doesn’t matter, such as a jump across a stream or chasm. […]

• Only classes from the books; multiclassing is allowed.
• You can make the character(s) level 20 (if required).
• The jumping character has allies that can aid in increasing the jump distance.
• For starting ability scores, use the standard array of 15, 14, 13, 12, 10, 8.
• Spells are allowed, preferably without casting Wish (because of its unreliability).
• Magic Items are allowed, but only from the official books.
• There is no time limit for preparing the epic jump.

Related: What happens when you run out of movement while jumping?

## Distance of the point (a,b,c) to the plane Z=0

I’m trying to solve a calculus problem, I need to find the mass of a cylinder, I’m close to the answer, I got $$8\pi$$ but it should be $$16\pi$$.

I think my mistake lies in the density function since it uses some linear algebra ideas.

“The density at the point (a,b,c) = double of the distance of the point to the plane z=0”

At first I did $$\sqrt{a^2+b^2}$$ but that’s the distance of a point to the z-axis not z-plane right?

If we want to find the distance of a point (a,b,c) to the z-plane can we just lower this point until it reaches the z-plane? So we have the distance between (a,b,c) and (a,b,0)? So we get $$\sqrt{z^2}=z$$

## Aggregate Pandas Columns on Geospacial Distance

I have a dataframe that has 3 columns, Latitude, Longitude and Median_Income. I need to get the average median income for all points within x km of the original point into a 4th column. I need to do this for each observation.

I have tried making 3 functions which I use apply to attempt to do this quickly. However, the dataframes take forever to process (hours). I haven’t seen an error yet, so it appears to be working okay.

The Haversine formula, I found on here. I am using it to calculate the distance between 2 points using lat/lon.

from math import radians, cos, sin, asin, sqrt  def haversine(lon1, lat1, lon2, lat2):      #Calculate the great circle distance between two points      #on the earth (specified in decimal degrees)      # convert decimal degrees to radians      lon1, lat1, lon2, lat2 = map(radians, [lon1, lat1, lon2, lat2])      # haversine formula      dlon = lon2 - lon1      dlat = lat2 - lat1      a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2     c = 2 * asin(sqrt(a))      r = 6371 # Radius of earth in kilometers. Use 3956 for miles     return c * r 

My hav_checker function will check the distance of the current row against all other rows returning a dataframe with the haversine distance in a column.

def hav_checker(row, lon, lat):      hav = haversine(row['longitude'], row['latitude'], lon, lat)      return hav 

My value grabber fucntion uses the frame returned by hav_checker to return the mean value from my target column (median_income).

For reference, I am using the California housing dataset to build this out.

def value_grabber(row, frame, threshold, target_col):      frame = frame.copy()      frame['hav'] = frame.apply(hav_checker, lon = row['longitude'], lat = row['latitude'], axis=1)      mean_tar = frame.loc[frame.loc[:,'hav'] <= threshold, target_col].mean()      return mean_tar 

I am trying to return these 3 columns to my original dataframe for a feature engineering project within a larger class project.

df['MedianIncomeWithin3KM'] = df.apply(value_grabber, frame=df, threshold=3, target_col='median_income', axis=1)  df['MedianIncomeWithin1KM'] = df.apply(value_grabber, frame=df, threshold=1, target_col='median_income', axis=1)  df['MedianIncomeWithinHalfKM'] = df.apply(value_grabber, frame=df, threshold=.5, target_col='median_income', axis=1) 

I have been able to successfully do this with looping but it is extremely time intensive and need a faster solution.

## Context

For context, this problem is part of my attempt to determine the path of least inertia for a free and open-source laser scanner DAC API I am developing. The following problem arises during the vector image optimisation pass. I convert the 2D vector image into a graph of 2D positions and add blank edges (i.e. transparent lines) to represent the image as a strongly connected, undirected Eulerian graph from which I should be able to determine the optimal Eulerian circuit.

## Problem

Given a strongly connected, undirected Eulerian graph (i.e. each vertex has an even degree), I’m trying to determine the Eulerian circuit that results in the minimum possible accumulative angle, where each vertex is a position in 2D space and each edge describes a straight line between the vertices.

## My Solution Attempt

My attempt at solving this was to first simplify the problem by looking at each vertex individually. We know that each vertex must have an even degree, and thus for each vertex there must be an optimal set of incoming/outgoing edge pairs (where each edge is used once) that results in a minimum accumulative angular distance. By minimum accumulative angular distance, I’m referring to the sum of the difference between the result of the difference between the angle of each incoming/outgoing edge pair and a straight line. For example, given the following vertex A and its neighbours B, C, D and E:

an example of optimal pairs would be (DA, AB) and (EA, AC) as they are cumulatively the least sharp angles through which A may be traversed (and in turn would induce the least inertia), whereas the pairs (EA, AD) and (BA, AC) would be the least optimal as cumulatively they contain the sharpest angles to be traversed (resulting in the highest inertia).

Once the set of optimal pairs is determined for each vertex, I suspect the Eulerian Circuit can be created by starting at one of the vertices, picking a direction to begin and following the optimal pairs until the beginning is reached again.

## My Solution Attempt Issues

Currently however I’m running into two issues.

1. I don’t know for sure whether or not my assumption holds true for all Euler graphs (where all nodes have an even degree).
2. I’m unsure of the best approach for determining the set of optimal edge pairs for each vertex. I suspect it may be possible to represent each vertex and its edges as a sub-graph and treat the problem as finding the shortest path (where the “shorter” distances are the paths through the vertex that result in the straightest angles), but I’m struggling to come up with a sub-graph representation that would allow me to do this.

## Related Research

In section 3.4 of Accurate and Efficient Drawing Method for Laser Projection the paper describes using Hierholzer’s algorithm for finding an optimal Eulerian circuit with the amendment that during traversal of each vertex you select the unvisited edge along the angle closest to a straight line. One issue that occurs to me with this approach is that it is not clear to me that this always results in the absolute optimal circuit, only one that is probably more optimal than a naive construction without this added amendment.

## Questions

1. Is there an existing solution to the original Problem stated above? If so, is there somewhere I might read further on this?
2. If not, does my attempted solution sound like a reasonable approach? If so, do you have an idea of how I might represent the sub-graph for determining the set of edge pairs resulting in the minimum accumulative angular distance for each vertex?
3. If not, can you recommend an approach I might be able to take to make progress on solving the previously mentioned Problem?

## Calculating the Distance Matrix from Adjacency Matrix

How would I calculate the distance matrix of a connected, simple and undirected graph from the adjacency matrix? I have 56 nodes, if that is helpful, and would need to the answer to return an array. Thank you!

# Context

During last session in a game that I GM, the party got attacked by monk NPCs from the trees. In the heat of the moment, the person who was playing a Warlock and got targeted by the monks (he was flying mid-air) convinced me that jumping distance is only 10 feet when doubled. It didn’t make any sense to me in the moment, to have 50 feet of movement as a monk but not be able to jump further than 10 feet. But the party was already having a rough time, and I didn’t want to slow down combat, so I ruled in favour of the party.

Now, post-session, I’m looking into the Basic Rules:

Long Jump. When you make a long jump, you cover a number of feet up to your Strength score if you move at least 10 feet on foot immediately before the jump. When you make a standing long jump, you can leap only half that distance. Either way, each foot you clear on the jump costs a foot of movement.

This rule assumes that the height of your jump doesn’t matter, such as a jump across a stream or chasm. At your DM’s option, you must succeed on a DC 10 Strength (Athletics) check to clear a low obstacle (no taller than a quarter of the jump’s distance), such as a hedge or low wall. Otherwise, you hit it.

When you land in difficult terrain, you must succeed on a DC 10 Dexterity (Acrobatics) check to land on your feet. Otherwise, you land prone.

### Question

The monk:

• has 50 feet of movement (base)
• has a Strength score of 16
• is able to run the required 10 feet
• takes Step of the Wind as bonus action
• saves the Action for attacking

Step of the Wind. You can spend 1 ki point to take the Disengage or Dash action as a bonus action on your turn, and your jump distance is doubled for the turn.

What is the longest distance the monk can jump within this framework?

# Context

During last session in a game that I GM, the party got attacked by monk NPCs from the trees. In the heat of the moment, the person who was playing a Warlock and got targeted by the monks (he was flying mid-air) convinced me that jumping distance is only 10 feet when doubled. It didn’t make any sense to me in the moment, to have 50 feet of movement as a monk but not be able to jump further than 10 feet. But the party was already having a rough time, and I didn’t want to slow down combat, so I ruled in favour of the party.

Now, post-session, I’m looking into the Basic Rules:

Long Jump. When you make a long jump, you cover a number of feet up to your Strength score if you move at least 10 feet on foot immediately before the jump. When you make a standing long jump, you can leap only half that distance. Either way, each foot you clear on the jump costs a foot of movement.

This rule assumes that the height of your jump doesn’t matter, such as a jump across a stream or chasm. At your DM’s option, you must succeed on a DC 10 Strength (Athletics) check to clear a low obstacle (no taller than a quarter of the jump’s distance), such as a hedge or low wall. Otherwise, you hit it.

When you land in difficult terrain, you must succeed on a DC 10 Dexterity (Acrobatics) check to land on your feet. Otherwise, you land prone.

### Question

The monk:

• has 50 feet of movement (base)
• has a Strength score of 16
• is able to run the required 10 feet
• takes Step of the Wind as bonus action
• saves the Action for attacking

Step of the Wind. You can spend 1 ki point to take the Disengage or Dash action as a bonus action on your turn, and your jump distance is doubled for the turn.

What is the longest distance the monk can jump within this framework?

## Why is $\mathbb{R}^2$ endowed with the taxicab metric isomorphic to the infinity distance model of the cartesian real plane? (Hartshorne exercise 8.9)

My question deals with the following exercise from Hartshorne’s Euclid: Geometry and Beyond:

Following our general principles, we say that two models $$M,M’$$ of our geometry are isomorphic if there exists a 1-to-1 mapping $$\phi:M\to M’$$ of the set of points of $$M$$ onto the set of points $$M’$$, written $$\phi(A) = A’$$, that sends lines to lines, preserves betweenness, i.e., $$A\ast B\ast C$$ in M $$\iff$$ $$A’\ast B’\ast C’$$ in M’, and preserves congruence of line segments, i.e., $$AB\cong CD$$ in M$$\iff$$ $$A’B’\cong C’D’$$ in $$M’$$

If $$A=(a_1,a_2),B=(b_1,b_2)\in\mathbb{R}^2$$, the exercise asks you to first show that $$\mathbb{R}^2$$ endowed with the taxicab metric: $$d(A,B)=|a_1-b_1|+|a_2-b_2|$$ Is isomorphic to the model of $$\mathbb{R}^2$$ endowed with the infinity distance: $$d(A,B)=sup\{|a_1-b_1|,|a_2-b_2|\}$$ How can we proceed in order to prove these models are isomorphic? How should we describe our isomorphism $$\phi:\mathbb{R}^2\to \mathbb{R}^2$$? I’m definitely having trouble with sending congruent lines to congruent lines.

The second part of the exercise claims that the taxicab metric model is not isomorphic to that of the standard model, i.e., the cartesian plane $$\mathbb{R}^2$$ equipped with the usual Euclidean distance. Hartshorne leaves a hint to this exercise: in order to prove two models are not isomorphic, one just has to find a statement which is true in one model but not in the other. I’m thinking, for example, that the line: $$y=x+1$$ Cuts the circle of center the origin $$(0,0)$$, and radius $$1$$ in infinitely many points in the taxicab metric model, a property that never holds in the standard model, which should make it clear that both models are not isomorphic. However, the first part still puzzles me, and I can’t imagine how to proceed.

from difflib import ndiff  def calculate_levenshtein_distance(str_1, str_2):     """         The Levenshtein distance is a string metric for measuring the difference between two sequences.         It is calculated as the minimum number of single-character edits necessary to transform one string into another     """     distance = 0     buffer_removed = buffer_added = 0     for x in ndiff(str_1, str_2):         code = x[0]         # Code ? is ignored as it does not translate to any modification         if code == ' ':             distance += max(buffer_removed, buffer_added)             buffer_removed = buffer_added = 0         elif code == '-':             buffer_removed += 1         elif code == '+':             buffer_added += 1     distance += max(buffer_removed, buffer_added)     return distance 
similarity = 1 - calculate_levenshtein_distance(str_1, str_2) / max(len(str_1), len(str_2))