How the recursion would be? - c++11

I have a function with "for" loop and I want to implement the recursion to replace the for loop. However I cannot use the global variables ie 'counter' ,so now I am logically confused how can I implement the recursion.
int makeHorizontalLine(char canvas[MAX_ROW][MAX_COL], int row, int col, int length){
int counter = 0;
for (int i =0; i<length ; i++){
if ((i+col) >= MAX_COL)
return counter;
canvas[row][i+col] = '-';
counter += 1;
}
This is what I tried in the recursion.
int makeHorizontalLine(char canvas[MAX_ROW][MAX_COL], int row, int col, int length){
if (col >= MAX_COL)
return length;
if (length != 0){
if (col < MAX_COL){
makeHorizontalLine(canvas, row, col+1, length-1);
return length;
}
}
As I cannot use the global variable so I tried to assign recursion such as
makeHorizontalLine(canvas, row, col+1; length -1)
and when length = 0 to stop the recursion, but I cannot return what I want in the recursion if
if ((i+col) >= MAX_COL)
So I got logically stucked in the recursion. Please give me some advice. Appreciate.

Related

Heap updating order

here's a working code for heapsort algorithm, my question is if in heap creation I swap the condition in the code with
for ( int i = 0 ; i < dim/2-1; i ++)
that I think it's the for cycle but in reverse order and I think that the process of updating the heap is quite the same (in my head we go trough updating the heap condition for every index from 0 to the end of the array),why the algorithm won't work anymore? It's wrong written the other condition or simply the algorithm is designed to work decreasing the index i? Thank you
#include <stdio.h>
void Scambia( int *px, int *py);
void Aggiornaheap( int *pa, int i, int j);
int main(void)
{
int a[256];
int n;
int dim = 0;
// Lettura dell’input da tastiera
while (scanf("%d\n", &n) == 1)
{
a[dim] = n;
dim++;
}
// heap creation
for ( int i = dim/2-1 ; i >= 0; i --)
{
Aggiornaheap(a, i, dim);
}
//Heapsort
for ( int i = dim-1; i >= 0; i --)
{
Scambia(&a[0], &a[i]);
Aggiornaheap(a, 0, i-1);
}
for ( int i = 0; i < dim; i++)
printf("%d ", a[i]);
printf("\n");
return 0;
}
void Scambia( int *px, int *py)
{
int temp;
temp = *px;
*px = *py;
*py = temp;
}
void Aggiornaheap( int *pa, int i, int j)
{
int k;
if ( 2*i == j )
{
if ( pa[i] < pa[j])
Scambia(&pa[i], &pa[j]);
}
if ( 2*i < j )
{
if ( pa[2*i] > pa[2*i+1] )
k = 2*i;
else k = 2*i+1;
if ( pa[i] < pa[k])
{
Scambia(&pa[i], &pa[k]);
Aggiornaheap(pa, k, j);
}
}
}
It is necessary that the nodes are visited in reverse order. The algorithm will not do its job correctly if you change that order.
Take for instance this input tree that needs to be heapified into a min-heap: [2,4,3,1], which can be visualised as follows:
2
/ \
4 3
/
1
Then note how it will be impossible for the 1 value to bubble to the top, when you alter the for loop to go forward. Let's just try this. When i==0 nothing is swapped, because 2 is less than its children. When i==1 then 4 will be swapped with 1, and then the loop has finished. Clearly, this has not created a valid heap.
If however we start with i==1, which triggers the swap of 1 with 4, and only then have i==0, then we will again swap 1 to move up:
1
/ \
2 3
/
4
One comment about your code. It looks like you work with zero-indexed arrays, with the root element at 0, but in that case the children are at i*2+1 and i*2+2, not one less like we see in your code.

Weird Outputs with Binary Search

So, this code has weird outputs when running on Command-Line with different outputs, I also get a segfault (core dumped) with some cases. I suspect it's to do with the min, max, mid bounds I have set. Please help me out as to what might be going wrong.
the code is searching based off two vectors of type class (Book) where all three elements ISBN,course, and type need to match for the counter to increment. We are searching for number of r in n.
int binary_search(std::vector<Book> n, std::vector<Book> r){
std::sort(n.begin(),n.end());
unsigned int mid;
int count = 0 ;
for (unsigned int i = 0; i < r.size(); i++) {
unsigned int min = 0 ;
unsigned int max = n.size() - 1;
while(max >= min) {
mid = (max + min) / (2);
if((n[mid].isbn == r[i].isbn) && (n[mid].course == r[i].course) && (n[mid].type == r[i].type)) {
count++;
break;
} else if(n[mid].isbn < r[i].isbn){
min = mid + 1;
} else{
max = mid - 1;
}
}
}
return count;
}

Broken Merge Sort

Good morning, Stack Overflow. You guys helped me out on an earlier assignment, and I'm hoping to get a little help on this one.
It's a programming assignment relating to sorts, one part of which is to write a working implementation of merge sort.
I adapted my solution from the pseudocode the professor used in class, but I'm getting an annoying segfault at the indicated location.
This method is sorting an array of structs, with data_t defined as struct pointers.
The struct definition:
typedef struct {
int id;
int salary;
} employee_t;
typedef employee_t* data_t;
They're being sorted by salary, which is a randomly generated number from 40,000 to 90,000.
Here's the actual method
void merge_sort(data_t items[], size_t n)
{
if (n < 2)
return;
size_t mid = (n / 2);
data_t *left = malloc(sizeof(data_t) * mid);
data_t *right = malloc(sizeof(data_t) * (n - mid));
for (int y = 0; y < mid; y++)
{
left[y] = items[y];
}
for (int z = mid; z < n; z++)
{
right[z] = items[z];
}
merge_sort(left, mid);
merge_sort(right, (n - mid));
size_t l, r, i;
l = 0;
r = 0;
for (i = 0; i < (n - 1); i++)
{
if ((l < mid) && ((r >= (n - mid)) || ((left[l]->salary) <= (right[r]->salary))))
{
items[i] = left[l++];
}
else
{
items[i] = right[r++];
}
}
free(left);
free(right);
}
Note that I haven't made it as far as the end, so the array frees might be incorrectly located.
The segfault always occurs when I try to access right[r]->salary, so I'm assuming this is related to a null pointer, or similar. However, I'm extremely new to sorting, and I don't know exactly where to properly implement a check.
Any advice is appreciated greatly.
At first glance there's this fix:
for (int z = mid; z < n; z++)
{
right[z-mid] = items[z];
}

The fastest algorithm for returning max length of consecutive same value fields of matrix?

Here is the given example:
We have the function which takes one matrix and it's number of columns and it's number of rows and returns int (this is gonna be length). For example:
int function (int** matrix, int n, int m)
The question is what's the fastest algorithm for implementing this function so it returns the maximum length of consecutive fields with the same value (doesn't matter if those same values are in one column or in one row, in this example on picture it's the 5 fields of one column with value 8)?
Values can be from 0-255 (grayscale for example).
So in the given example function should return 5.
If this is a bottleneck and the matrix is large, the first optimization to try is to make one pass over the matrix in sequential memory order (row-by-row in C or C++) rather than two. This is because it's very expensive to traverse a 2d array in the other direction. Cache and paging behavior are the worst possible.
For this you will need a row-sized array to track the number of consecutive values in the current run within each column.
int function (int a[][], int m, int n) {
if (n <= 0 || m <= 0) return 0;
int longest_run_len = 1; // Accumulator for the return value.
int current_col_run_len[n]; // Accumulators for each column
int current_row_run_len = 1; // Accumulator for the current row.
// Initialize the column accumulators and check the first row.
current_col_run_len[0] = 1;
for (int j = 1; j < n; j++) {
current_col_run_len[j] = 1;
if (a[0][j] == a[0][j-1]) {
if (++current_row_run_len > longest_run_len)
longest_run_len = current_row_run_len;
} else current_row_run_len = 1;
}
// Now the rest of the rows...
for (int i = 1; i < m; i++) {
// First column:
if (a[i][0] == a[i-1][0]) {
if (++current_col_run_len[0] > longest_run_len)
longest_run_len = current_col_run_len[0];
} else current_col_run_len[0] = 1;
// Other columns.
current_row_run_len = 1;
for (int j = 1; j < n; j++) {
if (a[i][j] == a[i][j-1]) {
if (++current_row_run_len > longest_run_len)
longest_run_len = current_row_run_len;
} else current_row_run_len = 1;
if (a[i][j] == a[i-1][j]) {
if (++current_col_run_len[j] > longest_run_len)
longest_run_len = current_col_run_len[j];
} else current_col_run_len[j] = 1;
}
}
return longest_run_len;
}
You need to pass over each entry of the matrix at least once, so you can't possible do better than O(m*n).
The most straightforward way is to pass over each row and each column once. This will be two passes over the matrix, but the algorithm is still O(m*n).
Any attempt to do it in one pass will probably be a lot more complex.
int function (int** matrix, int n, int m) {
int best=1;
for (int i=0; i<m; ++i) {
int k=1;
int last=-1;
for (int j=0; j<n; ++j) {
if (matrix[i][j] == last) {
k++;
if (k > best) {
best=k;
}
}
else {
k=1;
}
last = matrix[i][j];
}
}
for (int j=0; j<n; ++j) {
int k=1;
int last=-1;
for (int i=0; i<m; ++i) {
if (matrix[i][j] == last) {
k++;
if (k > best) {
best=k;
}
}
else {
k=1;
}
last = matrix[i][j];
}
}
return best;
}

Permutation of integers from an array given lengh

I was interviewed a problem and after that I tested my code, found it wrong.
Not good at recursion. But I can't figure out the problem.
The question is: Given an array range from 0 ~ 9, and a length, for example, 3; generate
all permutations of integers from the given array in given length.
So, for the example:
The permutation should be: 012, 013, 014,..., 345, 346...
Below is my java code, where's the problem? (I think it's the index or the offset part)
And, if there's any better solution!
public void NumPermutation(int[] list, int offset, int[] temp, int index){
if(index == 4){
printarray(temp);
}
for(int count = offset; count < list.length; count++){
temp[index++] = list[count];
int te = list[offset];
list[offset] = list[count];
list[count] = te;
NumPermutation(list, offset, temp, index);
index -= 1;
}
}
public void test(int len){
int[] list = {0,1,2,3,4,5,6,7,8,9};
int[] temp = new int[4];
int index = 0, offset = 0;
NumPermutation(list, offset, temp,index);
}
The problem is that, the offset may increase each time and
it can't even reach the number to the end.
You need to:
Pass offset+1 to the recursive call.
Return in the if-statement.
Reverse your swap after the recursive call.
Replace the 4 with temp.length for a more generic solution.
Also preferably replace index++, index, index -= 1 with index, index + 1 and nothing.
Which results in this code: (replaced printarray with a standard print method, assuming this is Java)
public static void NumPermutation(int[] list, int offset, int[] temp, int index){
if(index == temp.length) {
System.out.println(Arrays.toString(temp));
return;
}
for(int count = offset; count < list.length; count++){
temp[index] = list[count];
// swap
int te = list[offset];
list[offset] = list[count];
list[count] = te;
NumPermutation(list, offset + 1, temp, index + 1);
// reverse swap
te = list[offset];
list[offset] = list[count];
list[count] = te;
}
}
Live demo.

Resources