w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Find the largest sum including at most two consecutive elements from an array
I would imagine putting the array into a binary tree in that order. That way you can keep track of which element is next to each other. Then just simply do an if (node is not directly linked to each other) to sum the nodes which are not next to each other. You can potentially do it with recursion and return the maximum number, makes things easier to code. Hope it helps.

Categories : Java

Matlab, Find cell elements
You can do this really simply, use the code below indices = cell(size(B)); for i = 1:numel(B) indices{i} = find(strcmpi(A,B(i))); end While I do recommend using ismember or intersect, those solutions will not handle case insensitive solutions. Also, those methods will not indicate how many times a specific index was matched, where my solution, will return all indices that match for each comparison. UPDATE Code I am running to test this. A={'aaaa','bbbb','cccc','dddd','ffff','aaaa'}; B={'ffff','aaaa','cccc','qwerty'}; indices = cell(size(B)); for i = 1:numel(B) indices{i} = find(strcmpi(A,B(i))); end indices Which returns the following indices = [5] [1x2 double] [3] [1x0 double] I do not see where you are having problems

Categories : String

How to find the complexity of a program to find the length of the largest sub string?
You have two nested loops of order n (where n is the length of string), so is O(n*n) = O(n2). There are some other operations which are not important in calculating big O, e.g Split, takes O(n), but compare to O(n2) is not important, or push and pop, ... in each for loop takes O(1), but it's not important if we have multiple O(1) operations. For elaboration: We know that the first loop runs n times, but about the second loop, it will run O(n-i) time, so total running time is: Σ(n-i) = Σ n - Σ i = n2 - n(n-1)/2 = O(n^2).

Categories : Algorithm

Largest elements in an array
As your name says, it is simple x) The first dimension is the 30 in your example, the second 2. That is, the convention is as follows: 1st x 2nd x 3rd x 4th x nth dimension. We also call the 1st dimension as lines and the second as columns because that is how we are used to draw the matrices. I.e, suppose a matrix in matlab A, with dimensions nxm: A = 1st column 2nd column 3rd column … mth column 1st line A(1,1) A(1,2) A(1,3) … A(1,end) 2nd line A(2,1) A(2,2) A(2,3) … A(2,end) . . . . … . . . . . … . . . . . … . 2nd line A(end,1) A(end,2) A(end,3) … A(end,end) So using max on fi

Categories : Matlab

Finding a list of all largest open rectangles in a grid by only examining a list of "open" indices
Of course. To find a rectangle: Start with any free cell. Assume this is going to be the upper-left corner. See if it can be extended horizontally. See if it can be extended vertically. Backtrack. I'll ellaborate on this later, but thought this could give you a jump-start.

Categories : Arrays

Set height of 3 elements, taking largest value, across multiple rows
Try var $sections = $('.section-title'); $sections.filter(':nth-child(3n-2)').each(function () { var $this = $(this), $els = $this.nextAll(':lt(2)').addBack(); var sectionheight = new Array(); $els.each(function () { var value = $(this).height(); sectionheight.push(value); }); var newsectionheight = Math.max.apply(Math, sectionheight); $els.height(newsectionheight); }) Demo: Fiddle

Categories : Javascript

Does a VAO remember both a EBO/IBO (elements or indices) and a VBO?
Addressing your questions: A. Do I need to bind the IBO after I set the VertexAttribPointers? If so, why? No. You could bind the element array (IBO in your terminology) first, and do the vertex attributes later, but generally speaking, they're separate bindings within the VAO. For example, you could bind your IBO as well as several VBOs, and render with either glDrawElements (and variants) using the data in the IBO, or using glDrawArrays (and variants) using only the sequential vertex data in your VBOs - the rendering command determines if the IBO is used or not. B. Does the VAO really store both the VBO and the IBO? Yes. A VAO can store the binding information for a single IBO, and at least 16 VBOs. I've heard it only stores the last buffer that was bound, meaning I hav

Categories : C++

