# Questions tagged [optimization]

19755 questions

0

votes

2

answer

21

Views

### fastest way to minimize n as per given condition in python

how can i make the following code faster? the input is a binary string and i am converting it to a number. possibly i need to use the binary string instead of the number? the algorithm may only divide by 2 or subtract 1 from the input. I tried the code below and it is not fast enough.
I tried the b...

2

votes

0

answer

19

Views

### What's the most optimal query in PgSql to find the nearest neighbor in a huge dataset?

I have a huge table (about 40 Millions rows) called nearest_spot representing lines (in the linestring format) and the closest spot they're to (there is about 1500 different spot, stored in another table). The nearest_spot table comes like this :
data_id || spot_id || spot_name || link_geom
Where d...

1

votes

2

answer

132

Views

### Python re.sub() optimization

I have a python list with each string being one of the following 4 possible options like this (of course the names would be different):
Mr: Smith\n
Mr: Smith; John\n
Smith\n
Smith; John\n
I want these to be corrected to:
Mr,Smith,fname\n
Mr,Smith,John\n
title,Smith,fname\n
title,Smith,John\n
Easy en...

1

votes

1

answer

203

Views

### GCC Auto Vectorization

In gcc compiler is there a way to enable auto vectorization only? I do know that -ftree-vectorize flag enables auto vectorization. But it requires at least -O2 optimization level. Is there a way to enable auto vectorization without using the -O2 optimization flag?
Thanks in advance.

1

votes

1

answer

34

Views

### Optimize an existing for-loop over three arrays

I have three lists/arrays: one is a list of boolean values, the other two are arrays with certain values.
My goal is to loop through the boolean list and if the value is true take the j-th value of the first array and safe it in the solution array, and if the value is false take the j-th value of th...

1

votes

1

answer

436

Views

### What are the limits of docplex (the cplex version of python) in terms of the number of variables and constraints?

I am solving an optimization problem in python using docplex(not docplex cloud API) with only 2 constraints and 92 variables (dvar in OPL). But even though I get this error:
docplex.mp.utils.DOcplexLimitsExceeded: **** Promotional version. Problem size limits exceeded, CPLEX code=1016
I would like...

1

votes

1

answer

823

Views

### What is Cognitive Complexity in sonar report?

Now a days i switched to sonar reports for static code review and performance improvement. Under the rules section I found that the cognitive complexity of my methods are high.
You can find cognitive complexity error in sonar as:
Go to Project->Issues Tab->Rules Drop-down->Cognitive Complexity
Below...

1

votes

1

answer

164

Views

### What is the difference between SAT and linear programming

I have an optimization problem that is subjected to linear constraints.
How to know which method is better for modelling and solving the problem.
I am generally asking about solving a problem as a satisfiability problem (SAT or SMT) vs. Solving as a linear programming problem (ILP OR MILP).
I don't...

1

votes

2

answer

110

Views

### Mathematical solution to split X teams into 3 Teams per day

I am trying to split X number of Teams into 'play days' which consist of 3 teams per day
There is more than one solution to solve this for 15 teams.
What is the best approach to find all possible fixtures/match plans for team count 9-21?
Team count of 11, 14, 17 and 20 also cause problems, because t...

1

votes

1

answer

35

Views

### Minimum number of vertices whose removal makes the graph no longer connected

Given a undirected and connected graph G = (V, E). Find the minimum number of verticies whose removal make the graph no longer a connected graph.

1

votes

4

answer

54

Views

### ORACLE LIKE with multiple values

