Find the minimum unused value greater than MIN and smaller than MAX of the array. A negative value in the array marks the end of the list of values
int ComputeMinimumUnusedValue(int *TestArray)
{
int FirstValue = 0;
//TODO: Write function that computes minimum unused value > Min and < Max of the array. A negative value in the array marks the end of the list of values.
return(FirstValue);
}
//int TestArray[] = { 5, 87, 30, 145, 241, 245, 110, 1 }; => answer is 6
I have this to do for school and I am trying to do it in O(n). I cannot use any lib. I have been trying for hours different solutions, but I can't do it.
Any of you have any idea?
See also questions close to this topic

Can a concept be checked against incomplete type
I stumbled upon this:
#include <type_traits> #include <concepts> template<class T> concept IsFoo = requires(T a) { {a.a} > std::same_as<int>; }; #if 1 // Will not compile, because Foo currently has incomplete type template<IsFoo AFoo> struct AcceptsFoo {}; #else template<class AFoo> struct AcceptsFoo {}; #endif struct Foo { int a; int b; AcceptsFoo<Foo> obj; };
https://gcc.godbolt.org/z/j43s4z
Other variant (crtp) https://gcc.godbolt.org/z/GoWfhq
Foo is incomplete because it has to instantiate
AcceptsFoo
, but to do so,Foo
has to be complete, otherwise it cannot checkIsFoo
. Is this a bug in GCC, or does the standard say so? The latter would be sad, because this prevents concepts for being used together with some wellknown patterns such ass CRTP.I noticed that clang does gives a similar error: https://gcc.godbolt.org/z/d5bEez

Why do we need function definition before calling it in C++?
Hello to all I am new to C++ language and I came across with interesting fact that we cannot call function before defining it. I have searched on stackoverflow but couldn't find proper answer. I am thinking why just declarations are not enough to call a function because compiler can check the parameter list from declarations.

