My programme uses recursion for divide and conquer but i am getting an infinite loop due to reasons unknown. and i am still getting the unsorted array as an answer
/**
* MergeSort.c
*
* Uses recursion for divide and conquer
*
*
* Implements merge sort for an array
*/
Initialize the method calls for merge and merge sort
#include<stdio.h>
#include<conio.h>
void merge(int array[6],int beg,int mid,int end);
void mergesort(int array[6],int beg,int end);
Initialize the display functions
void display(int array[6]);
int main(void)
{
// Initializes the array
int array[6]={3,1,2,9,5,4};
// Initialize the beginning and the end
int beg=0, end=5;
// Implement the Merge Sort
mergesort(array,beg,end);
getch();
}
void mergesort(int array[6],int beg,int end) //Calls Initial merge sort
{
int mid;
mid=(beg+end)/2;
while (beg<end)
{
mergesort(array,beg,mid); //Left part of the array
mergesort(array,mid+1,end); //Right part of the array
merge(array,beg,mid,end); //merge two sorted arrays
}
}
//merges two subarrays
void merge(int array[6],int beg,int mid,int end)
{
int temp[6]; //Declare a temp array for storing the sorted elements
int k=beg;
int i=beg; //initialize the pointers for two sub arrays
int j=mid;
while (i<mid && j<end)
{
if(array[i]<array[j])
{
temp[k]=array[i];
i++;
k++;
}
else
{
temp[k]=array[j];
j++;
k++;
}
}
//Clearing any remaining elements in the sub array
while (i<mid)
{
temp[k]=array[i];
i++;
k++;
}
//Clearing any remaining elements in the sub array
while (j<end)
{
temp[k]=array[j];
j++;
k++;
}
//Reassign the sorted elements to the original array
for(i=0,k=0;i<end,k<end;i++,k++)
{
array[i]=temp[k];
}
//prints the individual array elements
display(array); //display array
}
//Displays the entire array
void display(int array[6])
{
//prints the individual array elements
for (int i=0;i<6;i++)
{
printf("%d ",array[i]); //prints the individual array elements
}
printf("\n"); //Enter a new line after every iteration
}
Well, from mergesort function,
while (beg<end)
{
mergesort(array,beg,mid); //Left part of the array
mergesort(array,mid+1,end); //Right part of the array
merge(array,beg,mid,end); //merge two sorted arrays
}
beg and end won't be editted. So it will do somethingin this loop forever.
I think you should change from while into if.
And moreover, if your end is 5 (last index in that array/segment) the last element in the segment won't be sorted. That's mean this array won't be sorted. You have to change to...
while (i<mid && j<=end) //from j<end to j<=end and for another loop
{
if(array[i]<array[j])
{
temp[k]=array[i];
i++;
k++;
}
else
{
temp[k]=array[j];
j++;
k++;
}
}
Good luck on DQ<3
Related
50
/ \
30 70 (( which should return 50+70=120 ))
int MyFunction(struct node *root){
struct node *ptr=root;
int leftsum=0;
int rightsum=0;
if(ptr==NULL){
return;
}
else{
MyFunction(ptr->left);
leftsum=leftsum+ptr->key;
MyFunctipn(ptr->right);
rightsum=rightsum+ptr->key;
return (root->key+max(leftsum,rightsum));
}
}
for that, I've written this code. Maybe it is wrong so please help me as I'm new in this field. I want to write a recursive code such a way that it compares two leaf node(left and right) and returns the maximum to the parent nood.
The recursive function should look something like this:
int getMaxPath(Node* root){
// base case, We traveled beyond a leaf
if(root == NULL){
// 0 doesn't contribute anything to our answer
return 0;
}
// get the max current nodes left and right children
int lsum = getMaxPath(root->left);
int rsum = getMaxPath(root->right);
// return sum of current node value and the maximum from two paths starting with its two child nodes
return root->value + std::max(lsum,rsum);
}
Full code:
#include <iostream>
struct Node{
int value;
Node* left;
Node* right;
Node(int val){
value = val;
left = NULL;
right = NULL;
}
};
// make a tree and return a pointer to it's root
Node* buildTree1(){
/* Build tree like this:
50
/ \
30 70
*/
Node* root= new Node(50);
root->left = new Node(30);
root->right = new Node(70);
}
int getMaxPath(Node* root){
if(root == NULL){
// 0 doesn't contribute anything to our answer
return 0;
}
int lsum = getMaxPath(root->left);
int rsum = getMaxPath(root->right);
return root->value + std::max(lsum,rsum);
}
int main() {
using namespace std;
Node* root = buildTree1();
int ans = getMaxPath(root);
cout<< ans <<endl;
return 0;
}
int Sum(struct node *root)
{
if(root->left == NULL && root->right== NULL)
return root->key;
int lvalue,rvalue;
lvalue=Sum(root->left);
rvalue=Sum(root->right);
return root->key+max(lvalue,rvalue);
}
int max(int r,int j)
{
if(r>j)
return r;
else
return j;
}
Code :
#include <stdio.h>
#include <stdlib.h>
#define N 5
typedef struct list
{
int data;
struct list * next;//self referenced structure
}slist;
void displayList(slist * start)
{
slist * temp;
if(start==NULL)
{
printf("Empty Linked List");
return;
}
for(temp=start;temp!=NULL;temp=temp->next)
printf("%d ",temp->data);
return;
}
void insertLast(slist * * start,slist * node)
{
slist * temp;
if(start==NULL){
(* start)=node;
return;
}
temp=(* start);
while((temp->next)!= NULL)
temp=temp->next;
temp->next=node;
return;
}
int main()
{
int i,j;
//slist * node;
char Ans;
/*printf("Write the number of vertices\n");
scanf("%d",&N);*/
slist * start[N];
for(i=0;i<N;i++)
start[i]=NULL;
for(i=0;i<N;i++)
{
for(j=i+1;j<N;j++)
{
printf("Is there a connection between V[%d] and V[%d]\n",(i+1),(j+1));
scanf(" %c",&Ans);
if(Ans=='y'||Ans=='Y')
{
slist * node1=(slist *)malloc(sizeof(slist));
node1->data=(j+1); node1->next=NULL;
insertLast(&start[i],node1);enter code here
slist * node2=(slist *)malloc(sizeof(slist));
node2->data=(i+1); node2->next=NULL;
insertLast(&start[j],node2);
}
}
}
for(i=0;i<N;i++)
{
displayList(start[i]);
printf("\n");
}
return 0;
}
The above code is showing segmentation fault at the line where while((temp->next)!=NULL) is written whereas while creation of linked lists, the same insertLast worked just fine. What is the fault in the code?
Your program crashed as you are checking if start is NULL or not. But that does not guarantee that *start is also not NULL. In such situation, temp gets NULL and in while loop temp->next actually trying to access next element of NULL pointer and that is why the crash.
Changing this line -
if(start==NULL)
to
if(*start==NULL)
in insertLast() will fix the crash.
I also recommend to use a debugger like gdb to debug such issues.
I'm working on an Arduino project where I need to build (and work with) a two-dimensional array at runtime. I've been poking around looking for a solution, but I've had no luck. I found an example of a dynamic one-dimentional array helper here: http://playground.arduino.cc/Code/DynamicArrayHelper, so i've been trying to adopt that code for my use. I created a library using the following code:
My Header file:
#ifndef Dynamic2DArray_h
#define Dynamic2DArray_h
#include "Arduino.h"
class Dynamic2DArray
{
public:
Dynamic2DArray( bool sorted );
//Add an integer pair to the array
bool add( int v1, int v2);
//Clear out (empty) the array
bool clear();
//Get the array item in the specified row, column
int getValue(int row, int col);
//Get the number of rows in the array
int length();
private:
int _rows;
void * _slots;
bool _sorted;
void _sort();
};
#endif
The library's code:
#include "Arduino.h"
#include "Dynamic2DArray.h"
#define ARRAY_COLUMNS 2
int _rows;
void * _slots;
bool _sorted;
Dynamic2DArray::Dynamic2DArray(bool sorted) {
//Set our local value indicating where we're supposed to
//sort or not
_sorted = sorted;
//Initialize the row count so it starts at zero
_rows = 0;
}
bool Dynamic2DArray::add( int v1, int v2) {
//Add the values to the array
//implementation adapted from http://playground.arduino.cc/Code/DynamicArrayHelper
//Allocate memory based on the size of the current array rows plus one (the new row)
int elementSize = sizeof(int) * ARRAY_COLUMNS;
//calculate how much memory the current array is using
int currentBufferSize = elementSize * _rows;
//calculate how much memory the new array will use
int newBufferSize = elementSize * (_rows + 1);
//allocate memory for the new array (which should be bigger than the old one)
void * newArray = malloc ( newBufferSize );
//Does newArray not point to something (a memory address)?
if (newArray == 0) {
//Then malloc failed, so return false
return false;
}
// copy the data from the old array, to the new array
for (int idx = 0; idx < currentBufferSize ; idx++)
{
((byte*)newArray)[idx] = ((byte *)_slots)[idx];
}
// free the original array
if (_slots != NULL)
{
free(_slots);
}
// clear the newly allocated memory space (the new row)
for (int idx = currentBufferSize; idx < newBufferSize; idx++)
{
((byte *)newArray)[idx] = 0;
}
// Store the number of rows the memory is allocated for
_rows = ++_rows;
// set the array to the newly created array
_slots = newArray;
//Free up the memory used by the new array
free(newArray);
//If the array's supposed to be sorted,
//then sort it
if (_sorted) {
_sort();
}
// success
return true;
};
int Dynamic2DArray::length() {
return _rows;
};
bool Dynamic2DArray::clear() {
//Free up the memory allocated to the _slots array
free(_slots);
//And zero out the row count
_rows = 0;
};
int Dynamic2DArray::getValue(int row, int col) {
//do we have a valid row/col?
if ((row < _rows) && (col < ARRAY_COLUMNS)) {
//Return the array value at that row/col
return _slots[row][col];
} else {
//No? Then there's nothing we can do here
return -1;
}
};
//Sorted probably doesn't matter, I can probably ignore this one
void _sort() {
}
The initial assignment of the _slots value is giving me problems, I don't know how to define it so this code builds. The _slots variable is supposed to point to the dynamic array, but I've got it wrong.
When I try to compile the code into my project's code, I get the following:
Arduino: 1.8.0 (Windows 10), Board: "Pro Trinket 3V/12MHz (USB)"
sketch\Dynamic2DArray.cpp: In member function 'int Dynamic2DArray::getValue(int, int)':
sketch\Dynamic2DArray.cpp:83:22: warning: pointer of type 'void *' used in arithmetic [-Wpointer-arith]
return _slots[row][col];
^
Dynamic2DArray.cpp:83: error: 'void*' is not a pointer-to-object type
Can someone please help me fix this code? I've posted the files to https://github.com/johnwargo/Arduino-Dynamic-2D-Array-Lib.
The code you took was for a 1D dynamic array; the modifications for a 2D array are too tricky. Give up these horrors.
I think there is no reason you use dynamic array. You can assume that size max is ROW_MAX * COL_MAX, so you can define a static array int array[ROW_MAX][COL_MAX].
on one hand if you defined a dynamic array, you could free space when you dont use it anymore and take advantage of it for other work. I dont know if this is your case.
on the other hand if you define a static array (on UNO), you have 32kB available on program space, instead of 2kB available on RAM.
Because of the difference 32kB / 2kB, there are very few chances you can get bigger array with dynamic allocation.
I have written the program to add two integer numbers of very large sizes wherein each digit is stored in a node of linked list.When i run the program my display method is not working.Can anyone tell me what is wrong with my display() method?
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int digit;
struct node* link;
}NODE;
typedef NODE* NODEPTR;
typedef struct stack{
int arr[100];
int top;
}STACK;
int isEmpty(STACK* s){
if(s->top==-1)
return 1;
return 0;
}
void push(STACK* s,int item){
s->arr[++s->top]=item;
}
int pop(STACK* s){
if(isEmpty(s))
return -999;
else
return s->arr[s->top--];
}
NODEPTR insertNode(NODEPTR head,int val){
NODEPTR curr,temp;
temp=(NODEPTR)malloc(sizeof(NODE));
temp->digit=val;
temp->link=NULL;
if(head->link==NULL)
return temp;
else{
curr=head->link;
while(curr->link!=NULL){
curr=curr->link;
}
curr->link=temp;
}
return head;
}
NODEPTR getNumber(NODEPTR head){
int n,i,val;
printf("enter the number of digits in the number\n");
scanf("%d",&n);
for(i=1;i<=n;i++){
printf("enter the digit at %dth position(in increasing power of 10)\n",i);
scanf("%d",&val);
head=insertNode(head,val);
}
return head;
}
NODEPTR add(NODEPTR h1,NODEPTR h2,NODEPTR h3){
NODEPTR curr1,curr2;
curr1=h1->link;
curr2=h2->link;
int carry=0,sum=0;
while(curr1!=NULL && curr2!=NULL){
sum=carry+curr1->digit+curr2->digit;
if(sum>9){
sum=sum-10;
carry=1;
}
else
carry=0;
h3=insertNode(h3,sum);
sum=0;
}
while(curr1!=NULL){
sum=carry+curr1->digit;
if(sum>9){
sum=sum-10;
carry=1;
}
else
carry=0;
h3=insertNode(h3,sum);
sum=0;
}
while(curr2!=NULL){
sum=carry+curr2->digit;
if(sum>9){
sum=sum-10;
carry=1;
}
else
carry=0;
h3=insertNode(h3,sum);
sum=0;
}
return h3;
}
void display(NODEPTR head){
STACK s;//stack to store digits of the number and then display
s.top=-1;
NODEPTR curr=head->link;
while(curr!=NULL){
push(&s,curr->digit);//pushing digits to the stack
curr=curr->link;
}
while(!isEmpty(&s))
printf("%d",pop(&s));//poping the digits from stack so that the number appears in correct order
}
int main(){
NODEPTR h1,h2,h3;
h1=(NODEPTR)malloc(sizeof(NODE));//dummy/header node for linked list that stores the first number
h1->link=NULL;
h2=(NODEPTR)malloc(sizeof(NODE));//dummy/header node for the linked list that stores the second number
h2->link=NULL;
h3=(NODEPTR)malloc(sizeof(NODE));//dummy/header node for linked list that stores the sum of both the numbers
h3->link=NULL;
h1=getNumber(h1);//to get first number from user
h2=getNumber(h2);//to get second number from user
h3=add(h1,h2,h3);//to add both the numbers and store it in the h3 linked list
printf("First number is:");
display(h1);//to display the first number
printf("second number is:");
display(h2);//to display the second number
printf("sum of the numbers is:");
display(h3);//to display the sum
return 0;
}
On running the program the output of display() method I get is:
first number is:second number is:sum of numbers is:
Here is my code for a texas old 'em poker program:
I have tried debugging this for hours and have looked everywhere! I probably have some very fundamental flaw in my knowledge of pointers and using malloc but I have no idea why this happens:
The program compiles fine and runs fine until it reaches the malloc function trying to assign a memory address to the cards variable cards *individualhand. The printf if statement just before confirms it is a NULL pointer and can be assigned.
Also included are a couple of the other functions. The functions printhand (prints the poker hand and islegal (detects illegal card inputs) I have omitted.
This might be a lot of code at once but I have a feeling that the answer is pretty simple
The error occurs in the handget function about half way down the code:
int hander(cards **handPtr,int counter) {
int i, nr_of_cards = 2;
char rawsuit, rawcard[4];
if(counter==0){
// allocate the required amount of memory for your cards
(*handPtr) = (cards *) malloc(nr_of_cards * sizeof(cards));
}
// ask for the cards
for (i=0; i<nr_of_cards; i++) do {
scanf("%3s", &rawcard);
rawsuit = rawcard[0];
if (rawcard[1]=='1') {
if (rawcard[2]=='0') {
(*handPtr)[i].value = ten;
} else {
(*handPtr)[i].value = zero;
}
} else if (rawcard[1]=='2') {
(*handPtr)[i].value = two;
} else if (rawcard[1]=='3') {
(*handPtr)[i].value = three;
} else if (rawcard[1]=='4') {
(*handPtr)[i].value = four;
} else if (rawcard[1]=='5') {
(*handPtr)[i].value = five;
} else if (rawcard[1]=='6') {
(*handPtr)[i].value = six;
} else if (rawcard[1]=='7') {
(*handPtr)[i].value = seven;
} else if (rawcard[1]=='8') {
(*handPtr)[i].value = eight;
} else if (rawcard[1]=='9') {
(*handPtr)[i].value = nine;
} else if (rawcard[1]=='J') {
(*handPtr)[i].value = jack;
} else if (rawcard[1]=='Q') {
(*handPtr)[i].value = queen;
} else if (rawcard[1]=='K') {
(*handPtr)[i].value = king;
} else if (rawcard[1]=='A') {
(*handPtr)[i].value = ace;
} else {
(*handPtr)[i].value = zero;
}
switch (rawsuit) {
case 'h':
(*handPtr)[i].suit = hearts;
break;
case 'd':
(*handPtr)[i].suit = diamonds;
break;
case 'c':
(*handPtr)[i].suit = clubs;
break;
case 's':
(*handPtr)[i].suit = spades;
break;
default:
(*handPtr)[i].value = zero;
}
} while (!islegal(*handPtr, i+1));
return nr_of_cards;
}
int handget(cards **playerhand,cards *thishands, int handsize) {
cards *player,*individualhand=NULL;
int i,playerhandsize=2,j=0,nr_players,phandsize,counter=0, individualhandsize;
printf("Please enter the number of players: ");
scanf("%d",&nr_players);
(*playerhand) = (cards *) malloc(((playerhandsize*nr_players)*sizeof(cards))+(handsize*sizeof(cards)));
handcat(playerhand,thishands,handsize);
for (i=1;i<=nr_players;i++){
do {
printf("Please enter the cards for player %d: ",i);
phandsize = (i*hander(&player,counter))+handsize;
playerflopcat(playerhand,player,j,phandsize,handsize);
counter++;
} while (!islegal(*playerhand, phandsize));
j++;
}
printf("The cards on the table are:\n");
printhand(thishands,handsize);
for (i=1;i<=nr_players;i++){
printf("The private cards of player %d are ",i);
printhand(*playerhand+(handsize+(2*(i-1))),2);
}
for (i=1;i<=nr_players;i++){
individualhandsize = handsize + playerhandsize;
printf("individualhandsize=%i\n",individualhandsize);
if(individualhand==NULL){
printf("individualhand EQUALS NULL!");
}
individualhand=((cards *) malloc(individualhandsize*sizeof(cards)));//THIS IS WHERE IT ALL GOES WRONG!!
printf("made it this far chaps!!\n");
memcpy(individualhand,playerhand,individualhandsize*sizeof(cards));
printf("made it this far chaps!!\n");
printf("The cards available to player %d are ",i);
/*i have yet to add code here*/
}
return nr_players;
}
void handcat(cards **playerhand,cards *playerx, int nr_cards){
memcpy(*playerhand,playerx,nr_cards*sizeof(cards));
return;
}
void playerflopcat(cards **playerhand,cards *playerx,int j, int nr_cards,int handsize){
memcpy((*playerhand+(handsize+(2*j))),playerx,nr_cards*sizeof(cards));
return;
}
The method I am using to call function handget:
int main(void) {
int handsize=0, playerhandsize=0, nr_of_players=0;
cards *thishand, *playerhands;
handsize = flop(&thishand);
//flop asks user for list of cards
//user inputs(e.g. "d5 d6 d7 d8 d9")
//flop returns int handsize=5
printhand(thishand,handsize);
//printhand returns a list (of handsize length) of the cards making up thishand
//e.g. "d5 d6 d7 d8 d9"
nr_of_players = handget(&playerhands,thishand,handsize);
//handget is the function we're looking at
//takes thishand which was assigned (using function flop) to a space in memory containing list of cards ("d5 d6 d7 d8 d9")
//also uses int handsize = 5
//playerhands is assigned in function handget
// printhand(playerhands,(handsize+(nr_of_players*2)));
return 0;
}
Just for completeness' sake I have include function flop
int flop(cards **handPtr) {
int i,*q=NULL,n=NULL;
int j[5]={0,0,0,0,0};
int k[5]={1,1,1,1,1},nr_of_cards = 5;//for more/less cards CHANGE HERE!
char rawsuit, rawcard[4];
// allocate the required amount of memory for your cards
(*handPtr) = (cards *) malloc(nr_of_cards * sizeof(cards));
n=memcmp(j,k,sizeof(j));
while(n!=0) {
printf("Please input the five cards on the table: ");
q=rawtoflop(*handPtr,nr_of_cards);
for (i=0;i<nr_of_cards;i++) {
j[i]=*(q+i);
}
n=memcmp(j,k,sizeof(j));
}
return nr_of_cards;
}
The code for islegal:
int islegal(cards *hand, int nr_of_cards) {
int i, fulldeck[4][13]={0};
int current_value, current_suit;
cards *current_card = hand;
int legal = 1;
for (i=0; i<nr_of_cards; i++) {
current_value = (int) (*current_card).value;
current_suit = (*current_card).suit;
// if the current card has value zero, it is not a valid hand
if (current_value==0) {
legal = 0;
break;
}
//check if the current card already appears, if yes invalid hand, if no,
//change the flag for that card in the full deck.
//Since (two) will correspond to fulldeck[.][0] there is a -2 offset.
if ( (fulldeck[current_suit][current_value - 2]) > 0 ) {
legal = 0;
break;
} else {
fulldeck[current_suit][current_value - 2]++;
}
current_card++;
}
return legal;
}
You are calling the function handget as :
nr_of_players = handget(&playerhands,thishand,handsize);
That's fine, and it'll compile, because handget does in fact expect a cards **. However, you have never allocated space for a cards **.playerhands is still a cards* and taking its address and trying to allocate memory there may be why the malloc is failing.
Can you try running this by declaring cards ** playerhands instead of the card * that it currently is?