"How to impress interviewers with my coding? What practices can I adopt in the code I've written for the question stated to impress interviewers?

时光总嘲笑我的痴心妄想 提交于 2020-01-03 15:38:07

问题


Say there is a vector of int. Now we want to merge such that , we select 2 adjacent element v[I] and v[I+1] ( for each valid I ) and do v[I] = v[I+1] + v[I] . And erase v[I+1]. Keep on doing this until you're just left with one element in the vector.(Note I=0 & I=v.size()-1 are also considered as adjacent ). so we need to try all such possible combination(i.e which pair we took first and merged matters if further clarification required please let me know in the comment)

where every time we merge we do cost+= v[I] + v[I+1].Goal is to minimise cost.Take an example say vector is 1 2 3. merging [1 2 3]-> [3,3] & cost=3 -> [6] & cost=9 another way [1 2 3]-> [1,5] & cost=5 -> [6] & cost=11 . So is their any algorithm to generate all permutation with given constrain ?

#include<bits/stdc++.h>
using namespace std;
int mn =INT_MAX;
void r(vector<int > v, int sum)
{
    if(v.size()==1){if( mn >sum) mn=sum; return ;}

    for(int i=0;i<v.size();i++)
    {
        sum+=v[i]+v[(i+1)%v.size()];
        v[i]=v[i]+v[(i+1)%v.size()];
        v.erase(v.begin()+(i+1)%v.size());
        r(v,sum);
    }
}
int main()
{
   vector<int> v;//suppose we gave some input to our vector 

   r(v,0);
   cout<<mn;
return 0;

}
#if you have a better solution, do state it, thankyou!

回答1:


Your goal is to impress interviewers.
They are looking for people who can work in teams and can make reusable code, which can be handed over to colleagues when needing to be switched to a different topic to work on.

For that, learn to

  • get into the habit of explaing your code, i.e. write useful comments
    • write comments according to "if code and comment do not match, both are probably in error"
    • write comments according to "my comments help me to understand my own code after I return from a three month vacation on an island without computers"
  • stop using global variables, at least instead of return values
  • use self-explaining identifiers for variables and functions
  • have a look through StackOverflow questions for questionable habits to abolish (e.g. Why should I not #include <bits/stdc++.h>? )
  • learn when to optimise, it usually does not pay to optimise when not needed
  • learn to optimise for a certain purpose


来源:https://stackoverflow.com/questions/57016753/how-to-impress-interviewers-with-my-coding-what-practices-can-i-adopt-in-the-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!