How to find pair with kth largest sum?
I start with a simple but not quite linear-time algorithm. We choose some value between array1[0]+array2[0] and array1[N-1]+array2[N-1]. Then we determine how many pair sums are greater than this value and how many of them are less. This may be done by iterating the arrays with two pointers: pointer to the first array incremented when sum is too large and pointer to the second array decremented when sum is too small. Repeating this procedure for different values and using binary search (or one-sided binary search) we could find Kth largest sum in O(N log R) time, where N is size of the largest array and R is number of possible values between array1[N-1]+array2[N-1] and array1[0]+array2[0]. This algorithm has linear time complexity only when the array elements are integers bounded by small

Categories : Performance

How to find largest values in C++ Map
I doubt there's a "Textbook Answer", and the answer is no: you can't sort maps by value. You could always create another map using the values. However, this is not the most efficient solution. What I think would be better is for you to chuck the values into a priority_queue, and then pop the first 100 off. Note that you don't need to store the words in the second data structure. You can store pointers or references to the word, or even a map::iterator. Now, there's another approach you could consider. That is to maintain a running order of the top 100 candidates as you build your first map. That way there would be no need to do the second pass and build an extra structure which, as you pointed out, is wasteful. To do this efficiently you would probably use a heap-like approach and

Categories : C++

Find the Kth largest int in array
the < and > in your code is reverse in partition() as @Dietmar Kühl mentioned,by change them,it works correctly. besides,my suggestion is to use a normal partition() of quicksort as follow, for whose two index of which move in the same direction and one of them never surpasses another. It is not easy to make anyone confused. int partition(int *input, int p, int r) { int pivot,i,j,tmp; pivot = input[r]; i = p-1; for (j=p;j<=r-1;j++) { if (input[j]>= pivot) { i++; tmp = input[i]; input[i] = input[j]; input[j] = tmp; } } tmp = input[i+1]; input[i+1] = input[r]; input[r] = tmp; return i+1; }

Categories : C++

Find value from one cell, copy value from cell near to that cell and paste it to another sheet
Use a VLOOKUP along with an IFERROR. =IFERROR(VLOOKUP(A1, Sheet1!A:B, 2, 0), "") This will do what you described (well described, by the way!) in your question. Drag the formula down in Sheet2 till the bottom. VLOOKUP takes the value of A1 in sheet 2 (no sheet reference because the value is in the same sheet as the formula) and looks it up in column A of Sheet1. It returns the second value (hence why 2) of the table selected in the formula (column A is 1, column B is 2). The 0 tells the VLOOKUP to look for exact matches. You don't need approximate match here. And IFFERROR is there in case VLOOKUP doesn't find anything (like with ada) and instead of giving #N/A, returns an empty cell, "".

Categories : Excel

Return the indices of unmasked elements that are both zero and not zero
This is one possibility. But I'm almost sure it's too circuitous. >>> xmindex = np.transpose(np.concatenate(((ma.MaskedArray.nonzero(xm==0), ma.MaskedArray.nonzero(xm!=0))),axis=1)) >>> xmindex array([[1, 1], [0, 0], [0, 1], [1, 2], [2, 1]]) And then sorting >>> xmindex = xmindex[np.lexsort((xmindex[:,1],xmindex[:,0]))] >>> xmindex array([[0, 0], [0, 1], [1, 1], [1, 2], [2, 1]])

Categories : Python

Get indices for all elements in an array in numpy
Have you thought of using itertools? It will generate an iterator for your results, and will almost certainly be optimally fast: import itertools a = range(1000) b = range(1000) product = itertools.product(a, b) for x in product: print x # (0, 0) # (0, 1) # ... # (999, 999) Notice this didn't require the dependency on numpy. Also, notice the fun use of range to create a list from 0 to 999.

Categories : Python

For double f, float g, How to find largest int i, such that i*g <= f
I think you should try to fix the root problem (.1f too far away from .1), i.e. turn TILE_SIZE into a double, or use floats consistently everywhere. Otherwise you might get similar problems caused by minimal rounding errors throughout the code. The candidate_answer function is a hack to work around a problem that should not exist in the first place. P.S. For this particular problem, you might just want to find a formula that is more robust, i.e. isn't sensitive to minimal rounding errors in one direction only. Try to put the player in the center of its field instead of at the tile edge where it can easily fall into rounding errors: col = (int)((x + MINIMAL_STEP_SIZE / 2.0) / TILE_SIZE) (Ideally, the MINIMAL_STEP_SIZE/2 part would already be part of x instead of being added here)

