## dynamic programming – Fastest Algorithm for Computing Expected Value

I came across this interesting problem:

If π is a finite binary string consisting of just 1’s and 0’s, then denote π(π) as the sum of the squares of the lengths of the consecutive runs of π. For example, π(10001100)=12+32+22+22=18. We can define a string, π by π, the length, and then $$π_1,π_2 cdots π_π$$ where each $$π_π$$ denotes the probability that the πth bit is 1 (and thus, there is a $$1βπ_π$$ chance that said bit is 0).

(a) Exhibit an algorithm, with the best runtime, that gives the expected value of π(π) given the above information (in terms of π).

Other than just bashing through all $$2^π$$ possibilities and calculating π(π), I don’t really see how to calculate the expected value, let alone make the most efficient algorithm. Any ideas would be greatly appreciated.

I originally posted this in Math StackExchange but was told that it’s better suited for here.

## algorithm – fastest way to check for surrounding tiles

I’m working on a tile map where each type of tiles has 12 states with 12 different sprites associated with it, what I’m trying to say is that whenever I place a tile let’s say a road tile, that tile should adjust itself automatically according to the 4 tiles surrounding it, so for example if the tile above it is a road tile and the tile below it is also a road tile, it should automatically adjust itself into a vertical road tile… there is 12 states a tile can have:

1-closed(not surrounded by any similar tile)

2-horizontal(similar tiles up and down)

3-vertical(similar tiles right and left)

4-open from up and left(similar tiles to the left and above)

5-open from left and down(…)

6-open from down and right(…)

7-open from right and up(…)

8-open from up & left & down(3 similar tiles up, left and down)

9-open from left & down & right(…)

10-open from down & right & up(…)

11-open from right & up & left(…)

12-open from all 4 directions(all surrounding tiles are similar)

the problem is that I don’t know how to check for surrounding tiles and choose the right tile state without having a huge mess of if statements and performance waste, and I don’t have enough experience with algorithms and data structures to figure it out myself.

how can check all 12 states the fastest way possible ?

thanks!

## oracle – Select arbitrary single value for GROUP BY: What’s the fastest option?

I have a query that I use to indicate locations in a map where there are overlapping points:

``````select
min(objectid) as min_objectid,
longitudex,
latitudey,
count(1) as count,
min(shape) as min_shape
from
workorders
group by
longitudex,
latitudey
having
count(1) > 1
``````

In the mapping software that I use, I need to include columns like `objectid` and `shape`. For those columns, it doesn’t matter which of the grouped-by rows the values come from, just as long as there is a value.

Presently, I’m using `min()` to get an arbitrary value for those columns. However, I don’t know if that’s the fastest option since finding the minimum value would require calculation β and I wonder if that time spent is unnecessary.

What is the fastest option for getting an arbitrary/single value for GROUP BY in an Oracle query?

## filesystems – What is the fastest way to append writes to a file?

What is the fastest way to append 4KB writes to a file ?

I tried concurrently writing 4KB from multiple threads with each thread tracking its offset in file. No data is corrupted or writes are lost. But 4 writer threads are slower than 1 writer thread. Disk utilization is also not different.

I then tried writes on a preallocated file which already has 4 GB data and then writing to it. Single writer thread is faster than appending to empty file. Even in preallocated case, 4 writer threads are slower than 1 writer thread.

``````#include <fstream>
#include <vector>
#include "gtest/gtest.h"

