Reputation: 33
I came across this question on Mettl :
The function takes four parameters -
pin(int) : a number that contains digits of any length
eg: 1234,34565789
number(int) : a number(1-9 both inclusive and less than the length of the pin) that determines the number of digits that has to be used for the generation of id, from the beginning and the end of the pin entered above.
Conditions for generating the id are:
if the lengths of both the first and last name are equal, then the name occurring alphabetically first is taken as the small name.
the number for the generation is obtained using the 'number' and 'pin' inputs.
Example 1:
first name: Rajiv
last name: Roy
pin: 123456
number: 3
Here 'Roy' is smaller in length than 'Rajiv'. So 'Roy' becomes the small name and 'Rajiv' becomes the large name. The 3rd digit from starting of the pin is '3' and the 3rd digit from the end of the pin is '4'. Therefore the number generated is 34.
The last letter of smaller name is 'y'. So the id generated is yRajiv34.
After toggling the letters, the final id generated is YrAJIV34.
function generateId(firstName, lastName, pin, n) {
var result = '';
var smallName = '';
var largeName = '';
if (firstName.length != lastName.length) {
if (firstName.length < lastName.length) {
smallName = firstName;
largeName = lastName;
} else {
largeName = firstName;
smallName = lastName;
}
} else {
var names = [firstName.toLowerCase(), lastName.toLowerCase()];
var sorted = names.sort(function (a, b) {
return a > b;
});
smallName = sorted[0];
largeName = sorted[1];
}
result += smallName.substr(smallName.length - 1, 1).toUpperCase();
result += largeName.substr(0, 1).toLowerCase() + largeName.substr(1, largeName.length).toUpperCase();
var pinString = pin.toString();
var numberLength = pinString.length;
result += pinString.charAt(n - 1) + pinString.charAt(numberLength - n);
return result;
}
var x = generateId('Kumar', 'Kumud', 530076, 2);
console.log(x);
var y = generateId('Rajiv', 'Roy', 345678, 3);
console.log(y);
its working well for all the test cases I pass and even got 7/10 test cases correct in the mettl site. I don't know what the reason is for the failure of the remaining 3 test cases. Is there a way to improve the algorithm or anything wrong with my code?
Upvotes: 1
Views: 4548
Reputation: 1623
You are not toggling the characters, you are just assuming that first character of the string will be uppercase and making it lower case and all other characters will be in lower case and making them uppercase. This won't work for cases such as:
generateId('RajIV', 'Roy', 345678, 6); // YrAJIV83
Also you are not handling the case where number
is greater than the length of pin
. It still gives an output.
generateId('RajIV', 'Roy', 345678, 7); // YrAJIV
Upvotes: 1