C / C++ Interview: Code Optimization - optimization

I had an interview today. This question was to optimize the code below. if we will see the code below after for loop there are four steps of "if-else" follows. So, interviewer asked me optimize it to 3 if-else line. I have tried a lot. But could not able to find the solution. Even he told me if you know scripting language then, you can use them also.
Please help me in optimizing the same.
int main()
{
int i = 1;
for(i; i <= 100; i++)
{
if((i % 3 == 0 && i % 5 == 0))
{cout << "PR\n";}
else if(i % 3 == 0)
{cout << "P\n";}
else if(i % 5 == 0)
{cout << "R\n";}
else
{cout << i <<"\n";}
}
system("pause");
return 0;
}

This is a well known question... the "FizzBuzz".
You can even solve it without any explicit IFs
const char *messages[] = {"%i\n", "P\n", "R\n", "PR\n"};
for (i=1; i<=100; i++) {
printf(messages[((i % 3)==0) + 2*((i % 5)==0))], i);
}

Here's one way, in Python:
for i in range(1, 101):
s = ''
if i % 3 == 0:
s += 'P'
if i % 5 == 0:
s += 'R'
if i % 3 != 0 and i % 5 != 0:
s = i
print(s)
Equivalently: using a flag, as shown in your own answer:
for i in range(1, 101):
s, flag = '', False
if i % 3 == 0:
flag = True
s += 'P'
if i % 5 == 0:
flag = True
s += 'R'
if not flag:
s = i
print(s)
Just for fun, a Python version of #6502's answer:
messages = ['{}', 'P', 'R', 'PR']
for i in range(1, 101):
print(messages[(i%3 == 0) + 2*(i%5 == 0)].format(i))
And finally, my personal favorite (because it's the shortest) - using the Greatest Common Divisor function and a lookup table:
from fractions import gcd
messages = {3:'P', 5:'R', 15:'PR'}
for i in range(1, 101):
print(messages.get(gcd(i, 15), i))

I found a solution.
Please let me know whether it is good or not?
int main()
{
int i = 1;int stat=0;
for(i; i <= 100; i++)
{
stat=0;
if(i%3 == 0){stat++; cout << "P";}
if(i%5 == 0){stat++; cout << "R";}
if(stat == 0)cout << i;
cout << "\n";
}
system("pause");
return 0;
}

I really like 6502's answer, but here is a simple solution without extra variables:
for(i = 1; i <= 100; i++)
{
if(i % 3 != 0 && i % 5 != 0)
{
printf("%d\n", i);
continue;
}
if(i % 3 == 0)
printf("P");
if(i % 5 == 0)
printf("R");
printf("\n");
}

this way only use 3 if
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i <= 100; ++i)
{
bool fizz = (i % 3) == 0;
bool buzz = (i % 5) == 0;
if (fizz)
cout << "Fizz";
if (buzz)
cout << "Buzz";
if (!fizz && !buzz)
cout << i;
cout << endl;
}
return 0;
}

Related

Using promela and Spin to solve algorithmic puzzle about frogs

I study verification at the university using promela. And as an example, i need to solve algorithmic puzzle about frogs. I tried to solve the problem but something doesn't work right
In how many moves will the frogs exchange places? Frogs jump in turn on an empty cage when it is nearby or through one frog of the opposite color.
enter image description here
bool all_frog_done;
active proctype frog_jump()
{
byte i = 0;
byte position[7];
position[0] = 1;
position[1] = 1;
position[2] = 1;
position[3] = 0;
position[4] = 2;
position[5] = 2;
position[6] = 2;
all_frog_done = false;
printf("MSC: position[0] %d position[1] %d position[2] %d position[3] %d position[4] %d position[5] %d position[6] %d \n", position[0], position[1], position[2], position[3], position[4], position[5], position[6]);
do
:: (position[0] == 2) && (position[1] == 2) && (position[2] == 2) && (position[3] == 0) && (position[4] == 1) && (position[5] == 1) && (position[6] == 1) ->
all_frog_done = true; break;
:: else ->
if
:: (position[i] == 1) && (position[i+1] == 0) && (i != 6) ->
position[i] = 0;
position[i+1] = 1;
:: (position[i] == 2) && (position[i-1] == 0) && (i != 0) ->
position[i] = 0;
position[i-1] = 2;
:: (position[i] == 1) && (position[i+1] == 2) && (position[i+2] == 0) && (i <= 4)->
position[i] = 0;
position[i+2] = 1;
:: (position[i] == 2) && (position[i-1] == 1) && (position[i-2] == 0) && (i >= 2)->
position[i] = 0;
position[i-2] = 2;
fi;
printf("MSC: position[0] %d position[1] %d position[2] %d position[3] %d position[4] %d position[5] %d position[6] %d \n", position[0], position[1], position[2], position[3], position[4], position[5], position[6]);
if
:: (i < 7) -> i++;
:: (i > 0) -> i--;
fi;
od;
}

I get garbage value on this jagged array

