Iterating inside an array, using similar methods but getting different results - c++

I don't understand the difference between these two processes (This is all part of a bigger program):
This is the working version:
for (int i = 0; i < 32; i++)
{
int cNumber = decNumb % 2;
binNum[32 - i] = cNumber;
decNumb = decNumb / 2;
}
and this is the version where I get the unintended result:
for(int i = 0; i < 32; i++)
{
int j = 0;
int cNumber = decNum % 2;
binNum[32-j] =cNumber;
decNumb = decNumb / 2;
j++;
}
I don't understand the difference why doing it with an extra variable j gives me a different result. Shouldn't both versions give me the same outcome?
Any help would be appreciated!
edit: added missing opening bracket (typo)

for(int i = 0; i < 32; i++)
int j = 0;
int cNumber = decNum % 2;
binNum[32-j] =cNumber;
decNumb = decNumb / 2;
j++;
}
This does not run because it does not have an open brace for the for loop. In addition, j is reiterated and reset to 0 every loop, so you would not get your desired result. You could have done:
int j = 0;
for(int i = 0; i < 32; i++){
int cNumber = decNum % 2;
binNum[32-j] =cNumber;
decNumb = decNumb / 2;
j++;
}
Otherwise, both codes should run equally fine.

Related

C++ How to memcpy int to char[]

I want to convert time from int to string in a fast way.The sprintf is too slow. I write a test code like this:
int year = 2020;
int month = 8;
int day = 16;
char* log = "test log";
char output[1024];
char timeformat[] = "[0000:00:00] ";
int n = strlen(timeformat);
/*------------------1start---------------*/
for (int i = 0; i < 100000000; ++i) {
for (int j = 0; j < 4; ++j) {
timeformat[4-j] += year%10;
year /= 10;
}
for (int j = 0; j < 2; ++j) {
timeformat[7-j] += month%10;
month /= 10;
}
for (int j = 0; j < 2; ++j) {
timeformat[10-j] += day%10;
day /= 10;
}
memcpy(output, timeformat, n);
memcpy(output+n,log, strlen(log));
}
/*------------------1end-----------------*/
/*------------------2start---------------*/
for (int i = 0; i < 100000000; ++i) {
sprintf(mem,"%d:%d:%d %s",year,month,day,log);
}
/*------------------2end-----------------*/
The first code cost 2~3seconds for average, and the second is much more slower than first one for 13~20s.
But the first code is too ugly. Is there any beautiful way to convert int to char*?

Comparing pixels in alpha-trimmed filter

I have the following problem. I have written code for alpha-trimmed filter in opencv library. I think that it is properly constructed but I don't know how to compare two 3 channels pixels during sorting a 'window with pixels'. In my code it is done but comparing two but it is impossible for vectors. I assume that i should compare it one channel and after second and so on. Have you any hints for me, or could you propose some modifications in my code. This is my code.
int alphatrimmed(Mat img, int alpha)
{
Mat img9 = img.clone();
const int start = alpha;
const int end = 9 - alpha;
//going through whole image
for (int i = 1; i < img.rows - 1; i++)
for (int j = 1; j < img.cols-1; j++)
{
int k = 0;
Vec3b element[9];
//selecting elements
for (int m = i - 1; m < i + 2; m++)
for (int n = j - 1; n < j + 2; n++)
element[k++] = img.at<Vec3b>(m*img.cols + n);
for (int i = 0; i < end; i++)
{
int min = i;
for (int j = i + 1; j < 9; j++)
if (element[j] < element[min])
min = j;
Vec3b temp = element[i];
element[i] = element[min];
element[min] = temp;
}
const int result = (i - 1)*(img.cols - 2) + j - 1;
img9.at<Vec3b>(result) = element[start];
for (int j = start + 1; j < end; j++)
img9.at<Vec3b>(result) += element[j];
img9.at<Vec3b>(result) /= 9 - alpha;
}
namedWindow("AlphaTrimmed Filter", WINDOW_AUTOSIZE);
imshow("AlphaTrimmed Filter", img9);
return 0;
}
Thank you for your time spent on solving my problem.

Proper use of rand()?

So the idea with this is that it takes in the 9x9 array that's in main, and swaps around rows. It can only swap rows 1-3 with 1-3, 4-6 with 4-6 and 7-9 with 7-9. For some reason every once in awhile it will swap one from 4-6 with one from 7-9, and also sometimes it will give me absolute garbage for one of the rows 7-9. I've spent the better part of 2 hours trying to figure out the proper way to use rand() in this context and I am sure I am not doing it correctly. Any ideas?
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
void printSudoku(int square[9][9]) // Prints out the 9x9 array
{
for(int i = 0; i < 9; i++)
{
for(int j = 0; j < 9; j++)
{
cout << square[i][j];
}
cout << endl;
}
}
void swapRows(int square[9][9]) // Randomly generates numbers, within bounds, and swaps those rows with each other
{
int temp[1][9];
srand(time(NULL));
int n = (rand() % 2) + 0;
int m = (rand() % 2) + 0;
for(int i = 0; i < 9; i++)
{
temp[0][i] = square[n][i];
}
for(int j = 0; j < 9; j++)
{
square[n][j] = square[m][j];
}
for(int k = 0; k < 9; k++)
{
square[m][k] = temp[0][k];
}
int a = (rand() % 5) + 3;
int b = (rand() % 5) + 3;
for(int i = 0; i < 9; i++)
{
temp[0][i] = square[a][i];
}
for(int j = 0; j < 9; j++)
{
square[a][j] = square[b][j];
}
for(int k = 0; k < 9; k++)
{
square[b][k] = temp[0][k];
}
int c = (rand() % 8) + 6;
int d = (rand() % 8) + 6;
for(int i = 0; i < 9; i++)
{
temp[0][i] = square[c][i];
}
for(int j = 0; j < 9; j++)
{
square[c][j] = square[d][j];
}
for(int k = 0; k < 9; k++)
{
square[d][k] = temp[0][k];
}
}
int main() {
int square[9][9] = {1,2,3,4,5,6,7,8,9,
4,5,6,7,8,9,1,2,3,
7,8,9,1,2,3,4,5,6,
2,3,4,5,6,7,8,9,1,
5,6,7,8,9,1,2,3,4,
8,9,1,2,3,4,5,6,7,
3,4,5,6,7,8,9,1,2,
6,7,8,9,1,2,3,4,5,
9,1,2,3,4,5,6,7,8,};
printSudoku(square);
swapRows(square);
cout << endl;
printSudoku(square);
return 0;
}
When you call rand(), it gives you a number between 0 and RAND_MAX. When you use something like rand() % 8, it gives you a random number between 0 and 7. This is more range than you want the random numbers to span. You only want the random numbers to be from 0 through 2 (0, 1, or 2), then add the offset for the first row.
For example, (rand() % 8) + 6 gives you a random number from 0+6=6 through 7+6=13. Instead, use (rand() % 3) + 6 to give you 0+6=6 through 2+6=8.