Categories : Java

Find largest intersecting diagonals
There is no asymptotic better solution with regards to time complexity. A weaker problem is to check if the matrix contains any 1-cell. For this problem you clearly you have to visit every cell, which gives you O(nxm). Now this is a lower bound to the original problem, which also has O(nxm). Qed.

Categories : Algorithm

How to find the largest power of 2 less than the given number
Change res =(int)Math.pow(res, 2); to res *= 2; This will return the next power of 2 greater than res. The final result you are looking for will therefore finally be res / 2 after the while has ended. To prevent the code from overflowing the int value space you should/could change the type of res to double/long, anything that can hold higher values than int. In the end you would have to cast one time.

Categories : Java

How to find largest delta in array?
change int[] largestDelta = {0}; to int largestDelta = stocks[0]; or int largestDelta = 0; Also remember about changing the return type.

Categories : Java

Find the largest integer in Datagridview column Vb.net
Try this Dim abcd as Integer For x As Integer = 0 to Datagrid.Rows.Count - 1 If abcd = 0 then abcd = Datagrid.Rows(x).Cells(0).Value Else if abcd < Datagrid.Rows(x).Cells(0).Value Then abcd = Datagrid.Rows(x).Cells(0).Value Endif Next MsgBox(abcd)

Categories : Vb.Net

How to find the size of the largest file in a directory?
Java 7 offers the new java.nio.* classes including a FileVisitor: http://docs.oracle.com/javase/tutorial/essential/io/walk.html I used them already, but i cant say, which solution is the better one. In my opinion you should keep your solution, because it is better to read.

Categories : Java

How to find the k largest integers in a list in O(n) time?
One easy way to do this is by turning the list into a heap and popping k times. In Python, this can be done with the heapq module. import heapq numbers = [6,1,32,8,2,1,9,77,12,-643,-6,3] def getKLargest(nums, k): nums = [-x for x in nums] heapq.heapify(nums) for _ in xrange(k): yield -heapq.heappop(nums) print list(getKLargest(numbers, 5)) print sorted(numbers, reverse=True)[:5]

Categories : List

How to find largest number in an array using NASM
The output 2222 is correct for a 32 bit register. Each number is 8 bits, 4 numbers = 8 * 4 = 32, the max a 32 bit register can hold. This is why if you change to 64 bit registers, the full number is printed. You will need to change the displayed number into a string to display the full number.

Categories : Arrays

Find largest document size in MongoDB
You can use a small shell script to get this value. Note : Following will do a full table scan var max = 0; db.test.find().forEach(function(obj) { var curr = Object.bsonsize(obj); if(max < curr) { max = curr; } }) print(max);

Categories : Mongodb

How to extract indices of all nonzero elements from an 0-1 array using OpenMP?
I am not 100% sure this will be much better, but you could try the following: int count = 0; #pragma omp parallel for for(int i = 0; i < N; ++i) { if(M[i]) { #pragma omp atomic T[count++] = i; } } If the array is quite sparse, threads will be able to zip through a lot of zeros without waiting for others. But you can only update one index at a time. The problem is really that different threads are writing to the same memory block (T), which means you will be running into issues of caching: every time one thread writes to T, the cache of all the other cores is "dirty" - so when they try to modify it, a lot of shuffling goes on behind the scenes. All this is transparent to you (you don't need to write code to handle it) but it slows things down signficantly - I s

Categories : C

What's the fastest way to get all of the indices of false elements in a boolean array?
A for loop is likely the fastest way to do this: List<int> indices = new List<int>(); for (int i=0;i < theArray.Length; ++i) { if (theArray[i]) { indices.Add(i); } } Note that you can probably gain a slight bit of speed at the cost of extra memory by preallocating the List<int>: List<int> indices = new List<int>(theArray.Length); This will avoid extra memory allocations.

Categories : C#

Program to find largest and smallest among 5 numbers without using array
#include <algorithm> #include <iostream> template <typename T> inline const T& max_of(const T& a, const T& b) { return std::max(a, b); } template <typename T, typename ...Args> inline const T& max_of(const T& a, const T& b, const Args& ...args) { return max_of(std::max(a, b), args...); } int main() { std::cout << max_of(1, 2, 3, 4, 5) << std::endl; // Or just use the std library: std::cout << std::max({1, 2, 3, 4, 5}) << std::endl; return 0; }