void write_concurrently(string filename, const int data_in_gb, const int num_threads, const char start_char,
bool stream_cache = true) {
const int offset = 4 * 1024;
const long long num_records_each_thread = (data_in_gb * 1024 * ((1024 * 1024)/ (num_threads * offset)));

{
auto write_file_fn = (&)(int index) {
// each thread has its own handle
fstream file_handle(filename, fstream::in  | fstream::out | fstream::ate | fstream::binary);
if (!stream_cache) {
file_handle.rdbuf()->pubsetbuf(nullptr, 0); // no bufferring in fstream
}

file_handle.seekp(0, ios_base::beg);

vector<char> data(offset, (char)(index + start_char));
long long myoffset = index * offset;

for (long long i = 0; i < num_records_each_thread; ++i) {
file_handle.seekp(myoffset, ios_base::beg);
file_handle.write(data.data(), offset);
}

// file_handle.flush();
};

auto start_time = chrono::high_resolution_clock::now();
for (int i = 0; i < num_threads; ++i) {
}

for (int i = 0; i < num_threads; ++i) {
}

auto end_time = chrono::high_resolution_clock::now();

std::cout << "Data written : " << data_in_gb << " GB, " << num_threads << " threads "
<< ", cache " << (stream_cache ? "true " : "false ") << ", size " << offset << " bytes ";
std::cout << "Time taken: " << (end_time - start_time).count() / 1000 << " micro-secs" << std::endl;
}

{
ifstream file(filename, fstream::in | fstream::binary);
file.seekg(0, ios_base::end);
file.seekg(0, ios_base::beg);
EXPECT_TRUE(file);

char data(offset){ 0 };
for (long long i = 0; i < (num_records_each_thread * num_threads); ++i) {
EXPECT_TRUE(file || file.eof()); // should be able to read until eof
char expected_char = (char)((i % num_threads) + start_char);

bool same = true;
for (auto & c : data) {
same = same && (c == expected_char);
}

EXPECT_TRUE(same);
if (!same) {
std::cout << "corruption detected !!!" << std::endl;
break;
}

if (file.eof()) {
break;
}
}
}
}
// analysis: Possible but multiple thread is slower because of exlsuive locking in filesystem : ExAcquireResourceExclusiveLite
//Name                                                          Inc %        Inc    Exc %      Exc  Fold                                 When     First        Last
//module ntoskrnl << ntoskrnl!ExAcquireResourceExclusiveLite >> 11.5       1, 030    11.5    1, 030    3     1o010___110110110___11011011____    63.097  12, 941.694
//+ module ntfs.sys << ntfs!NtfsCopyWriteA >> 7.7        693      0.0        0     0     00000___00000010o___01o10000____    63.097  12, 941.694
//| +module fltmgr.sys << fltmgr!FltpFastIoWrite >> 7.7      693      0.0        0     0     00000___00000010o___01o10000____    63.097  12, 941.694
//| +module ntoskrnl << ntoskrnl!NtWriteFile >> 7.7      693      0.0        0     0     00000___00000010o___01o10000____    63.097  12, 941.694
//+ module ntfs.sys << ntfs!NtfsFsdWrite >> 3.8      337      0.0        0     0     o0000___00o00o00o___00o00o00____    68.759  12, 912.626
//+ module ntoskrnl << ntoskrnl!IofCallDriver >> 3.8         337      0.0        0     0     o0000___00o00o00o___00o00o00____    68.759  12, 912.626
//+ module fltmgr.sys << fltmgr!FltpDispatch >> 3.8      337      0.0        0     0     o0000___00o00o00o___00o00o00____    68.759  12, 912.626
//+ module ntoskrnl << ntoskrnl!NtWriteFile >> 3.8       337      0.0        0     0     o0000___00o00o00o___00o00o00____    68.759  12, 912.626

TEST(fstream, write_concurrently_to_same_file) {
string filename = "file4.log";
long data_in_gb = 4;
{
// create file before write threads start.
{
fstream file(filename, fstream::in | fstream::out | fstream::trunc | fstream::binary);
}
write_concurrently(filename, data_in_gb, 1, 'A'); // concurrent is slower than 1 thread
}

{
// create file before write threads start.
{
fstream file(filename, fstream::in | fstream::out | fstream::trunc | fstream::binary);
}
write_concurrently(filename, data_in_gb, 4, 'A'); // concurrent is slower than 1 thread
}

std::remove(filename.c_str());
}

// Preallocated file
TEST(fstream, preallocated_file_concurrent_writes) {
string filename = "file5.log";
const int data_in_gb = 4;
{
// create file before write threads start.
fstream file(filename, fstream::in | fstream::out | fstream::trunc | fstream::binary);
write_concurrently(filename, data_in_gb, 1, 'A');
}

std::cout << "Preallocated file." << std::endl;
write_concurrently(filename, data_in_gb, 1, 'B');
write_concurrently(filename, data_in_gb, 4, 'C');

std::remove(filename.c_str());
}
``````
``````Running main() from gtest_main.cc
Note: Google Test filter = *write_concurrently_to_same_file
(==========) Running 1 test from 1 test case.
(----------) Global test environment set-up.
(----------) 1 test from fstream
( RUN      ) fstream.write_concurrently_to_same_file
Data written : 4 GB, 1 threads , cache true , size 4096 bytes Time taken: 21895907 micro-secs
Data written : 4 GB, 4 threads , cache true , size 4096 bytes Time taken: 30937922 micro-secs
(       OK ) fstream.write_concurrently_to_same_file (84657 ms)
(----------) 1 test from fstream (84658 ms total)