cin causes runtime error

Here's the problem https://www.hackerrank.com/challenges/extra-long-factorials
Here's my code
#include <iostream>
using namespace std;
int main(){
int n;
cin >> n;
int product[200];
for (int i = 0; i < 200; i++)product[i] = 0;
product[0] = 1;
for (int i = 1; i <= n; i++){
int a[200], res[200];
for (int j = 0; j < 200; j++)a[j] = 0, res[j] = 0;
int n = i;
int k = 0;
while(n != 0){
a[k] = n % 10;
n = n / 10;
k++;
}
int at[200][200];
for (int p = 0; p < 200; p++){
for (int h = 0; h < 200; h++){
at[p][h] = 0;
}
}
int carry = 0;
for (int x = 0; x < 200; x++){
for (int d = 0; d < 200; d++){
at[x][x+d] = ((product[d] * a[x]) % 10) + carry;
carry = (product[x] * a[d]) / 10;
}
}
int carry2, temp;
for (int u = 0; u < 200; u++){
temp = 0;
for (int e = 0; e < 200; e++){
temp += at[e][u];
}
temp = (temp + carry2);
carry2 = temp/10;
res[u] = temp %10;
product[u] = res[u];
}
}
int f = 0;
for (; f < 200; f++){
if(product[200-f-1] != 0)break;
}
for (; f < 200; f++){
cout << product[200-f-1];
}
return 0;
}
It runs fine on gcc on my mac and gives a correct answer. However it gives a runtime error on the online judge as well as ideone.
I've debugged the code and the error is caused by cin >> n; It runs fine without it and gives a correct answer (which is 1). The test input that caused the error is 25 so it's not a big number. I dont know exactly what's the problem or how is it causing the error. Thank you.
This is the problem:
at[x][x+d] = ...
because both x and d run from 0 to 200, but at is an array on the stack, with size: [200][200] so obviously x+d will overwrite the code coming after the array declaration.
This is a classical buffer overflow :)
(Obviously, initializing carry2 won't hurt either, but not doing that will not give the core dump at 0x0, just some unexpected behaviour)

Putting String into a 2D Matrix in Objective C++

So I'm using Objective C++ and I want to put a string into a 4 by X (X = length of string/4) int array by using the ASCII code. The first quarter of the string (which is formatted to fit completely into a 4 by X array) is supposed to go in [0][col], the second quarter into [1][col], the third quarter into [2][col] and the fourth quarter into [3][col]. So I tried the following with 4 for loops, but it doesnt work at all, and I just can't seem to get it to work somehow. Any suggestions would be greatly appreciated.
textMatrix is the matrix in which I want to put the NSString/ASCII number, and inputFinal is the NSString itself. Length * (1/4) or whatever is also always going to be an integer.
for(int i = 0; i < length*(1/4); i++)
{
textMatrix[0][i] = (int)[inputFinal characterAtIndex: i];
}
for(int j = length*(1/4); j < length*(2/4); j++)
{
textMatrix[1][j] = (int)[inputFinal characterAtIndex: j];
}
for(int k = length*(2/4); k < length*(3/4); k++)
{
textMatrix[2][k] = (int)[inputFinal characterAtIndex: k];
}
for(int l = length*(3/4); l < length; l++)
{
textMatrix[3][l] = (int)[inputFinal characterAtIndex: l];
}
You can rewrite your 4 loops in 1 loop:
for(int i = 0; i < length; i++)
{
textMatrix[i/4][i%4] = (int)[inputFinal characterAtIndex:i];
}
I don't think I understand what you're trying to do..
Given a string: "Here";
do you want:
Matrix[0][0] = 'H';
Matrix[1][1] = 'e';
Matrix[2][2] = 'r';
Matrix[3][3] = 'e';
If so then this works:
#import <objc/objc.h>
#import <objc/Object.h>
#import <Foundation/Foundation.h>
#implementation TestObj
int main()
{
NSString* str = #"Here";
int matrix[4][4] = {0};
for (int i = 0, j = 0; j < 4; ++j)
{
matrix[i][i++] = (int) [str characterAtIndex: j];
}
for (int i = 0; i < 4; ++i)
{
for (int j = 0; j < 4; ++j)
{
printf("%c", (char)matrix[i][j]);
}
}
return 0;
}
#end
The above prints Here.
actually a double loop like so ended up working best for me:
int index = 0;
for(int row = 0; row < 4; row++)
{
for(int col = 0; col < length/4; col++)
{
textMatrix[row][col] = (int)[inputFinal characterAtIndex:index];
index++;
}
}