Categories : C++

Python Splitting string to find largest odd integer
How about a list comprehension: if len(x) == 10: oddList = [int(a) for a in x if int(a) % 2] if oddList: return max(oddList) Assuming x needs to be 10 values long; assuming you don't need an else statement. You don't need to check for int(a) % 2 != 0, because if it is zero it returns false anyway.

Categories : Python

Android OpenCV Find Largest Square or Rectangle
There are some related questions here in SO. Check them out: OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection How do I recognize squares in this image? There is also an example shipped with OpenCV: https://code.ros.org/trac/opencv/browser/trunk/opencv/samples/cpp/squares.cpp?rev=4079 Once you have the rectangle, you can align the picture by computing the homography with the rectangle corners and applying a perspective transform.

Categories : Android

Find indices of a value in 2d matrix
If you want all of the locations that the value appears at, you can use the following list comprehension with val set to whatever you're searching for [(index, row.index(val)) for index, row in enumerate(mymatrix) if val in row] for example: >>> mymatrix=[[1,2,9],[4,9,6],[7,8,9]] >>> val = 9 >>> [(index, row.index(val)) for index, row in enumerate(mymatrix) if val in row] [(0, 2), (1, 1), (2, 2)] EDIT It's not really true that this gets all occurrences, it will only get the first occurrence of the value in a given row.

Categories : Python

Can't find any special indices
The problem was with setting up the index Instead of Address.collection.create_index("randomizer", '2d' => true) should be as Address.collection.create_index("randomizer" => '2d')

Categories : Ruby

