I cant find out whats wrong with this part of my program, i want to find out most occuring number in my structure(array), but it finds only the last number :/
void Daugiausiai(int n)
{
int max = 0;
int sk;
for(int i = 0; i < n; i++){
int kiek = 0;
for(int j=0; j < n; j++){
if(A[i].datamet == A[j].datamet){
kiek++;
if(kiek > max){
max = kiek;
sk = A[i].datamet;
}
}
}
}
}
ps. its only a part of my code
You haven't shown us enough of your code, but it is likely that you are not looking at the real result of your function. The result, sk is local to the function and you don't return it. If you have global variable that is also named sk, it will not be touched by Daugiausiai.
In the same way, you pass the number of elements in your struct array, but work on a global struct. It is good practice to "encapsulate" functions so that they receive the data they work on as arguments and return a result. Your function should therefore pass both array length and array and return the result.
(Such an encapsulation doesn't work in all cases, but here, it has the benefit that you can use the same function for many different arrays of the same structure tape.)
It is also enough to test whether the current number of elements is more than the maximum so far after your counting loop.
Putting all this together:
struct Data {
int datamet;
};
int Daugiausiai(const struct Data A[], int n)
{
int max = 0;
int sk;
for (int i = 0; i < n; i++){
int kiek = 0;
// Count occurrences
for(int j = 0; j < n; j++){
if(A[i].datamet == A[j].datamet) kiek++;
}
// Check for maximum
if (kiek > max) {
max = kiek;
sk = A[i].datamet;
}
}
return sk;
}
And you call it like this:
struct Data A[6] = {{1}, {2}, {1}, {4}, {1}, {2}};
int n = Daugiausiai(A, 6);
printf("%d\n", n); // 1
It would be nice if you had english variable names, so I could read them a bit better ^^. What should your paramter n do? Is that the array-length? And what should yout funtion do? It has no return value or something.
int getMostOccuring(int array[], int length)
{
int current_number;
int current_count = 0;
int most_occuring_number;
int most_occuring_count = 0;
for (int i = 0; i < length; i++)
{
current_number = array[i];
current_count = 0;
for (int j = i; j < length; j++)
{
int test_number = array[j];
if (test_number == current_number)
{
current_count ++;
if (current_count > most_occuring_count)
{
most_occuring_number = current_number;
most_occuring_count = current_count;
}
}
}
}
return most_occuring_number;
}
this should work and return the most occuring number in the given array (it has a bad runtime, but is very simple and good to understand).
Related
here I am trying to convert my recursive solution into a dynamic solution but I am getting problem in converting. I am trying to count minimum possible coin to make value. what I am doing is I am taking all possible coin and putting inside a vector and finally in main function I will find and minimum of my vector and that will be my answer
int rec(vector<int>coins,int n,int sum,int counter)
{
if(sum==0)
{
return 1;
}
if(n==0)
{
return 0;
}
int total=rec(coins,n-1,sum,counter);
if(sum-coins[n-1]>=0)
{
total+=rec(coins,n,sum-coins[n-1],counter+1);
if(sum-coins[n-1]==0)
{
vec.push_back(counter+1);
}
}
return total;
}
you should first try to solve this type of problems by yourself.
BTW:
#define BIG 2147483647
int min_coin(int *coins, int m, int desire_value)
{
int dp[desire_value+1];
dp[0] = 0;
for (int i=1; i<=desire_value; i++)
dp[i] = BIG;
for (int i=1; i<=desire_value; i++)
{
for (int j=0; j<m; j++)
if (coins[j] <= i)
{
int diff = dp[i-coins[j]];
if (diff != BIG && diff + 1 < dp[i])
dp[i] = diff + 1;
}
}
if(dp[desire_value]==BIG)
return -1;
return dp[desire_value];
}
you can easily convert dp and coins to vector. vector is like array.(beware for allocate vector for dp you should reserve space in vector see here.)
Currently, I am making a C++ program that solves a sudoku. In order to do this, I calculate the "energy" of the sudoku (the number of faults) frequently. This calculation unfortunately takes up a lot of computation time. I think that it can be sped up significantly by using pointers and references in the calculation, but have trouble figuring out how to implement this.
In my solver class, I have a vector<vector<int> data-member called _sudoku, that contains the values of each site. Currently, when calculating the energy I call a lot of functions with pass-by-value. I tried adding a & in the arguments of the functions and a * when making the variables, but this did not work. How can I make this program run faster by using pass-by-reference?
Calculating the energy should not change the vector anyway so that would be better.
I used the CPU usage to track down 80% of the calculation time to the function where vectors are called.
int SudokuSolver::calculateEnergy() {
int energy = 243 - (rowUniques() + colUniques() + blockUniques());//count number as faults
return energy;
}
int SudokuSolver::colUniques() {
int count = 0;
for (int col = 0; col < _dim; col++) {
vector<int> colVec = _sudoku[col];
for (int i = 1; i <= _dim; i++) {
if (isUnique(colVec, i)) {
count++;
}
}
}
return count;
}
int SudokuSolver::rowUniques() {
int count = 0;
for (int row = 0; row < _dim; row++) {
vector<int> rowVec(_dim);
for (int i = 0; i < _dim; i++) {
rowVec[i] = _sudoku[i][row];
}
for (int i = 1; i <= _dim; i++) {
if (isUnique(rowVec, i)) {
count++;
}
}
}
return count;
}
int SudokuSolver::blockUniques() {
int count = 0;
for (int nBlock = 0; nBlock < _dim; nBlock++) {
vector<int> blockVec = blockMaker(nBlock);
for (int i = 1; i <= _dim; i++) {
if (isUnique(blockVec, i)) {
count++;
}
}
}
return count;
}
vector<int> SudokuSolver::blockMaker(int No) {
vector<int> block(_dim);
int xmin = 3 * (No % 3);
int ymin = 3 * (No / 3);
int col, row;
for (int i = 0; i < _dim; i++) {
col = xmin + (i % 3);
row = ymin + (i / 3);
block[i] = _sudoku[col][row];
}
return block;
}
bool SudokuSolver::isUnique(vector<int> v, int n) {
int count = 0;
for (int i = 0; i < _dim; i++) {
if (v[i] == n) {
count++;
}
}
if (count == 1) {
return true;
} else {
return false;
}
}
The specific lines that use a lot of computatation time are the ones like:
vector<int> colVec = _sudoku[col];
and every time isUnique() is called.
I expect that if I switch to using pass-by-reference, my code will speed up significantly. Could anyone help me in doing so, if that would indeed be the case?
Thanks in advance.
If you change your SudokuSolver::isUnique to take vector<int> &v, that is the only change you need to do pass-by-reference instead of pass-by-value. Passing with a pointer will be similar to passing by reference, with the difference that pointers could be re-assigned, or be NULL, while references can not.
I suspect you would see some performance increase if you are working on a sufficiently large-sized problem where you would be able to distinguish a large copy (if your problem is small, it will be difficult to see minor performance increases).
Hope this helps!
vector<int> colVec = _sudoku[col]; does copy/transfer all the elements, while const vector<int>& colVec = _sudoku[col]; would not (it only creates an alias for the right hand side).
Same with bool SudokuSolver::isUnique(vector<int> v, int n) { versus bool SudokuSolver::isUnique(const vector<int>& v, int n) {
Edited after Jesper Juhl's suggestion: The const addition makes sure that you don't change the reference contents by mistake.
Edit 2: Another thing to notice is that vector<int> rowVec(_dim); these vectors are continuously allocated and unallocated at each iteration, which might get costly. You could try something like
int SudokuSolver::rowUniques() {
int count = 0;
vector<int> rowVec(_maximumDim); // Specify maximum dimension
for (int row = 0; row < _dim; row++) {
for (int i = 0; i < _dim; i++) {
rowVec[i] = _sudoku[i][row];
}
for (int i = 1; i <= _dim; i++) {
if (isUnique(rowVec, i)) {
count++;
}
}
}
return count;
}
if that doesn't mess up with your implementation.
I'm trying to write a function that finds the number of prime numbers in an array.
int countPrimes(int a[], int size)
{
int numberPrime = 0;
int i = 0;
for (int j = 2; j < a[i]; j++)
{
if(a[i] % j == 0)
numbPrime++;
}
return numPrime;
}
I think what I'm missing is I have to redefine i after every iteration, but I'm not sure how.
You need 2 loops: 1 over the array, 1 checking all possible divisors. I'd suggest separating out the prime check into a function. Code:
bool primeCheck(int p) {
if (p<2) return false;
// Really slow way to check, but works
for(int d = 2; d<p; ++d) {
if (0==p%d) return false; // found a divisor
}
return true; // no divisors found
}
int countPrimes(const int *a, int size) {
int numberPrime = 0;
for (int i = 0; i < size; ++i) {
// For each element in the input array, check it,
// and increment the count if it is prime.
if(primeCheck(a[i]))
++numberPrime;
}
return numberPrime;
}
You can also use std::count_if like this:
std::count_if(std::begin(input), std::end(input), primeCheck)
See it live here.
So I am trying so merge 2 sorted arrays into one and I get really weird numbers like an output. Here is my code:
#include<iostream>
using namespace std;
int* add(int first[],int second[], int sizeFirst, int sizeSecond)
{
int result[sizeFirst + sizeSecond];
int indexFirst = 0,indexSecond = 0;
for(int i = 0;i < sizeFirst + sizeSecond;i++)
{
if(indexFirst == sizeFirst || first[indexFirst] > second[indexSecond])
{
result[i] = second[indexSecond];
indexSecond++;
}
else
{
result[i] = first[indexFirst];
indexFirst++;
}
}
return result;
}
int main()
{
int n;
cin>>n;
int arr[n];
for(int i = 0;i < n;i ++)
cin>>arr[i];
int m;
cin>>m;
int arr2[m];
for(int i = 0;i < m;i ++)
cin>>arr2[i];
int *res;
res = add(arr,arr2,n,m);
for(int i = 0;i < n + m;i ++)
cout<<res[i]<<" ";
return 0;
}
Notes: It sorts it properly, so the mistake is not there. Also I need to do it as a function because I will need it later on for some other stuff.
return result;
You are returning a pointer to local array, which gets destroyed immediately after - this is undefined behavior. You should either allocate it using new or use std::vector (which is preferred).
Also, int result[sizeFirst + sizeSecond]; is not valid C++ because the standard doesn't allow variable sized arrays (but int* result = new int[sizeFirst + sizeSecond]; is valid).
I am supposed to get the output 8, 6. But I get 8,9 when this code is run. Why am I getting the out put 8,6 and how can I fix the code to make the output become 8,9.
int inputarray[]={9,8,9,9,9,9,6};
int length = 7;
int value = 9;
void arrayShift(int arr[], int length, int value)
{
for(int i = 0; i<length; i++)
{
if(arr[i] == value)
{
for (int k = i; k<length ; k++)
{
arr[k] = arr[k+1];
}
arr[length-1] = 0;
}
}
}
When shifting array, you may replace first element (containing number equal to value) with the same value from other element. In that case, you need to restart iteration on this element again, e.g.:
void arrayShift(int arr[], int length, int value)
{
for(int i = 0; i<length; i++)
{
if(arr[i] == value)
{
for (int k = i; k<length-1 ; k++)
{
arr[k] = arr[k+1];
}
arr[length-1] = 0;
i--; // <-- this
}
}
}
Your algorithm for shifting is wrong: you fail to adjust i on removal. In addition, it is rather inefficient: you can do this in a single loop with two indexes - r for reading and w for writing. When you see the value you want to keep, adjust both the reading and the writing index. Otherwise, increment only the reading index.
Once the reading index reaches the count, the writing index indicates how many items you have left. You need to return it to the caller somehow, otherwise he wouldn't know where the actual data ends. You can return the new length as the return value of your function, or take length as a pointer, and adjust it in place.
int arrayShift(int arr[], int length, int value) {
int r = 0, w = 0;
for (; r != length ; r++) {
if (arr[r] != value) {
arr[w++] = arr[r];
}
}
return w;
}
Here is how you call it:
int inputarray[]={9,8,9,9,9,9,6};
int length = 7;
int value = 9;
int newLen = arrayShift(inputarray, length, value);
for (int i = 0 ; i != newLen ; i++) {
printf("%d ", inputarray[i]);
}
printf("\n");
Demo.