(----------) Global test environment tear-down
(==========) 1 test from 1 test case ran. (84660 ms total)
(  PASSED  ) 1 test.

>.x64Releasetests.exe --gtest_filter=*preallocated_file_concurrent_writes
Running main() from gtest_main.cc
Note: Google Test filter = *preallocated_file_concurrent_writes
(==========) Running 1 test from 1 test case.
(----------) Global test environment set-up.
(----------) 1 test from fstream
( RUN      ) fstream.preallocated_file_concurrent_writes
Data written : 4 GB, 1 threads , cache true , size 4096 bytes Time taken: 20529264 micro-secs
Preallocated file.
Data written : 4 GB, 1 threads , cache true , size 4096 bytes Time taken: 15053958 micro-secs
Data written : 4 GB, 4 threads , cache true , size 4096 bytes Time taken: 16394996 micro-secs
(       OK ) fstream.preallocated_file_concurrent_writes (87653 ms)
(----------) 1 test from fstream (87654 ms total)

(----------) Global test environment tear-down
(==========) 1 test from 1 test case ran. (87659 ms total)
(  PASSED  ) 1 test.
``````

I looked at profile and one difference i noticed was lock acquire fn showing up in multi threads case.

``````// analysis: Possible but multiple thread is slower because of exlsuive locking in filesystem : ExAcquireResourceExclusiveLite
//Name                                                          Inc %        Inc    Exc %      Exc  Fold                                 When     First        Last
//module ntoskrnl << ntoskrnl!ExAcquireResourceExclusiveLite >> 11.5       1, 030    11.5    1, 030    3     1o010___110110110___11011011____    63.097  12, 941.694
//+ module ntfs.sys << ntfs!NtfsCopyWriteA >> 7.7        693      0.0        0     0     00000___00000010o___01o10000____    63.097  12, 941.694
//| +module fltmgr.sys << fltmgr!FltpFastIoWrite >> 7.7      693      0.0        0     0     00000___00000010o___01o10000____    63.097  12, 941.694
//| +module ntoskrnl << ntoskrnl!NtWriteFile >> 7.7      693      0.0        0     0     00000___00000010o___01o10000____    63.097  12, 941.694
//+ module ntfs.sys << ntfs!NtfsFsdWrite >> 3.8      337      0.0        0     0     o0000___00o00o00o___00o00o00____    68.759  12, 912.626
//+ module ntoskrnl << ntoskrnl!IofCallDriver >> 3.8         337      0.0        0     0     o0000___00o00o00o___00o00o00____    68.759  12, 912.626
//+ module fltmgr.sys << fltmgr!FltpDispatch >> 3.8      337      0.0        0     0     o0000___00o00o00o___00o00o00____    68.759  12, 912.626
//+ module ntoskrnl << ntoskrnl!NtWriteFile >> 3.8       337      0.0        0     0     o0000___00o00o00o___00o00o00____    68.759  12, 912.626
``````

Current test runs are in windows.

## algorithms – Fastest way to determine constrained sum of an array

I have two $$N$$-vectors of positive integers, called `cost` and `gain`, and I have another integer called `budget`. You can think of every pairwise correspondence between `cost` and `gain` as a stock, and every possible subset of stocks as a portfolio.

I need to determine the portfolio (subset of pairwise correspondences) whose sum of gains is maximised, given that the corresponding sum of costs is smaller than `budget`. Every stock can appear only once in the portfolio.

Example:

``````budget = 5, cost = (1,2,17,4), gain = (5,9,100,2)
``````

The third element must be discarded because it doesn’t fit in the budget, while the best subset is given by first plus second, because the cumulative gain would be 14 for an expense of 3, while the other subset first plus fourth would respect the budget but gain less.

I approached the problem thinking to extract all the subsets contained in the power set of integers from 1 to N with at least one element, that is, all the ordered sequences of indices from 1 to N with length varying from 1 to N. This would correspond to all the possible portfolios, let’s say. However, it turned to be too slow, because of nested loops.

I feel like this must be some classical problem in Algorithms, but I never studied this subject and I have just the sensation that there must be some kind of Dynamical Programming like solution. What is the fastest solution to this problem?

## What is the fastest way to get ‘is_active’ column value from ‘customer_entity" table?