find the max difference between j and i indices such that j > i and a[j] > a[i] in O(n)
Let's make this simple observation: If we have 2 elements a[i], a[j] with i < j and a[i] < a[j] then we can be sure that j won't be part of the solution as the first element (he can be the second but that's a second story) because i would be a better alternative. What this tells us is that if we build greedily a decreasing sequence from the elements of a the left part of the answer will surely come from there. For example for : 12 3 61 23 51 2 the greedily decreasing sequence is built like this: 12 -> 12 3 -> we ignore 61 because it's worse than 3 -> we ignore 23 because it's worse than 3 -> we ignore 51 because it's worse than 3 -> 12 3 2. So the answer would contain on the left side 12 3 or 2. Now on a random case this has O(log N) length so you can binary search on it for ea

Categories : C

Objective-C algorithm to find largest common subsets of arrays?
You are looking for an algorithm to find the cardinality of a set intersection. Depending on your set representation, you could choose different ways of doing it. The most performant representation for this would be using bits in an integer, but if the number of possible interests exceeds 64 this may not be easy to implement. A straightforward way of implementing it would be with NSMutableSet, like this: // Prepare the individual lists NSArray *chris = @[@"bowling", @"gaming", @"skating", @"running"]; NSArray *brad = @[@"bowling", @"jumping", @"walking", @"sitting"]; // Obtain the intersection NSMutableSet *common = [NSMutableSet setWitArray:chris]; [common intersectSet:[NSSet setWithArray:brad]]; NSLog(@"Common interest count: %i", common.count);

Categories : Objective C

Find the order of numbers which will give the largest number in an array
A lexicographic sort is a good start. However, the difficulty comes in when considering that, for example, [854, 854853, 854855] needs to be sorted to [854855, 854, 854853]. One way to fix this is to define a comparator that compares concatenated versions of the numbers (i.e. comparing abc and def translates to comparing abcdef and defabc). The simplest version: // processing numbers as strings List<String> array = Arrays.asList("854", "854853", "854855"); Collections.sort(array, new Comparator<String>() { @Override public int compare(String o1, String o2) { // negative since we want biggest first return -(o1+o2).compareTo(o2+o1); } }); Test. The compare function without the overhead of actually having to concatenate the numbers, just doing the ch

Categories : Java

How can I find all indices of a value in a multidimensional array?
Not exactly the output you imagine, but this one preserves the nested structure of lists: def getAllIndicesRecursively(s, l): r = [] for i, v in enumerate(l): if isinstance(v, list): r += [ getAllIndicesRecursively(s, v) ] elif v == s: r += [ i ] return r arr = ["foo", ["foo", "foo", [1, "foo"]], "foo"] getAllIndicesRecursively("foo", arr) Output: [0, [0, 1, [1]], 2] And this gives the output you describe: def getAllIndicesRecursively(s, l, agg=[], path=[]): for i, v in enumerate(l): if isinstance(v, list): getAllIndicesRecursively(s, v, agg, path + [ i ] ) elif v == s: agg += [ path + [ i ] ] return agg Output: [[0], [1, 0], [1, 1], [1, 2, 1], [2]]

Categories : Python

find all indices of max values matlab
First you find the max value, then you find all the elements equal to that: m = max(myArray); maxIndex = find(myArray == m); Or using your variable names: maxChaqueCell = [4 5 5 4]; maximum = max(maxChaqueCell) indicesDesMax = find( maxChaqueCell == maximum ); This is how you find all of them, not just the first one.

Categories : Matlab

Getting awkward results when trying to find largest product in array for project euler 11
I found several problems. The first block of code multiplies twenty_grid[i][j+2] twice. In the third block of code the end condition for the inner loop should be j < 17. The last block of code uses i as an array index instead of j in three places. It produces the correct answer after fixing these issues.

Categories : C++

Find starting and ending indices of sublist in list
Slice the list: >>> greeting[0:3] ['hello', 'my', 'name'] >>> greeting[1:4] ['my', 'name', 'is'] >>> greeting[1:4] == ['my','name','is'] True This should get your started: for n in range(len(greeting) - len(sub_list) + 1): ...

Categories : Python

MATLAB: Given a row vector, find the indices of two nearest numbers
Try to get a distance function for each index to every other index. for i=1:length(A) for j=1:i B(i,j)=NaN; end for j=i+1:length(A) B(i,j)=abs(A(i)-A(j)); end end B = NaN 4.0000 1.0000 11.0000 2.0000 18.1000 NaN NaN 3.0000 7.0000 6.0000 22.1000 NaN NaN NaN 10.0000 3.0000 19.1000 NaN NaN NaN NaN 13.0000 29.1000 NaN NaN NaN NaN NaN 16.1000 NaN NaN NaN NaN NaN NaN [ind1,in2]=find(B==min(min(B))) ind1 = 1 ind2 = 3

Categories : Matlab

How to find all indices above a specific value in a python multidimensional list
You could do this with a nested loop: indices = [] for i, row in enumerate(grid): for j, val in enumerate(row): if val > threshold: indices.append((i, j)) but it's quite likely that you should be using numpy, which offers high-speed vectorized operations and very convenient syntax. With a numpy ndarray instead of a nested list, the code is as follows: numpy.where(grid > threshold)

Categories : Python

Avoiding merged cell when find next empty cell in a column
I started to reply with a comment to your question, but think this will be easier to read as an answer. There are a few things that need to be cleaned up or clarified. Always require variable declaration. wsMaster and wbData are not declared. In the VBE, go to Tools --> Options to set this. You declare some row variables as integers and others as longs. Always use longs to avoid overflow errors. You set lastRowToPaste to be 1000 greater than LastRow. What is the significance of 1000? NextRow and LastRow have the first letter capitalized. All other variables have a lower-case first letter. You should use a consistent naming convention. What is the purpose of NextRow? You set its value, and then never use it. You set rowToPaste equal to lastCheckedRow, an variable that hasn't itself bee

Categories : Vba

Find median value of the largest clump of similar values in an array in the most computationally efficient manner
This possibility bins your data and looks for the bin with most elements. If your distribution consists of well separated clusters this should work reasonably well. H = [99,100,101,102,103,180,181,182,5,250,17]; nbins = length(H); % <-- set # of bins here [v bins]=hist(H,nbins); [vm im]=max(v); % find max in histogram bl = bins(2)-bins(1); % bin size bm = bins(im); % position of bin with max # ifb =find(abs(H-bm)<bl/2) % elements within bin median(H(ifb)) % average over those elements in bin Output: ifb = 1 2 3 4 5 H(ifb) = 99 100 101 102 103 median = 101 The more challenging parameters to set are the number of bins and the size of the region to look around the most populated bin. In the example y

Categories : Matlab



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.