# Questions tagged [optimization]

19755 questions

2

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...
zelda1234

0

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...

2

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...
t.r.orion

1

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.
Pasindu

1

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...
zeniapy

1

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...
sel

1

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...
Akshay Paliwal

1

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...

2

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...
Vid Man

1

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.
dandoh

4

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...
JHegde

2

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...

2

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...
Jean-Pierre Coffe

2

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

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...
repeat

1

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_...
Mathieu

2

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...
Sam

3

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...
user1784397

1

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...
austin_sherron

0

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...

1

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...
Karthik K S

1

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...
Michael

2

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...
Daryl

2

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...
JohnE

0

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...
Vasiliy

1

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-bit

4

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...
WojciechR

2

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...
Balaji Pooruli

1

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
user-2147482565

2

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;...
Greggz

2

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....
iovo

6

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...
MFnx

3

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 =...
Xirema

2

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
ezik

3

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...
Jan Kolombo

3

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 | +------------------+----------+------+-----+-----------------...
Coder 477

4

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
Mark

0

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...
jisu

1

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...
kayas

5

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...
DublinMeUp