tag:blogger.com,1999:blog-6294663875929591018.post2775244551291342963..comments2023-09-24T03:12:58.137-07:00Comments on Ramblings of a techie: Compact a given array coding problemBragBoyhttp://www.blogger.com/profile/01173019524783723568noreply@blogger.comBlogger3125tag:blogger.com,1999:blog-6294663875929591018.post-72173262160819793122011-12-12T06:51:11.648-08:002011-12-12T06:51:11.648-08:00@Yogesh - Nice attempt !@Yogesh - Nice attempt !BragBoyhttps://www.blogger.com/profile/01173019524783723568noreply@blogger.comtag:blogger.com,1999:blog-6294663875929591018.post-83219776037484346342011-12-06T19:16:38.009-08:002011-12-06T19:16:38.009-08:00We may do following to recieve exact output as men...We may do following to recieve exact output as mentioned in examples above, where we must keep -1 in array if they are more in numers than non -1s. I chose to go this way:<br /><br />int main()<br />{<br /> int i=0;<br /> int arr[6]= {-1,-1,-1,3,3,3};<br /> printf("The array is as follows: \n");<br /> for(i=0;i<6;i++)<br /> printf("%d\n",arr[i]);<br /> printf("\n\nTime to compact the array\n\n");<br /> int k=0;<br /> for(i=0,k=0;i<6,k<6;i++)<br /> {<br /> if(arr[i]==-1)<br /> {<br /> while(arr[k]==-1 && k<6){<br /> k++;<br /> };<br /> arr[i]=arr[k++];<br /> }<br /> else<br /> {<br /> k++;<br /> }<br /> }<br /> printf("\n\n The last valid index is :%d\n\n", i-1);<br /> printf("The compacted array is as follows: \n");<br /> for(i=0;i<6;i++)<br /> printf("%d\n",arr[i]);<br /> return 0;<br />}<br /><br />Regards,<br />YogeshYogeshhttps://www.blogger.com/profile/03423823202640194270noreply@blogger.comtag:blogger.com,1999:blog-6294663875929591018.post-73698486580417897172011-03-11T17:12:57.669-08:002011-03-11T17:12:57.669-08:00Hi,
If more values at the starting are valid, co...Hi,<br /> If more values at the starting are valid, copying the same value to the same location isn't worth.<br /><br /> for(int i=0;i<arr.length;i++){<br /> if(arr[i]!=-1)<br /> arr[k++] = arr[i];<br /> } <br />This part can be improved by using<br /><br /> for(int i=0;i<arr.length;i++){<br /> if(arr[i]!=-1) {<br /> if ( i != k) <br /> arr[k] = arr[i];<br /> k++;<br /> }<br /> }<br /><br />Regards,<br />MathurUnknownhttps://www.blogger.com/profile/07528282014024246897noreply@blogger.com