C++ Cout array values with upper and lower limits - c++

I have an array of prime numbers from 2 to 997. How do you display array values with upper and lower limits? For example:
Upper and lower limits: 0 20
Output:
2, 3, 5, 7, 11, 13, 17, 19

Loop on the array till you find a number bigger than the lower limit, Then loop and display until you find a number bigger than the upper limit.

Related

How many number are less than or equal than x in an array?

Given an integer n and array a, I need to find for each i, 1≤ i ≤ n, how many elements on the left are less than or equal to ai
Example:
5
1 2 1 1 2
Output
0 1 1 2 4
I can do it in O(N2) but I want to ask if there is any way to do it faster, since N is very large (N ≤ 106)?
You can use a segment tree, you just need to use a modified version called a range tree.
Range trees allow rectangle queries, so you can make the dimensions be index and value, and ask "What has value more than x, and index between 1 and n?"
Queries can be accomplished in O(log n) assuming certain common optimizations.
Either way O(N^2) is completely fine with N < 10^6.
I like to consider a bigger array to explain, so let's consider following array,
2, 1, 3, 4, 7, 6, 5, 8, 9, 10, 12, 0, 11, 13, 8, 9, 12, 20, 30, 60
The naïve way is to compare an element with all elements at left of it. Naïve approach has complexity of O(n^2) which make it not useful for big array.
If you look this problem closely you will find a pattern in it, and the pattern is Rather than comparing with each left element of an element we can compare first and last value of a range!. Wait a minute what is the range here?
These numbers can be viewed as ranges and there ranges can be created from traversing left to right in array. Ranges are as follows,
[2], [1, 3, 4, 7], [6], [5, 8, 9, 10, 12], [0, 11, 13], [8, 9, 12, 20, 30, 60]
Let’s start traversing array from left to right and see how we can create these ranges and how these ranges shall reduce the effort to find all small or equal elements at left of an element.
Index 0 have no element at its left to compare thus why we start form index 1, at this point we don’t have any range. Now we compare value of index 1 and index 0. Value 1 is not less than or equals to 2, so this is very import comparison, due to this comparison we know the previous range should end here because now numbers are not in acceding order and at this point we get first range [2], which contains only single element and number of elements less than or equals to left of element at index 1 is zero.
As continue with traversing left to right at index 2 we compare it with previous element which is at index 1 now value 1 <= 3 it means a new range is not staring here and we are still in same range which started at index 1. So to find how many elements less than or equals, we have to calculate first how many elements in current range [1, 3), in this case only one element and we have only one know range [2] at this point and it has one element which is less than 3 so total number of less than or equals elements at the left of element at index 2 is = 1 + 1 = 2. This can be done in similar way for rest of elements and I would like to jump directly at index 6 which is number 5,
At index 6, we have all ready discovered three ranges [2], [1, 3, 4, 7], [6] but only two ranges [2] and [1, 3, 4, 7] shall be considered. How I know in advance that range [6] is not useful without comparing will be explained at the end of this explanation. To find number of less than or equals elements at left, we can see first range [2] have only one element and it is less than 5, second range have first element 1 which is less than 5 but last element is 7 and it is greater than 5, so we cannot consider all elements of range rather we have to find upper bound in this range to find how many elements we can consider and upper bound can be found by binary search because range is sorted , so this range contains three elements 1, 3, 4 which are less then or equals to 5. Total number of elements less than or equals to 5 from two ranges is 4 and index 6 is first element of current range and there is no element at left of it in current range so total count = 1 + 3 + 0 = 4.
Last point on this explanation is, we have to store ranges in tree structure with their first value as key and value of the node should be array of pair of first and last index of range. I will use here std::map. This tree structure is required so that we can find all the range having first element less than or equals to our current element in logarithmic time by finding upper bound. That is the reason, I knew in advance when I was comparing element at index 6 that all three ranges known that time are not considerable and only two of them are considerable .
Complexity of solution is,
O(n) to travels from left to right in array, plus
O(n (m + log m)) for finding upper bound in std::map for each element and comparing last value of m ranges, here m is number of ranges know at particular time, plus
O(log q) for finding upper bound in a range if rage last element is greater than number, here q is number of element in particular range (It may or may not requires)
#include <iostream>
#include <map>
#include <vector>
#include <iterator>
#include <algorithm>
unsigned lessThanOrEqualCountFromRage(int num, const std::vector<int>& numList,
const std::map<int,
std::vector<std::pair<int, int>>>& rangeMap){
using const_iter = std::map<int, std::vector<std::pair<int, int>>>::const_iterator;
unsigned count = 0;
const_iter upperBoundIt = rangeMap.upper_bound(num);
for(const_iter it = rangeMap.cbegin(); upperBoundIt != it; ++it){
for(const std::pair<int, int>& range : it->second){
if(numList[range.second] <= num){
count += (range.second - range.first) + 1;
}
else{
auto rangeIt = numList.cbegin() + range.first;
count += std::upper_bound(rangeIt, numList.cbegin() +
range.second, num) - rangeIt;
}
}
}
return count;
}
std::vector<unsigned> lessThanOrEqualCount(const std::vector<int>& numList){
std::vector<unsigned> leftCountList;
leftCountList.reserve(numList.size());
leftCountList.push_back(0);
std::map<int, std::vector<std::pair<int, int>>> rangeMap;
std::vector<int>::const_iterator rangeFirstIt = numList.cbegin();
for(std::vector<int>::const_iterator it = rangeFirstIt + 1, endIt = numList.cend();
endIt != it;){
std::vector<int>::const_iterator preIt = rangeFirstIt;
while(endIt != it && *preIt <= *it){
leftCountList.push_back((it - rangeFirstIt) +
lessThanOrEqualCountFromRage(*it,
numList, rangeMap));
++preIt;
++it;
}
if(endIt != it){
int rangeFirstIndex = rangeFirstIt - numList.cbegin();
int rangeLastIndex = preIt - numList.cbegin();
std::map<int, std::vector<std::pair<int, int>>>::iterator rangeEntryIt =
rangeMap.find(*rangeFirstIt);
if(rangeMap.end() != rangeEntryIt){
rangeEntryIt->second.emplace_back(rangeFirstIndex, rangeLastIndex);
}
else{
rangeMap.emplace(*rangeFirstIt, std::vector<std::pair<int, int>>{
{rangeFirstIndex,rangeLastIndex}});
}
leftCountList.push_back(lessThanOrEqualCountFromRage(*it, numList,
rangeMap));
rangeFirstIt = it;
++it;
}
}
return leftCountList;
}
int main(int , char *[]){
std::vector<int> numList{2, 1, 3, 4, 7, 6, 5, 8, 9, 10, 12,
0, 11, 13, 8, 9, 12, 20, 30, 60};
std::vector<unsigned> countList = lessThanOrEqualCount(numList);
std::copy(countList.cbegin(), countList.cend(),
std::ostream_iterator<unsigned>(std::cout, ", "));
std::cout<< '\n';
}
Output:
0, 0, 2, 3, 4, 4, 4, 7, 8, 9, 10, 0, 11, 13, 9, 11, 15, 17, 18, 19,
Yes, It can be done in better time complexity compared to O(N^2) i.e O(NlogN). We can use the Divide and Conquer Algorithm and Tree concept.
want to see the source code of above mentioned two algorithms???
Visit Here .
I think O(N^2) should be the worst case. In this situation, we will have to traverse the array at least two times.
I have tried in O(N^2):
import java.io.*;
import java.lang.*;
public class GFG {
public static void main (String[] args) {
int a[]={1,2,1,1,2};
int i=0;
int count=0;
int b[]=new int[a.length];
for(i=0;i<a.length;i++)
{
for(int c=0;c<i;c++)
{
if(a[i]>=a[c])
{
count++;
}
}
b[i]=count;
count=0;
}
for(int j=0;j<b.length;j++)
System.out.print(b[j]+" ");
}`

HALCON min_mas_grey()

Can someone explain what the percent parameter is for on the min_mas_grey() operator in Halcon?
min_max_gray(Regions, Image : : Percent : Min, Max, Range)
The documentation for this operator can be found here:
https://www.mvtec.com/doc/halcon/2005/en/min_max_gray.html
To elaborate a little on the explanation if you are having trouble following it:
calculates the number of pixels Percent corresponding to the area of
the input image. Then it goes inwards on both sides of the histogram
by this number of pixels and determines the smallest and the largest
gray value
Essentially, if percent is 0 you will obtain min/max as you'd expect however if you give a percentage it will subtract this percentage (as a pixel value) from either side of the histogram and give these values as min and max instead. If percent is 50 that then means min and max are the same and signify the median.
Let's look at a simplified example:
image in an image with 10 pixels who have the following values:
[0, 0, 1, 2, 3, 3, 3, 3, 4, 5]
The histogram would be like this:
0: 2
1: 1
2: 1
3: 4
4: 1
5: 1
If percent is 0 then min = 0 and max = 5.
Percent 10 would mean you take one pixel away at the edges of the histogram, thus min = 0 and max = 4...
percent 20, equals 2 pixels and thus min = 1 max = 3
percent 30, equals 3 pixels thus min = 2, max = 3
percent 50, min=max=3 which is the median

How can I find median with an even amount of numbers in a list?

This is what I have right now. It just finds the median with an odd amount of numbers.
def median(height):
height.sort()
x = len(height)
x -= 1
posn = x // 2
return height[posn]
"The median is the numeric value separating the higher half of a sample data set from the lower half. The median of a data set can be found by arranging all the values from lowest to highest value and picking the one in the middle. If there is an odd number of data values then the median will be the value in the middle. If there is an even number of data values the median is the mean of the two data values in the middle." - Source
For the data set 1, 1, 2, 5, 6, 6, 9 the median is 5.
For the data set 1, 1, 2, 6, 6, 9 the median is 4. It is the mean of 2 and 6 or, (2+6)/2 = 4.

C++ Armadillo Access Triangular Matrix Elements

What would be the most efficient (i.e. balance memory and speed) way to access the upper or lower triangular elements of an Armadillo matrix? I know I could provide a vector of integers for the elements but as matrices become very large I would like avoid carrying around another large vector. Or is there an efficient way to quickly create the lower/upper triangular indices?
For example with a 5x5 matrix
// C++11 Initialization
arma::mat B = { 1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
11, 12, 13, 14, 15,
16, 17, 18, 19, 20,
21, 22, 23, 24, 25 };
B.reshape(5,5);
// the matrix
//1 6 11 16 21
//2 7 12 17 22
//3 8 13 18 23
//4 9 14 19 24
//5 10 15 20 25
I would like to pull the elements in the lower triangle where the result vector would be:
2 3 4 5 8 9 10 14 15 20
The only solution I can think of right now is using a uvec object. For example:
arma::uvec idx {1,2,3,4,7,8,9,13,14,19);
arma::vec lower_elems = B.elem(idx);
The final object doesn't need to be a vector. I just need to be able to access the elements for various comparisons. As a simple example let's say I would want to check if they all equal 0.
To check if all the elements in the lower triangle are equal to zero:
bool all_zero = all( X.elem(find(trimatl(X))) == 0 );
Armadillo 9.900 has the functions trimatu_ind() and trimatl_ind(). These functions provide the indices of the upper and lower triangular portions of a matrix. These indices can be used with .elem() to access the elements in upper/lower triangular portions.
There are also the functions .is_trimatu() and .is_trimatl() which check if a matrix is upper/lower trinagular.

How do I find permutations or combinations for byte?

A character (1 byte) can represent 255 characters but how do i actually find it?
(answering the comment)
There are 256 different combinations of 8 0s and 1s.
This is true because 256 = 28.
Each digit that you add doubles the number of combinations.
In a fixed width binary number, there are two choices for the first bit, two choices for the second bit, two choices for the third, and so on. The total number of combinations for an 8-bit byte is:
2 * 2 * 2 * 2 * 2 * 2 * 2 * 2 = 28 = 256
do you mean
for (char c = " "; c <= "~"; c++) std::cout << c << std::endl;
?
This should show you printable characters in ASCII proper. To see all characters in your font, try c = 0 and c < 255 (be careful with 255 and infinite loop) - but this won't work with your terminal, most probably.
8 bits can represent permutations of ones and zeros from binary 00000000 to 11111111. Just like 3 decimal digits can represent permutations of decimal numbers (0-9) from decimal 000 to 999.
You just start counting: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 and then after you reach the digit maximum, you carry over a 1 and start from 0: ..., 8, 9, 10. Right? And then continue this until you fill up all your digits with nines: ..., 997, 998, 999.
It's the same thing in binary: 0, 1 then carry over 1 and start from 0: 0, 1, 10. Continue: 10, 11, 100, 101, 110, 111, 1000, 1001 etc.
Simply counting from 0 to the maximum value than can be represented by your digits gives you all the permutations.