Psycho
BAN USERSimple guy. Loves Programming.
- 0of 0 votes
AnswersState the difference between this two statement.
- Psycho in India
char str[] = "/root//foo/bar" ;
char *str = "/root//foo/bar" ;
Now, you have given an assignment str[in1] = str[in2]
where in1 and in2 both initialize with 0.
In first type of declaration no problem. But in second type of declaration 'Segmentation fault' is there. Why this happens?| Report Duplicate | Flag | PURGE
Adobe Software Engineer / Developer C - 0of 0 votes
AnswersJust Example : "Given 8 cue balls , one is weighing lesser than other 7. Find that(light weight) ball using just 2 chances on balance weight."
- Psycho in India
How to find a general solution to these kind of question? How to divide this set of balls? Is there any finer method or general formula?| Report Duplicate | Flag | PURGE
Software Engineer / Developer Brain Teasers - 0of 0 votes
AnswersAn unsorted array is given, where there is no specific range in which the elements occur. There is only one duplicate element present in it. Let it is a[i]. It should be within the half of the size of the array from where it appears for first time. i.e. the duplicate element should be within (i+(arr_size/2)), at ith index it appears for 1st time. Find the duplicate element with minimum number comparisons.
- Psycho in United States| Report Duplicate | Flag | PURGE
Microsoft
- 0 Answers C++ Topic : Related to 'Multiset' functionality
Consider this sample piece of code!
multiset<int> iends; multiset<int>::iterator et1; while(et1!=iends.end()){ multiset<int>::iterator te=et1; et1++; iends.erase(te); } while(et1!=iends.end()){ multiset<int>::iterator te=et1; iends.erase(te); et1++; }
What is the difference between this two pieces of code?
- Psycho December 09, 2012| Flag | PURGE
Checking and decreasing count k inplace. If k == 0 output the character. If invalid position return a space or blank.!!
#include <stdio.h>
#include <ctype.h>
#define SIZE 100
/* Index starts from 0 - kth position */
char getChar (char *str, int k) {
int i, index = 0, count = 0 ;
if ( k < 0 || strlen(str)==0)
return ' ' ;
char ch = str[0];
while ( str[index] != '\0' ) {
if ( isalpha(str[index]) ) {
if ( k <= 0 )
return ch ;
k -= count ;
ch = str[index] ;
count = 0 ;
}
else {
count = count * 10 + (str[index]-'0') ;
if ( k < count )
return ch ;
}
index ++ ;
}
if ( k == 0 || k < count )
return ch ;
return ' ' ;
}
int main () {
char str[SIZE] ;
int k ;
scanf ( "%s", str ) ;
scanf ( "%d", &k ) ;
printf ( "\nChar at position : %c", getChar(str,k) ) ;
return 0 ;
}
just codes what algos said. Some modi as mentioned above.
#include <cstdio>
#include <algorithm>
#include <vector>
#include <climits>
using namespace std ;
typedef struct element {
int index ;
int val ;
bool operator < (const element& ele) const {
return (val < ele.val);
}
}element ;
void findSubArraySumCloseToZero (vector<element> vec) {
sort (vec.begin(), vec.end()) ;
vector<element>::iterator it = vec.begin() ;
element prev = *it , cur, start = *it, end = *it;
int max = INT_MAX, sindex, eindex ;
for ( it ++ ; it < vec.end(); it ++ ) {
cur = *it ;
if ( (cur.val - prev.val) <= max ) {
max = cur.val - prev.val ;
start = prev ;
end = cur ;
}
prev = cur ;
}
sindex = (start.index > end.index) ? (end.index) : (start.index) ;
eindex = (start.index <= end.index) ? (end.index) : (start.index) ;
sindex ++ ;
printf ( "\nStart index = %d, end index = %d", sindex, eindex ) ;
}
int main () {
vector<element> vec ;
int num, size ;
scanf ( "%d", &size ) ;
element ele ;
ele.index = -1 ;
ele.val = 0 ;
vec.push_back (ele) ;
for ( int i = 0 ; i < size ; i ++ ) {
scanf ( "%d", &num ) ;
element ele, prev = vec.back();
ele.index = i ;
ele.val = num + prev.val ;
vec.push_back (ele) ;
}
findSubArraySumCloseToZero (vec) ;
}
@algos take this corner case : all are negative you always increase the start index. How do you handle this.
-5 -3 -1 -8 -9 -3
so after sorting your elements will be like this
(5,-29)
(4,-26)
(3,-17)
(2,-9)
(1,-8)
(0,-5)
(-1,0)
so your start index will be 2 and end index will be 1.
So final answer becomes 2+1 = 3 to 1 which is odd.
So first you have to check which end is minimum and update the min index by +1.
#include<stdio.h>
// Returns true if C is an interleaving of A and B, otherwise
// returns false
bool isInterleaved (char *A, char *B, char *C) {
bool ans = false ;
// Iterate through all characters of C.
while (*C != 0) {
// Search For Both
if ( (*A == *B) && (*A == *C) ) {
//printf ( "\nMatches %c Remaining a =%s, b=%s\n", *A,A,B) ;
ans = isInterleaved (A+1, B, C+1) ;
ans = ans || isInterleaved (A, B+1, C+1) ;
return ans ;
}
// Match first character of C with first character of A,
// If matches them move A to next
if (*A == *C)
A++;
// Else Match first character of C with first character of B,
// If matches them move B to next
else if (*B == *C)
B++;
// If doesn't match with either A or B, then return false
else
return false;
// Move C to next for next iteration
C++;
}
// If A or B still have some characters, then length of C is smaller
// than sum of lengths of A and B, so return false
if (*A || *B)
return false;
return true;
}
// Driver program to test above functions
int main() {
char A[] = "ABBC";
char B[] = "ABD";
char C[] = "AABBDBC";
if (isInterleaved(A, B, C) == true)
printf("%s is interleaved of %s and %s", C, A, B);
else
printf("%s is not interleaved of %s and %s", C, A, B);
return 0;
}
It is 81+81+88
divide into 3 groups such that at least two groups contain elements to certain power of 3 which is nearest to the total number of elements.
If it is not possible to divide in such order then atleast one group should contain elements to certain power of 3.
Interesting conversation really.
Suppose we have 624 balls. I am comparing two methods given by @mAn1Ac and @eugene.yarovoi
First consider @mAn1Ac 's comment.
According to him - "divide into 3 groups such that at least two groups contain elements to certain power of 3 which is nearest to the total number of elements" (some modification by me)
So 624 is divided into 243-243-138
If odd ball(considering only one ball is lighter than other) present in 138 group. Again 138->(27+27+74), Considering 27 group contains lighter ball 27->(9+9+9).. And so on.
So in this sequence 624->138->27->9->3 overall 5 comparisons. So my point is there is slight chance that we can minimize the total number of comparisons by doing this. Otherwise this can always be done in ceil(log_3_(n)) comparisons.
But if we use @eugene.yarovoi 's proposal we will surely lead with ceil(log_3_(n)) comparisons. Because all the balls are evenly distributed in all three groups.
So 624(208+208+208)->208(69+69+70)->69(23+23+23)->23(7+8+8)->7(3+3+2)->3(1+1+1) Overall 6 comparisons.
Its the factorization problem.
All numbers except the squares have even number of factors, so if all those doors which are at position number i, where i is not a square should remain closed at the last pass.
So, all those doors which are on open state are 1,4,9,16,25,36,49,64,81,100
All others are remain closed.
#include <stdio.h>
#include <stdlib.h>
int* createIncreasingOrder (int limit) {
int *result, i, index2 = 0, index5 = 0 ;
result = (int *) malloc (sizeof(int) * limit) ;
result[0] = 1 ;
for ( i = 1 ; i < limit ; i ++ ) {
/* Check which one is better multiplied by 2 or 5 specified by their indices */
if ( (result[index2]<<1) > (result[index5]*5) )
result[i] = result[index5++] * 5 ;
else if ( (result[index2]<<1) < (result[index5]*5) )
result[i] = result[index2++] << 1 ;
else {
result[i] = result[index2] << 1 ;
index2 ++ ;
index5 ++ ;
}
}
return result ;
}
void printList (int *list, int size) {
int i ;
printf ( "\n" ) ;
for ( i = 0 ; i < size ; i ++ )
printf ( "%d ", list[i] ) ;
}
int main () {
int limit = 20 ;
printList (createIncreasingOrder(limit),limit) ;
return 0;
}
"how do you find the shortest distance (find a formula) for two points on the opposite vertices of a cube (shortest distance is actually sqrt(3) but can't cut through interior, must go along surface of cube)"
Shortest dist sqrt(3) means here the points should be end points of the diagonal. If we cant go through a diagonal (of a cube which is not present in any surface), then we must go through one diagonal of a surface (side*sqrt(2)) and one side.
So answer is (1+sqrt(2))*side
You dont have to sort it. For sorting part you just reverse it. It will remove the cost of sorting.
kill's option :
3521
ptr = 1
ptr = 2
ptr = 5
ptr = 3 < 5
swap(ptr, min_digit > 3 ) = swap (ptr, 5)
Number = 5321
Sort the rest => 5123
5123 is the number
here you dont need to sort! Just reverse it.
@Anonymous on August 29, 2012 Code is working perfectly.
Since i m using char arr[] and sizeof operator it will return strlen(arr) + 1. So edge cases are covered.
But if i use char *arr for initialization and then use strlen then i have to cover the edge case. You can also try.
Same as @carol says
#include <cstdio>
#include <algorithm>
using namespace std ;
void swap (int *a, int *b) {
int temp = *a ;
*a = *b ;
*b = temp ;
}
int main () {
int arr[] = {9,0,3,2,4,1,3,4,0,4,4,0} ;
int max, s_max, mCount = 1, smCount = 0, temp, count = 0;
int size = sizeof(arr)/sizeof(arr[0]) ;
sort (arr,arr+size) ;
for ( int i = 1, max = arr[0], temp = arr[0] ; i < size ; i ++ ) {
if ( temp == arr[i] )
count ++ ;
else {
/* New element with max occurance found out */
if ( count > mCount ) {
/*assign it to second max */
swap (&max, &s_max);
swap (&mCount, &smCount) ;
mCount = count ;
max = temp ;
count = 0 ;
} else if ( count > smCount ) {
/* Second max found */
smCount = count ;
s_max = temp ;
count = 0 ;
}
}
temp = arr[i] ;
}
if ( smCount != 0 )
printf ( "\nSecond ocurring number = %d", s_max ) ;
return 0;
}
Here fp will reach earlier than sp to NULL when it is acyclic. So in that case if (fp->next) may give the exception. because fp points to NULL and tries to access the next.
//till they meet if there is a cycle or if it terminates with NULL
do {
if (sp->next) {
sp = sp->next;
count++;
}
if (fp->next) {
if (fp->next->next)
fp = fp->next->next;
else
fp = fp->next; //ensures sp and fp meets if NULL encountered at end
}
} while (sp != fp);
Thumbs up for @Anonymous on July 17, 2012
Great one! I am just following your steps.
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node *left;
struct node *right;
}node ;
node* newNode (int data) {
node *temp = (node *) malloc (sizeof(node));
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
/* Calculates height as well as total
number of nodes present in the tree */
int height (node *root, int *count) {
int left, right ;
if (!root)
return 0 ;
*count = *count + 1 ;
/* Leaf node */
if ( root->left == NULL && root->right == NULL )
return 1 ;
left = height (root->left,count) ;
right = height (root->right,count) ;
return 1+((left>right) ? left : right ) ;
}
/* Post order traversal and puts the element in the array,
also puts the height of the tree nodes in another array */
int givePostOrderUtil (int* arr, node* root, int len, int* tLevel, int level) {
if (root) {
len = givePostOrderUtil (arr, root->left, len, tLevel, level+1) ;
len = givePostOrderUtil (arr, root->right, len, tLevel, level+1) ;
arr[len] = root->data ;
tLevel[len] = level ;
/* Special marks which indicates this as a leaf node */
if ( root->left == NULL && root->right == NULL )
tLevel[len] = -level ;
len ++ ;
}
return len ;
}
/* Post order traversal driver function */
int* givePostOrder (node *root, int size, int** tLevel) {
int *arr = (int *) malloc (sizeof(int)*size) ;
int *tlevel = (int *) malloc (sizeof(int)*size) ;
givePostOrderUtil (arr, root, 0, tlevel, 0) ;
*tLevel = tlevel ;
return arr ;
}
int giveSumParticularOrder (int* arr, int *tLevel, int tHeight, int count, int level) {
int *bitArr, i, sum = 0 ;
/* Array denotes for leaf nodes */
bitArr = (int *) malloc (sizeof(int) * tHeight) ;
for ( i = 0 ; i < tHeight ; i ++ )
bitArr[i] = 0 ;
for ( i = 0 ; i < count ; i ++ ) {
/* marks as leaf node */
if ( tLevel[i] < 0 ) {
bitArr[-tLevel[i]] = 1 ;
}
else {
/* check the marker boundary and if the bit set then it will be
a child at that extra depth. Collect the value and adds */
if ( (tLevel[i]+level) < tHeight && bitArr[tLevel[i]+level] ) {
sum += arr[i] ;
}
}
}
return sum ;
}
int main () {
int cNode = 0, i, *arr, *tLevel, tHeight ;
node *root = newNode(1) ;
root->left = newNode(2) ;
root->right = newNode(3) ;
root->left->left = newNode(4) ;
root->left->right = newNode(5) ;
root->right->left = newNode(6) ;
root->right->right = newNode(7) ;
root->left->right->left = newNode(8) ;
root->left->right->right = newNode(9) ;
root->right->right->right = newNode(10) ;
tHeight = height(root,&cNode) ;
arr = givePostOrder (root, cNode, &tLevel) ;
for ( i = 0 ; i < cNode ; i ++ )
printf ( "\n%d (%d)", arr[i], tLevel[i]) ;
printf ( "\nMaximum sum is : %d", giveSumParticularOrder (arr, tLevel, tHeight, cNode, 2) ) ;
return 0 ;
}
z=++x||++y&&++z
Short circuiting is fine.
I wanna ask that precedence of ++ is greater than =
so ++x will execute first then it will assigned to z
so z will be 2
Or this is the condition
z=++x||++y&&++z
here left of the || is taken as one component, as x is > 0 it skips the assignment left z as 1. after that z is incremented to 2.
- Psycho August 30, 2012
RepOliviaJBlack, Consultant at Apkudo
I am Olivia from San Diego. I am working as a checker in the Thom McAn Store company. My strong ...
RepShirleyCWest, Software Engineer at Agilent Technologies
Hello, me Shirley and I from Savage. I am an artist and I love to doing art and I am ...
- Psycho September 19, 2012