C++ while loop not terminating even after condition becomes false
I have written a heap building function that builds a max heap in an array. It starts from the last node and checks for each node moving up. It its on node 'a' currently, it checks for left and right children and if they exist and have value greater than 'a' then 'a' is swapped with largest of the immediate child nodes and this continues until the subtree is heapified. I have used a while loop for the trickle down part. It goes on until any of the children nodes have value greater than the current node, or at least it's supposed to. When I use a while loop with this condition, the loop never terminates. However, if I put a breaking if statement with the same condition within the while loop, it works. What's wrong?
void buildHeap(int arr[], int n) { int m= n; while(m){ int i= m; int l= (2*i<=n)?arr[2*i1]:INT_MIN; int r= (2*i+1<=n)?arr[2*i]:INT_MIN; cout<<l<<" "<<r<<endl; while(arr[i1]<l  arr[i1]<r){ // < This doesn't work cout<<i<<endl; if(l>r){ arr[2*i1]= arr[i1]; arr[i1]= l; i= 2*i; } else{ arr[2*i]= arr[i1]; arr[i1]= r; i= 2*i+1; } int l= (2*i<=n)?arr[2*i1]:INT_MIN; int r= (2*i+1<=n)?arr[2*i]:INT_MIN; cout<<(arr[i1]<l  arr[i1]<r)<<endl; //if(!(arr[i1]<l  arr[i1]<r)) break; < This works } m; } for(int i=0; i<n; i++) cout<<arr[i]<<" "; cout<<endl; return; }
I had used a simple example of array {1,2,3} with it. Following is the output.
2147483648 2147483648 < l and r for node 3 2147483648 2147483648 < l and r for node 2 2 3 < l and r for node 1 1 < while loop starts here, i= 1 0 < The value of while loop condition is 0. Still it doesn't terminate. 3 < i= 3 0 < Loop condition still false. 7 0 15 0 31 0 63 0 127 0 255 Segmentation fault (core dumped)

Sorting array by certain value
I am playing around with the API from The Movie Database. I want to list all movies directed by Stanley Kubrick sorted by year descending.
The first part is done and the movies are shown:
A Clockwork Orange The Killing Eyes Wide Shut Full Metal Jacket Dr. Strangelove or: How I Learned to Stop Worrying and Love the Bomb Spartacus Paths of Glory Killer's Kiss Fear and Desire Barry Lyndon The Seafarers Day of the Fight Flying Padre The Shining 2001: A Space Odyssey Lolita
How can I sort the output so that the movies are sorted in descending order? I know I have to use the field "release_date" but I do not know exactly how to do it.
My code so far:
$data = file_get_contents($url); // put the contents of the file into a variable $director = json_decode($data); // decode the JSON feed echo '<pre>'; print_r($director); foreach ($director>crew as $showDirector) { if ($showDirector>department == 'Directing') { echo $showDirector>title . '<br>'; } }
The output of the array:
( [id] => 185 [department] => Directing [original_language] => en [original_title] => A Clockwork Orange [job] => Director [overview] => In a nearfuture Britain, young Alexander DeLarge and his pals get their kicks beating and raping anyone they please. When not destroying the lives of others, Alex swoons to the music of Beethoven. The state, eager to crack down on juvenile crime, gives an incarcerated Alex the option to undergo an invasive procedure that'll rob him of all personal agency. In a time when conscience is a commodity, can Alex change his tune? [vote_count] => 8567 [video] => [poster_path] => /4sHeTAp65WrSSuc05nRBKddhBxO.jpg [backdrop_path] => /wlA20drTwk2lAfypVQykZZR8ful.jpg [title] => A Clockwork Orange [popularity] => 19.484 [genre_ids] => Array ( [0] => 18 [1] => 878 ) [vote_average] => 8.2 [adult] => [release_date] => 19711219 [credit_id] => 52fe4224c3a36847f80071db )
How can I sort that stuff? I am thankful for every hint!

combine specific properties of array of objects
add default value for basis 'Default' if not available in second array when combined
var arrayOne = [{id: 1, name: 'A'},{id:2, name: 'B'},{id:3, name: 'C'},{id:4, name: 'D'},{id:5, name: 'E'}]; var arrayTwo = [{id: 1, basis: 'Online'},{id:3, basis: 'Paper'},{id:4, basis: 'Referrer'}];
Result should be:
var combinedArray = [{id: 1, name: 'A', basis: 'Online'},{id:2, name: 'B', basis: 'Default'},{id:3, name: 'C', basis: 'Paper'},{id:4, name: 'D', basis: 'Referrer'},{id:5, name: 'E', basis: 'Default'}];
I tried
var combinedArray = []; arrayOne.forEach(objOne => { arrayTwo.forEach(objTwo => { if(objOne.id === ObjTwo.id){ combinedArray.push({...objOne,...objTwo}); } }); });
Is there any easy way and faster way to get resulted array without iterating two times with improved performance

ValueError: shapes (2,210) and (2,210) not aligned: 210 (dim 1) != 2 (dim 0)
I want to fit an intensity distribution function to 2D image data using
scipy.optimize.curve_fit
and can't locate the error in my code:# Define doughnut beam intensity distribution function def doughnut(x, y, x0, y0, A, FWHM): '''2D intensity distribution function of doughnut beams (DOI: 10.1126/science.aak9913, https://science.sciencemag.org/content/sci/suppl/2016/12/21/science.aak9913.DC1/Balzarotti_SM.pdf). Parameters  x, y : float X and Y coordinates, orthogonal to beam axis x0 : float X offset y0 : float Y offset A : float Peak intensity FWHM : float Full width at half maximum ''' return A*np.exp(1)*4*np.log(2)*(np.dot(x+x0,x+x0) + np.dot(y+y0,y+y0))/FWHM**2*np.exp(4*np.log(2)*(np.dot(x+x0,x+x0) + np.dot(y+y0,y+y0))/FWHM**2) # Read image file names pathname = '/home/user/doughnut_beam/' filenameList = [filename for filename in os.listdir(pathname) if filename.endswith('.tif')] # Open image files, fit doughnut beam intensity distribution function for filename in filenameList: img = Image.open(pathname + filename) X, Y = img.size xRange = np.arange(1, X+1) yRange = np.arange(1, Y+1) xGrid, yGrid = np.meshgrid(xRange, yRange) xyGrid = np.vstack((xGrid.ravel(), yGrid.ravel())) # scipy.optimize.curve_fit requires 2xNarray imgArray = np.array(img) imgArrayFlat = imgArray.ravel() # Flatten 2D pixel data into 1D array for scipy.optimize.curve_fit params_opt, params_cov = curve_fit(doughnut, xyGrid, imgArrayFlat)
This is the output from Jupyter Notebook:
 ValueError Traceback (most recent call last) <ipythoninput44eaa3ebdb6469> in <module>() 17 imgArrayFlat = imgArray.ravel() # Flatten 2D pixel data into 1D array for scipy.optimize.curve_fit 18 > 19 params_opt, params_cov = curve_fit(doughnut, xyGrid, imgArrayFlat) /usr/lib/python3/distpackages/scipy/optimize/minpack.py in curve_fit(f, xdata, ydata, p0, sigma, absolute_sigma, check_finite, bounds, method, jac, **kwargs) 749 # Remove full_output from kwargs, otherwise we're passing it in twice. 750 return_full = kwargs.pop('full_output', False) > 751 res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs) 752 popt, pcov, infodict, errmsg, ier = res 753 cost = np.sum(infodict['fvec'] ** 2) /usr/lib/python3/distpackages/scipy/optimize/minpack.py in leastsq(func, x0, args, Dfun, full_output, col_deriv, ftol, xtol, gtol, maxfev, epsfcn, factor, diag) 381 if not isinstance(args, tuple): 382 args = (args,) > 383 shape, dtype = _check_func('leastsq', 'func', func, x0, args, n) 384 m = shape[0] 385 if n > m: /usr/lib/python3/distpackages/scipy/optimize/minpack.py in _check_func(checker, argname, thefunc, x0, args, numinputs, output_shape) 25 def _check_func(checker, argname, thefunc, x0, args, numinputs, 26 output_shape=None): > 27 res = atleast_1d(thefunc(*((x0[:numinputs],) + args))) 28 if (output_shape is not None) and (shape(res) != output_shape): 29 if (output_shape[0] != 1): /usr/lib/python3/distpackages/scipy/optimize/minpack.py in func_wrapped(params) 461 if transform is None: 462 def func_wrapped(params): > 463 return func(xdata, *params)  ydata 464 elif transform.ndim == 1: 465 def func_wrapped(params): <ipythoninput433e0adae6fbe0> in doughnut(x, y, x0, y0, A, FWHM) 17 Full width at half maximum 18 ''' > 19 return A*np.exp(1)*4*np.log(2)*(np.dot(x+x0,x+x0) + np.dot(y+y0,y+y0))/FWHM**2*np.exp(4*np.log(2)*(np.dot(x+x0,x+x0) + np.dot(y+y0,y+y0))/FWHM**2) ValueError: shapes (2,210) and (2,210) not aligned: 210 (dim 1) != 2 (dim 0)

Mongo DB  Find between date range with format (ddmmyyyy hh:mm:ss)
I'm need to find documents between a date range, but the date field comes from the API as a String in the next format:
05032020 16:04:17
I've tried doing this:
db.Collection.find({ date: { $gte: "20191201T00:00:00.000Z",$lte: "20200814T23:00:00.000Z" }});
and
db.Collection.find({ date: { $gte: "20191201", $lte:"20200814" }});
but does not match with any documents. I have to say that I cannot change the format of the date field.
Any idea how I can solve this? Thanks in advance.

JavaScript find(), what is the difference of passing {} and without {}?
I have the following example. Both of the find() function works, but I am not sure how the first one with {} is passed into the callback function.
1.If {} is used, I assume an object is passed into the find function, but how does 'title' as an object can be used to compare with values(1.2). Can someone please explain the basics, with reference will be even better.
2.I understand the second find function is passing in object, and arr.title refers to the value inside the object 'array1'. I am right?
const array1 = [{name:1,title:1.1}, {name:2,title:1.2}]; const found = array1.find(({title}) => title ==1.2); const found2 = array1.find(arr => arr.title ==1.2); console.log(found); console.log(found2);
The result of the code above is:
> Object { name: 2, title: 1.2 } > Object { name: 2, title: 1.2 }

Same script is giving result zero on cron where manually getting correct result
#!/bin/bash cd /ad/bd/cd/dd/ed/zd count=$(find . type fcut d "/" f3wc l) echo $count >> /ad/bd/cd/abc.log #exit
Manually it is giving correct value. i.e 230




 ad/bd/script



when above cron running it is giving zero i.e 0


What is the worst case for the following function?
What is the worst case for the following function?
void test(int x) { int k = x * x; int counter = 0; for (int i = 0; i < k; i++) { counter = counter + 1; } return counter; }

find time and space complexity
I need to find the time and space complexity of
f3
. I think thatg
has space complexity oflog(n)
, so for the time complexity, but I am not really sure how I find the time and space complexity off3
because the calling forg
is inside thefor
commend, does it mean theg
is being called every time to check ifg(i) < n
?int g(int n) { if (n <= 1) return 1; return g(n / 2) + 1; } int f3(int n) { int counter = 0; for (int i = 0; g(i) < n; ++i) ++counter; return counter; }

Why selection best case is not O(n)
I have read many topics which people usually say that Selection sort's complexity in best case is still O(n^2). But I coundn't be convinced by those ideas. For instance, I want to sort the array in ascending order. And this is my algorithm in Java code:
void selectionSort(int[] arr) { int min, temp; int length = arr.length; for (int i = 0; i <= length  1; i++) { //System.out.println(i); min = i; for (int j = i+1; j < length ; j++) { if (arr[j] < arr[min]) { min = j; } } if (min != i) { temp = arr[min]; arr[min] = arr[i]; arr[i] = temp; } else { break; } } }
I believe this is O(n) in best case, which is the input arrray is already sorted. One additional thing I added here to the algorithm is to check if (min == i) and break the loop. What do you think? Am I wrong?

How can I access latitude and longitude after calculating distance and checking whis one closer?
I have a list of points, called intersect. This list is order like this:
latitudePoint1,longitudePoint1,latitudePoint2,longitudePoint2,latitudePoint3,longitudePoint3,...
So that the latitude and longitude of the same point have different indexes. I calculate the distance of those points to an fixed point and then I need to check which one of those points is closest to the fixed point(hardcoded). I try to explain everything better with comments bellow:
List<double> distanciasOcorrenciaIntersecao = new List<double>(); for (int i = 0; i <= intersect.Count(); i++) { //get latitude double intLat = intersect[2 * i]; //get longitude double intLong = intersect[2 * i + 1]; //calculates the distance between the fixed point and the point of the list intersect var distancia = GetDistance(FixedLatitude, FixedLongitude, intLat.ToString(), intLong.ToString()); //Add the latitude and longitude and long as the distance calulated to another list distanciasOcorrenciaIntersecao.Add(intLat); distanciasOcorrenciaIntersecao.Add(intLong); distanciasOcorrenciaIntersecao.Add(distancia); }
Now I need to check which one of the distances added to the list distanciasOcorrenciaIntersecao is the closer to the fixed point and then return the latitude and longitude associated with that distance.
Here is what I've done so far:
for (int j = 0; j <= distanciasOcorrenciaIntersecao.Count(); j++) { // I need to at least have two point in the intersect list, // meaning 4 elements, latitude1,longitude1,latitude2,longitude2 if (intersect.Count() >= 4) { if (distanciasOcorrenciaIntersecao[3 * j + 2] < distanciasOcorrenciaIntersecao[3 * j + 5]) { //....? } } } }
I'm not sure if this is the best approach to this problem, but if someone knows a better way to do this, please help. Thank you

How to get minimum values key from hash in Perl
I have script which is able to pick minimum value from hash values.
use strict; use warnings; use Data::Dumper; use List::Util qw(min); my @array = qw/50 51 52 53 54/; my $time = 1596561300; my %hash; foreach my $element(@array){ $hash{$time} = $element; $time += 6; #based on some condition incrementing the time to 6s } print Dumper(\%hash); my $min = min values %hash; print "min:$min\n";
Here I am able to get
50
as a minimum value out of all the values in hash values. But how would I also get the hash key that corresponds to the minimum value, i.e.,1596561300
. 
Python: Get the lowest, most frequent value of a list
Hi Community! Could You please help me regarding following issue? I do not manage do achieve an efficient solution for my problem. Any help is highly appreciated! Thanks to all of You in advance!
My Problem: As first step, I would like to identify the most frequent value(s) of a given list of integers. As second step, if there are multiple most frequent values, I would like to take the lowest among them.
Example: Given following list, I would like to receive the "5", as it is the lowest, most frequent value.
list = [1,2,3,4,5,5,5,6,6,6,7,7,8,8,8]
Could You please help me? Thanks!