patternjavaModerate
Printing a multiplication table
Viewed 0 times
printingtablemultiplication
Problem
I was recently given a coding test by an employer. After the test, this was the employer's response:
"I’d say that a lot of his solutions were pretty inefficient and took
a very ‘brute force’ approach to a solution. For example, his solution
for question 1 took 30 lines (give or take for some spacing). This is
normally done in about 8 lines. I did like that he documented all of
his answers very well, so that’s a positive, but yeah, just a lot of
inefficiency throughout his answers (processing inefficiency, object
allocation inefficiency, etc)"
I know this question cannot be answered well without an example so to give an example of question 1:
Write a method that takes a parameter x and then prints out an x by x multiplication table
This is what I wrote:
I am experienced, but I read and was told by previous employers that code that is easier to read is better, than complex code that takes only 3 lines. I could have written the code in less lines but I thought this was the way.
So my questions are:
"I’d say that a lot of his solutions were pretty inefficient and took
a very ‘brute force’ approach to a solution. For example, his solution
for question 1 took 30 lines (give or take for some spacing). This is
normally done in about 8 lines. I did like that he documented all of
his answers very well, so that’s a positive, but yeah, just a lot of
inefficiency throughout his answers (processing inefficiency, object
allocation inefficiency, etc)"
I know this question cannot be answered well without an example so to give an example of question 1:
Write a method that takes a parameter x and then prints out an x by x multiplication table
This is what I wrote:
public void printMultTable(int x)
{
int totalNumberOfPrints = x * x;
int rowCounter = 0;
int columnCounter = 1;
int number = 0;
for(int i = 0; i < totalNumberOfPrints; i++)
{
if(i < x)
{
number = i + 1;
System.out.print(number + " ");
}
else if (i % x == 0)
{
columnCounter = columnCounter + 1;
rowCounter = 2;
System.out.println();
System.out.print(columnCounter + " ");
}
else
{
number = columnCounter * rowCounter;
System.out.print(number + " ");
rowCounter = rowCounter + 1;
}
}
}I am experienced, but I read and was told by previous employers that code that is easier to read is better, than complex code that takes only 3 lines. I could have written the code in less lines but I thought this was the way.
So my questions are:
- What is processing inefficiency and how is that shown in my code?
- What is object allocation inefficiency(I didn't use any static variables)
- Is it better to use less lines (I thought it doesn't matter?)
Solution
Suggested interviewing technique
When writing code for an interview, always ask questions to seek clarification from your interviewer. There are nearly always technical decisions to be made, and you want to make choices that match what they have in mind. (If you don't have any questions, then you probably haven't thought things through properly.)
For this task, I would ask:
Before you even write a single line of code, you can score points by showing that you know how to negotiate software requirements.
Here's a solution that I would have written:
After writing it, explain and defend any technical decisions:
Note that other answers are possible. Your interviewer might have answered, "I don't care about any of those requirements. I just want to know that you know how to write a nested loop." In that case, just write the simplest code that prints out the right numbers with sloppy formatting.
Your solution and feedback
My biggest concern is that it is not obvious from inspection what your code does. There are a lot of variables, and the flow of control is convoluted.
The natural way to write this solution is using a nested for-loop. If you really wanted to do it in one loop, it should be simpler:
Note that the function should be static
When writing code for an interview, always ask questions to seek clarification from your interviewer. There are nearly always technical decisions to be made, and you want to make choices that match what they have in mind. (If you don't have any questions, then you probably haven't thought things through properly.)
For this task, I would ask:
- "Can I assume that the the input
xis a reasonably small positive integer, not requiring validation? It doesn't make much sense to print anything larger than 100 × 100 anyway, right?"
- "I assume that you want the entries to be aligned nicely in a grid?"
- "I assume that we don't need row and column headings, and that we don't need to print grid lines?"
- "I assume that you want a reasonable balance of simplicity and speed?"
Before you even write a single line of code, you can score points by showing that you know how to negotiate software requirements.
Here's a solution that I would have written:
public static void printMultTable(int x) {
int width = (int)Math.floor(Math.log10(x * x)) + 2;
String fmt = "%" + width + "d";
StringBuilder b = new StringBuilder(x * width);
for (int row = 1; row <= x; row++) {
b.setLength(0);
for (int col = 1; col <= x; col++) {
b.append(String.format(fmt, row * col));
}
System.out.println(b);
}
}After writing it, explain and defend any technical decisions:
- "To achieve grid alignment, we need to first determine the width of each entry.
String.valueOf(x * x).length() + 1would have worked, but I think that the mathematical approach is slightly more efficient."
- "I could call
System.out.print()for every entry, but printing an entire row at once should have less overhead. Printing the entire table at once might be even faster, but I figured this was good enough."
Note that other answers are possible. Your interviewer might have answered, "I don't care about any of those requirements. I just want to know that you know how to write a nested loop." In that case, just write the simplest code that prints out the right numbers with sloppy formatting.
Your solution and feedback
My biggest concern is that it is not obvious from inspection what your code does. There are a lot of variables, and the flow of control is convoluted.
- I think
numberis superfluous. After each assignment, you use it just once.
- Why is
rowCounterinitialized to 0, butcolumnCounterinitialized to 1? Why is there arowCounter = 2assignment right in the middle of everything? (I would expect reinitializing to either 0 or 1.) More alarmingly, you incrementrowCounterto count the columns printed, andcolumnCounterto number the current row. That's the kind of trap that makes co-workers hate your code.
- Three cases is excessive. All of them have
System.out.print(… + " "), which makes it cut-and-paste code. Couldn't you lump the firstif(i
The natural way to write this solution is using a nested for-loop. If you really wanted to do it in one loop, it should be simpler:
public static void printMultTable(int x)
{
int row = 1, col = 1;
int totalEntries = x * x;
for (int i = 1; i <= totalEntries; i++)
{
System.out.print((row * col++) + " ");
if (i % x == 0)
{
System.out.println();
row++;
col = 1;
}
}
}Note that the function should be static
, since there's no reason for it to have any object state.
I’d say that a lot of his solutions were pretty inefficient and took a very ‘brute force’ approach to a solution. For example, his solution for question 1 took 30 lines (give or take for some spacing). This is normally done in about 8 lines. I did like that he documented all of his answers very well, so that’s a positive, …
Comparing your solution against the others posted here, I think you would agree that the logic was unnecessarily convoluted.
but yeah, just a lot of inefficiency throughout his answers (processing inefficiency, object allocation inefficiency, etc)
For all practical purposes, there isn't going to be much user-visible difference in performance of your printMultTable()` and the better implementations. I don't think that there's much object allocation to speak of in this particular solution; that feedback probably referred to the solutions you wrote for the other tasks. But judging from the way you used a zoo of variables without any clear purpose, I'm inclined to believe their assessment.Code Snippets
public static void printMultTable(int x) {
int width = (int)Math.floor(Math.log10(x * x)) + 2;
String fmt = "%" + width + "d";
StringBuilder b = new StringBuilder(x * width);
for (int row = 1; row <= x; row++) {
b.setLength(0);
for (int col = 1; col <= x; col++) {
b.append(String.format(fmt, row * col));
}
System.out.println(b);
}
}public static void printMultTable(int x)
{
int row = 1, col = 1;
int totalEntries = x * x;
for (int i = 1; i <= totalEntries; i++)
{
System.out.print((row * col++) + " ");
if (i % x == 0)
{
System.out.println();
row++;
col = 1;
}
}
}Context
StackExchange Code Review Q#86443, answer score: 10
Revisions (0)
No revisions yet.