I’d like to ask for the fastest way to get the column value of ‘is_active’ from ‘customer_entity’ table. It could be using object_manager or something.

## usa – How can I find the fastest path by car to reach a US state from a given US location?

#### Stack Exchange Network

Stack Exchange network consists of 176 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

## dnd 5e – What is the Fastest a Character Can Move in One Turn?

The fastest single round movement speed is one of 3 answers. The fastest is the 303-Monk which has to be lightly beaten until launch.

Using a friendly Transmuter plus magic item property rules – 16,800 feet flying, but all you can do is move and it also requires a friendly Transmuter to flog until ready to maintain Rage whilst the Abjurer Ward covers the HP damage. The 303-Monk covers 3.03miles at Mach 2.37 and is quite angry when it arrives.

Using a friendly Transmuter and only the printed magic items – 16,000 flying

Just by themselves means losing Elk Rage and dropping Monk FM to +10 – 15,400 flying or 14,800 if we forego the Magic Item qualities too

Just by themselves and no Wind Walk has a different build utilizing Druid Wild Shaping and Potion of Speed. This gets – Land 6,800, Swimming 6,800, Climbing 6,000, Burrowing 5,000, Potion of Flying 6,800

Same Druid, but no +5 or +10 speed magic items – 6,200/6,200/5,400/4,400/6,200

Fastest Speed Build – Solo and no Wind Walk
Tabaxi – Wizard 7, Barbarian 5, Druid 4, Fighter 2, Rogue 2
Race – Double speed
Feats – Mobile +10
Class – Barbarian Elk Rage +15, Barbarian Fast Movement +10, Fighter Action Surge +Dash, Cunning Action +Dash
Spells – Longstrider +10, Potion of Speed +Dash & Double Speed, Wind Walk 300ft speed
Objects – Boots of Speed Double Speed, +5 Minor Magic Item Quality, +10 Major Magic Item Quality, +10 Transmuter, Potion of Flying
Boon – Speed +30

Base Movement: 170 feet
60 +10+15+10+10+10+5+10+10+30

Speed Multipliers: 1,360 feet
Boots x2
Haste x2
Tabaxi x2

Number of Moves: 5 x 1,360 = 6,800
Move = 1
Action +1
Bonus (ER or CA) +1
Haste Extra Action +1
Action Surge +1

Fastest Speed Build – Wind Walk + Friendly Transmuter
Tabaxi – Rogue 2, Fighter 2, Elk-Barbarian 5, Monk 11
Race – Double speed
Feats – Mobile +10
Class – Barbarian Elk Rage +15 (walking only), Barbarian Fast Movement +10, Fighter Action Surge +Dash, Monk Unarmored Movement +20
Spells – Cunning Action +Dash, Longstrider +10, Haste +Dash & Double Speed, Wind Walk 300ft speed (unlcear: “While in this cloud form, a creature has a flying speed of 300 feet” – that wording implies that your fly speed DECREASES to 300 if its more than that.)
Objects – Boots of Speed Double Speed (walking only), +5 Minor Magic Item Quality(if you make your own), +10 Major Magic Item Quality (if you make your own), +10 Transmuter
Boon – Speed +30

Base Movement: 420 feet
300 +10+15+10+20+10+5+10+10+30

Speed Multipliers: 3,360 feet
Boots x2
Haste x2
Tabaxi x2

Number of Moves: 5 x 3,360 = 16,800
Move = 1
Action +1
Bonus (CA) +1
Haste Extra Action +1
Action Surge +1

## budget – What is the cheapest / fastest way to get from Brussels to Paris?

Thalys is definitely the fastest way of getting from Brussels to Paris. You can buy tickets directly at the Thalys website. You can also buy them at the Belgian (SNCB) or French (SNCF) railway companies. The prices are in principle identical.

The trip by bus takes around 5 hours, to be compared to the 1h20 of the train trip. Apart from Eurolines you can use iDBUS. The prices are more or less the same. I have checked for a departure in 2 days. Eurolines is 25 EUR and iDBUS varies between 15 and 33 EUR depending on the departure time. Thalys starts at 79 EUR on that particular day.

In case you are unable to choose among the two bus companies, note that they are using different terminals in Brussels and Paris. Choose whichever suits you best.

It is possible to travel by “classical” trains from Brussels to Paris. But this is neither a real bargain nor is it really fast, as documented in another post. It takes around 5h30, involves three train changes (Tournai, Lille and Amiens) and costs around 65 EUR (45 EUR if you are less than 26 years old).