I have the below query in ORACLE which takes a really long time to run because of the OR in between the 2 likes.
select pat_mrn_id,surgery_date, proc_name
from or_log_all_proc, or_proc, or_log, patient
where
upper(proc_name) like ('%CRANIOTOMY ANEURYSM%') OR upper(proc_name) like
('CLIPPING%ANE...

1

votes

2

answer

71

Views

### Best practice: how to pass many many arguments to a function?

I am running some numerical simulations, in which my main function must receive lots and lots of arguments - I'm talking 10 to 30 arguments depending on the simulation to run.
What are some best practices to handle cases like this?
Dividing the code into, say, 10 functions with 3 arguments each does...

1

votes

2

answer

48

Views

### Using a spatial index to find points within range of each other

I'm trying to find a spatial index structure suitable for a particular problem : using a union-find data structure, I want to connect\associate points that are within a certain range of each other.
I have a lot of points and I'm trying to optimize an existing solution by using a better spatial inde...

1

votes

2

answer

69

Views

### Powershell - Fastest way to create a very large array of hashtables

I am trying to create a rather large array of hashtables, with much of the data either fully randomized or randomly picked from a list.
Here is my Current Code
$ArrayData = @()
$ArrayDataRows = 150000
foreach ($i in 1..$ArrayDataRows) {
$thisobject = [PSCustomObject] @{
Number = $i
Place = Get-Rando...

1

votes

1

answer

43

Views

### Space / time requirements for ISO-Prolog processor compliance

All implementations of the functional programming language scheme are required to perform tail-call-optimization whenever it is applicable.
Does iso-prolog have this one and / or similar requirements?
It's clear to me that Prolog processor features like first argument principal functor indexing and...

1

votes

1

answer

55

Views

### How to turn this code into a 1 liner without losing efficiency?

to improve the readability, I'd like to turn this code into a 1-liner.
The variable tup_ranges is a a tuple of 2 values, e.g. (20, 40). If the value of elt is included in this range, then the key corresponding to this value n is retrieved.
identification = dict()
for elt in combination:
for n, tup_...

1

votes

2

answer

398

Views

### More efficient to check if a variable is set, then set it, or just constantly set it?

Making a game... More efficient to do this?
if (37 in keysDown) { //left arrow
if (sprite.state != 'left') sprite.state = 'left';
}
or this?
if (37 in keysDown) { //left arrow
sprite.state = 'left';
}
This is being called in my game's update function (constantly, as fast as possible).
Sidenote:
her...

1

votes

3

answer

1.4k

Views

### Stopping MySQL query after the first row [closed]

I have a piece of MySQL code that searches through a quite lengthy mysql database. When done multiple times, it takes a long time, although the only thing I need from the code is to check the existence of at least one entry. Is it possible to instruct the mysql code to stop searching after finding o...

1

votes

1

answer

1.3k

Views

### Optimal Length of a Python Function (Style) [closed]

Perhaps this is not the correct place to ask this question, and part of me thinks that there is no real answer to it, but I'm interested to see what experienced Python users have to say on the subject:
For maximum readability, concision, and utility, what is a range for an optimal length of a Pyth...

0

votes

0

answer

9

Views

### TypeError: 'int' object is not subscriptable: adding a column with a calculation

I have found the code of a bisection method in Python. This is a method to find the root of a function. This function depends on several variables. The function and the bisection method works perfect. However, I now created a dataframe with multiple rows (>1000) where I want to apply the function to...

0

votes

1

answer

59

Views

### Constrain logic in Linear programming

I'm trying to build a linear optimization model for a production unit. I have Decision variable (binary variable) X(i)(j) where I is hour of J day. The constrain I need to introduce is a limitation on downtime (minimum time period the production unit needs to be turned off between two starts).
For e...

-1

votes

1

answer

79

Views

### Simplify/Optimize Regex in Java

I am using a Java-based machine learning library. The library provides a method called readInstances to input data, preprocess it and then classify it. For its parameters, the method readInstances takes FileReader, Pattern and an array of integers which are the indices of fields of interest in each...

1

votes

2

answer

316

Views

### What x86 32 bit peepholes does GCC perform?

I've been browsing through the GCC source code and I've been stumped on how to extract these. Can anyone provide a list or information on how to extract these peepholes (assembly rewrite optimizations)?
GCC code: https://github.com/gcc-mirror/gcc
Edit: To clarify, a 'peephole' is defined to be a fin...

7

votes

2

answer

260

Views

### Minimize quadratic function subject to linear equality constraints with SciPy

I have a reasonably simple constrained optimization problem but get different answers depending on how I do it. Let's get the import and a pretty print function out of the way first:
import numpy as np
from scipy.optimize import minimize, LinearConstraint, NonlinearConstraint, SR1
def print_res( re...

6

votes

0

answer

104

Views

### How can I optimize parallel sorting to improve temporal performance?

I have an algorithm for parallel sorting a list of a given length:
import Control.Parallel (par, pseq)
import Data.Time.Clock (diffUTCTime, getCurrentTime)
import System.Environment (getArgs)
import System.Random (StdGen, getStdGen, randoms)
parSort :: (Ord a) => [a] -> [a]
parSort (x:xs) = force...

1

votes

1

answer

231

Views

### Call non-static function in constructor initialization list, C++

I am currently optimizing my code, and I came to a point where I was tempted to use the following pattern when initializing my class:
class MyClass
{
MyClass(int x) :
_x(x),
_collection(createCollection())
{
}
int functionThatDependsOnTheStateOfTheClass() const
{
return _x;
}
private:
std::vector cr...

4

votes

4

answer

148

Views

### Fast way to find all vectors similar to a given one

By 'similar vector' I define a vector that differs from a given one at just one position by either -1 or 1. However, if the element of the given one is zero, only difference by 1 is possible. Examples:
similar_vectors(np.array([0,0,0]))
array([[ 1., 0., 0.],
[ 0., 1., 0.],
[ 0., 0., 1.]])
simi...

1

votes

2

answer

50

Views

### Issue in comparing double values with ISNULL

I am working on an assignment where I need to compare three revenue fields between two tables and when any of them are different, I need to update the value from table1 into table2.
My update query is below.
UPDATE OP
SET OP.CompCanceledRevenue = OPW.Comp_Canceled_Revenue__c,
OP.PriorYearOperatingRe...

1

votes

1

answer

176

Views

### How to find upper and lower bounds of a function in R

I am wanting to try find the upper and lower bounds of a function in R.
I am trying to use the built in R function 'optimise', but the function tries to find where the function's tangent is zero. For instance, if you run the following code:
phi_function

1

votes

2

answer

81

Views

### How to optimize to a string-rewriting rules program

I have this small program that keeps rewriting the same string
string a = 'aRbFR';
string b = 'LFaLb';
string str = 'Fa';
for (; n < 50; ++n)
{
for(Int64 i = 0; i < str.Length; ++i)
{
if (i < str.Length && str[(int)i] == 'a')
{
str = str.Remove((int)i, 1);
str = str.Insert((int)i, a);
i += a.Length;...

1

votes

2

answer

117

Views

### A faster way of generating combinations with a given length, preserving the order

TL;DR: I want the exact behavior as filter ((== 4) . length) . subsequences. Just using subsequences also creates variable length of lists, which takes a lot of time to process. Since in the end only lists of length 4 are needed, I was thinking there must be a faster way.
I have a list of functions....

1

votes

6

answer

154

Views

### Relying on compiler optimizations with C++ [closed]

Question: is it OK to rely on compiler optimizations while coding?
Let's say I need to calculate calculateF and calcuateG which both depend on another value returned by getValue. Sometimes I need both values, some other times I only need one of those values.
// some function
double getValue(double v...

1

votes

3

answer

114

Views

### Is there a way to optimize this function?

For an application I'm working on, I need to take two integers and add them together using a particular mathematical formula. This ends up looking like this:
int16_t add_special(int16_t a, int16_t b) {
float limit = std::numeric_limits::max();//32767 as a floating point value
float a_fl = a, b_fl =...

1

votes

2

answer

44

Views

### Is it possible to change logical operator of the conditional statement in js programmatically?

I have two almost identical functions except for one difference, the logical operator in if.
I cannot write

1

votes

3

answer

87

Views

### How to save a matrix in C++ in a non-linear way

I have to program an optimized multi-thread implementation of the Levenshtein distance problem. It can be computed using dynamic programming with a matrix, the wikipedia page on Levenshtein distance covers that well enough.
Now, I can compute diagonal elements concurrently. That is all alright.
My...

1

votes

3

answer

45

Views

### MySQL- Improvement on count(*) aggregation with composite index keys

I have a table with the following structure with almost 120000 rows,
desc user_group_report
+------------------+----------+------+-----+-------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------+----------+------+-----+-----------------...

0

votes

4

answer

24

Views

### optimize 32-bit value construction

So, I have the following code:
uint32_t val;
if (swap) {
val = ((uint32_t)a & 0x0000ffff) | ((uint32_t)b

0

votes

0

answer

10

Views

### Optimize for runtime

The following code takes in two params. An array of sentences and an array of queries. Each query has one or more words. The function below prints out index of sentence for each query that has all the words in that sentence.
This is functioning code. However, it is not optimized for large inputs bec...

1

votes

1

answer

37

Views

### Minimizing Function with vector valued input in MATLAB

I want to minimize a function like below:
Here, n can be 5,10,50 etc. I want to use Matlab and want to use Gradient Descent and Quasi-Newton Method with BFGS update to solve this problem along with backtracking line search. I am a novice in Matlab. Can anyone help, please? I can find a solution for...

1

votes

5

answer

105

Views

### Python, iterating and modifying DataFrames in a dictionary of df's

Coming from a C# background (years ago) and being very new to Python I'm struggling to optimise my code. Literally just learned that for loops are very slow.
In the code below the loop that adds a calculated column to each DataFrame in the Dict appears to be a huge bottleneck.
I've read up on ways t...