I get garbage value on this jagged array, that takes input size from another array's last value which must be -111(if not ten add one index to put in -111).
i know i have missed some cout statements but dont know why i get garbage vals
'''
int jaggedArr(int** arr2, int r, int c)
{
int* numbers = nullptr;
numbers = new int[r]; /// array to store no of columns
int** jagArr = new int* [r]; /// jagged array
for (int i = 0; i < r; i++)
{
int tempNum;
for (int j = 0; j < c; j++)
{ //store size of cols in arr4 to put int new array (arr3)
if (arr2[i][j] == -111)
{
tempNum = j;
numbers[i] = tempNum;//if -111 is present then dont change size just copy
}
else if (arr2[i][j] != -111)
{
tempNum = j + 1;
numbers[i] =tempNum;//else if -111 is not present then dont change size just copy
}
tempNum = 0;
}
}
for (int i = 0; i < r; i++)
{
jagArr[i] = new int[numbers[i]];
}
for (int i = 0; i < r; i++)
{
for (int j = 0; j < 10; j++)//remove 10
{
jagArr[i] = new int[numbers[i]];
}
}
cout << "Showing all the Inputed data in a matrix form" << endl;
for (int i = 0; i < r; i++) {
for (int j = 0; j < numbers[i]; j++)
{
//if (jagArr[i][j] >= 0 && jagArr[i][j] <= 9)
//{
// cout << jagArr[i][j] << " |";
//}
//else if (jagArr[i][j] == -111)
//{
// cout << jagArr[i][j] << "|";
//}
//else
//{
// cout << jagArr[i][j] << " |";
//}
cout << jagArr[i][j];
}
cout << "\n";
}
return **arr2;
}
'''

What does the code comment 'HD, Figure' mean in Java java.lang.Integer class?

for example, the JDK method java.lang.Integer.numberOfLeadingZeros(int):
public static int numberOfLeadingZeros(int i) {
// HD, Figure 5-6
if (i == 0)
return 32;
int n = 1;
if (i >>> 16 == 0) { n += 16; i <<= 16; }
if (i >>> 24 == 0) { n += 8; i <<= 8; }
if (i >>> 28 == 0) { n += 4; i <<= 4; }
if (i >>> 30 == 0) { n += 2; i <<= 2; }
n -= i >>> 31;
return n;
}
what does the code comment 'HD, Figure 5-6' mean?
HD = Hacker's Delight. See the the javadoc:
Implementation note: The implementations of the "bit twiddling" methods (such as highestOneBit and numberOfTrailingZeros) are based on material from Henry S. Warren, Jr.'s Hacker's Delight, (Addison Wesley, 2002).
There are also such comments in java.lang.Long and java.lang.Math.
For example, the addExactmethod in java.lang.Math:
public static int addExact(int x, int y) {
int r = x + y;
// HD 2-12 Overflow iff both arguments have the opposite sign of the result
if (((x ^ r) & (y ^ r)) < 0) {
throw new ArithmeticException("integer overflow");
}
return r;
}
For information of Hacker's Delight we can also refer to: http://hackersdelight.org/

what is the n queens complexity time by Back Tracking Method?

What is the n queens complexity time by Back Tracking Method?
and what is the count of Queens Position?
With below algorithm :
void queens (index i)
{
index j;
if (promising(i))
if (i == n)
cout << col[1] through col[n];
else
for (j = 1; j <= n; j++) {
col[i + 1] = j;
queens(i + 1);
}
}
bool promising (index i)
{
index k;
bool Switch;
k = 1;
Switch = true ;
while (k < i && switch) {
if (col[i] == col[k] || abs(col[i] – col[k] == i - k))
switch = false;
k++;
}
return Switch;
}
Any suggestion?

c++ print out arrays incrementally

I am trying to print out arrays incrementally like this;
TractMultBox->Text = rows[0] + newline;
TractMultBox->Text += rows[1] + rows[0] + newline;
TractMultBox->Text += rows[2] + rows[1] + rows[0] + newline;
which would give an output like this
3
43
543
I can do fine with this code, however. It would like to use a for loop, that would make it easier, since I would like it to output all arrays until max is reached automatically.
I'm assuming you want to concatenate and not sum.
string text;
for (int i = 0; i < rows.count; ++i)
{
text = rows[i] + text;
TractMultBox->Text = text + newline;
}
for less lines of code.
string text = newline;
for (int i = 0; i < rows.count; ++i)
{
TractMultBox->Text = (text = rows[i] + text);
}
but that's a little hard to read.
Sounds like a job for a for loop indeed perhaps something like this:
#include <iostream>
int main()
{
int rows[3] = {3, 4, 5};
for (int i(0); i < 3; ++i)
{
for (int j(i); j >= 0; --j)
std::cout << rows[j];
std::cout << "\n";
}
std::cin.get();
return 0;
}
If rows contained 345 this would give you the following output:
3
43
543
Not sure if that's what you wanted but you can adjust the loops accordingly. The key is to have 2 for loops.
Edit: Changed to self contained example you can play with
What about a double loop like:
for (int i = 0; i < maxNRows; ++i)
{
for (int j = 0; j < i; ++j)
{
TractMultBox->Text += rows[j];
}
TractMultBox->Text += newline;
}