How do I print a pattern with number of rows is equal to number of stars such that if 1 star then 1 row of 1 star, 2 star then 2 rows of 2 stars and so on, provided with good logic?
Here's the output for the logic mentioned above
*
**
**
***
***
***
using mod operator you can get proper output.Java has one important arithmetical operator you may not be familiar with, %, also known as the modulus or remainder operator. The % operator returns the remainder of two numbers. For instance 10 % 3 is 1 because 10 divided by 3 leaves a remainder of 1. You can use % just as you might use any other more common operator like + or -.
I write code in java.
Execution Steps:-
for loop for declare i value to 1.loop start with value 1 and last value 5.
for loop for declare i value to 1.in this we gave condition for j is i*i.
if j value is 1 then it print star.
if j value is not 1 then it goes to else part.
in this there are again if and else part in if part we use mod operator and if its value gives 0 value then print star otherwise goto else condition.
for(int i = 1; i <= 5; i++) {
for(int j = 1; j <= i * i; j++) {
if(j == 1) {
System.out.println();
System.out.print("*");
} else if(j % i == 0) {
System.out.print("*");
System.out.println();
} else {
System.out.print("*");
}
}
}
Related
I am writing code in Hackerrank. And recently the problem said, convert decimal to base 2 and then count the max consecutive 1's in the binary number. And first I come with following solution. It works fine. But I do not understand the counting part of it, even though I wrote it.
The code is
int main(){
int n,ind=0, count=0, mmax=0;
char bin[100];
cin >> n;
while(n){
if(n%2==0) {
bin[ind]='0';
n = n / 2;
ind = ind + 1;
}
else if(n%2==1) {
bin[ind]='1';
n = n / 2;
ind = ind + 1;
}
}
for(int i=0; i<=(ind-1); i++){
if(bin[i] == '1' && bin[i+1] == '1'){
count++;
if(mmax < count)
mmax = count;
}
else
count=0;
}
cout << mmax + 1 << endl;
return 0;
}
In the above code, I guess that variable mmax will give me the max consecutive number of 1's but it gives me value that has (max consecutive - 1), So I just wrote like that and submitted the code. But I am curious about. why it is working that way. I am little bit of confused the way that code works like this.
Thanks
Lets say you have this binary sequence:
11110
Your code will compare starting from the first and second:
|11|110 1 && 1 -> max = 1
1|11|10 1 && 1 -> max = 2
11|11|0 1 && 1 -> max = 3
111|10| 1 && 0 -> max = 3
you can see, that although there are 4 1's you only do 3 comparisons, so your max will always be -1 of the actual max. You can fix this by adding mmax += 1 after your for loop.
Just a little bit of trace using small example will show why.
First, lets say there is only 1 '1' in your array.
Since you require both the current position and your next position to be '1', you will always get 0 for this case.
Let's say I have "11111". At the first '1', since next position is also '1', you increment count once. This repeats until 4th '1' and you increment your count 4 times in total so far. When you reach 5th '1', your next position is not '1', thus your count stops at 4.
In general, your method is like counting gaps between fingers, given 5 fingers, you get 4 gaps.
Side note: your code will fail for the case when there is no '1' in your array.
The project I am working on needs to find some way of verifying that a variable after the modulus operation is either number != 0, number > 0, or number < (0 < x < 1). I have the first two understood, however employing the mod operator to accomplish the third is difficult.
Essentially what I am looking to do is to be able to catch a value similar to something like this:
a) 2 % 6
b) flag it and store the fact that .333 is less than 1 in a variable (bool)
c) perform a follow up action on the basis that the variable returned a value less than 1.
I have a feeling that the mod operator cannot perform this by itself. I'm looking for a way to utilize its ability to find remainders in order to produce a result.
edit: Here is some context. Obveously the below code will not give me what I want.
if (((inGameTotalCoins-1) % (maxPerTurn+1)) < 0){
computerTakenCoins = (inGameTotalCoins - 1);
inGameTotalCoins = 1;
The quotient is 0(2/6) with the fractional part discarded.The fractional part is .3333 ... So you are basically talking about the fractional part of the quotient , not the modulus value. Modulus can be calculated as follows :
(a / b) * b + (a % b) = a
(2 / 6) * 6 + (2 % 6) = 2
0 * 6 + (2 % 7) = 2
(2 % 6) = 2
*6 goes into 2 zero times with 2 left over.
How about this:-
int number1 = 2;
int number2 = 6;
float number3 = static_cast<float>(number1) / static_cast<float>(number2);
bool isfraction = number3 > 0 && number3 < 1;
if(isfraction){
std :: cout << "true\n" << number3;
}
else{
std :: cout << "false" << number3;
}
number != 0 includes number > 0 and number < (0 x < 1). And number > 0 includes number < (0 x < 1). Generally we do not classify so. For example, people classify number > 0, number == 0 and number < 0.
If you do the modulous operation, you get remainder. Remainder's definition is not one thing. You can see it at https://en.m.wikipedia.org/wiki/Remainder
I have this very weird issue going on. The function you will see in a moment is supposed to ensure that all elements (chars) in a 2D array are at there utmost position, that is, there is no empty space above any of the characters. For instance a board could look like this:
1 X * * X ^
2 * X ^ *
3 o o * X ^
4 o ^ X X X
5 ^ * X * ^
1 2 3 4 5
And there is an issue at (2,1) because there is an empty space above a non empty space.
My function does the sorting correctly but it deletes any character in the bottom row that has an empty space above it. I cannot, for the life of me, figure out why. Here is my sort function.
int bb_float_one_step(BBoard board){
int i,j;
for (i = 0; i < board->rows; i++){
for (j = 0; j < board->cols; j++){
if (board->boardDim[i][j] == None && (board->boardDim[i + 1][j] != None && i + 1 <= board->rows)){
char tmp = board->boardDim[i + 1][j];
board->boardDim[i + 1][j] = board->boardDim[i][j];
board->boardDim[i][j] = tmp;
}
}
}
for (i = 0; i < board->rows; i++){
for (j = 0; j < board->cols; j++){
printf("%c",board->boardDim[i][j]);}printf("\n");}
}
Below Is a picture of the full sequence, The Program prints a board. The user is asked to select a region to 'pop.' A function then replaces all the characters that are connected with a blank space. Then in the last portion of the picture you can see how the characters are deleted. The board that doesn't have a border is there because I was using it to check if the characters actually were deleted or not.
Thank you in advanced for 1, reading this whole post, and 2, any help you can give.
Since you are comparing current row with next row you should use for(i = 0; i < board->rows-1; i++)
Then in your complex if statement, get rid of && i <= board->rows. That should have been a less-than anyway, not less-than-or-equals. You're going out of bounds and getting garbage in your array.
You are checking the row beyond the maximum number of rows.
(board->boardDim[i + 1][j] != None && i + 1 <= board->rows)
That memory is not guaranteed to be 0. If it is not 0, your function will swap it in. If it is not human readable, printf won't print anything for it thereby shifting the | to the left.
I am trying to implement Long Hand Multiplication method for 8 bit binary numbers stored in two arrays BeforeDecimal1 and BeforeDecimal2. The problem is I always get the wrong result. I tried to figure out the issue but couldn't do it. Here is the code:
This is a much more refined code then previous one. It is giving me result but the result is not correct.
int i=0,carry=0;
while(true)
{
if(BeforeDecimal2[i]!=0)
for(int j=7;j>=0;j--)
{
if(s[j]==1 && BeforeDecimal1[j]==1 && carry==0)
{
cout<<"Inside first, j= "<<j<<endl;
carry=1;
s[j]=0;
}
else
if(s[j]==1 && BeforeDecimal1[j]==0 && carry==1)
{
cout<<"Inside second, j= "<<j<<endl;
carry=1;
s[j]=0;
}
else
if(s[j]==0 && BeforeDecimal1[j]==0 && carry==1)
{
cout<<"Inside third, j= "<<j<<endl;
carry=0;
s[j]=1;
}
else
if(s[j]==0 && BeforeDecimal1[j]==0 && carry==0)
{
cout<<"Inside fourth, j= "<<j<<endl;
carry=0;
s[j]=0;
}
else
if(s[j]==0 && BeforeDecimal1[j]==1 && carry==0)
{
cout<<"Inside fifth, j= "<<j<<endl;
carry=0;
s[j]=1;
}
else
if(s[j]==1 && BeforeDecimal1[j]==1 && carry==1)
{
//cout<<"Inside fifth, j= "<<j<<endl;
carry=1;
s[j]=1;
}
else
if(s[j]==1 && BeforeDecimal1[j]==0 && carry==0)
{
//cout<<"Inside fifth, j= "<<j<<endl;
carry=0;
s[j]=1;
}
else
if(s[j]==0 && BeforeDecimal1[j]==1 && carry==1)
{
//cout<<"Inside fifth, j= "<<j<<endl;
carry=1;
s[j]=0;
}
}
for(int h=7;h>=0;h--)
{
if(h==0)
{
BeforeDecimal1[0]=0; // that is inserting zeros from the right
}
else
{
BeforeDecimal1[h]=BeforeDecimal1[h-1];
BeforeDecimal1[h-1]=0;
}
}
if(i==3)
break;
i++;
}
Regards
Maybe it would be easiest to back up and start with 8-bit binary numbers stored as 8-bit binary numbers. Much like when we do decimal multiplication, we start with a number of digits. We take the values of multiplying by those individual digits, and add them together to get the final result. The difference (or one obvious difference) is this since we're working in binary, all our digits represent powers of two, so we can get each intermediate result by simply bit shifting the input.
Since it's binary, we have only two possibilities for each digit: if it's a 0, then we need to add 0 times the other number shifted left the appropriate number of places. Obviously, 0 time whatever is still 0, so we simply do nothing in this case. The other possibility is that we have a 1, in which case we add 1 times the other number shifted left the appropriate number of places.
For example, let's consider something like 17 x 5, or (in binary) 10001 x 101.
10001
101
------
10001
+ 1000100
--------
= 1010101
Converting that to something more recognizable, we get 0x55, or 85d.
In code, that process comes out fairly short and simple. Start with a result of 0. Check whether the least significant bit in one operand is set. If so, add the other operand to the result. Shift the one operand right a bit and the other left a bit, and repeat until the operand you're shifting to the right equals 0:
unsigned short mul(unsigned char input1, unsigned char input2) {
unsigned short result = 0;
while (input2 != 0) {
if (input2 & 1)
result += input1;
input1 <<= 1;
input2 >>= 1;
}
return result;
}
If you want to deal with signed numbers, it's generally easiest to figure up the sign of the result separately, and do the multiplication on the absolute values.
You have problem in following lines of code
if(reverse==0)
{
totalReverse=totalReverse-1;
reverse=totalReverse;
}
after some iterations of the inner for loop (index j based) the values of reverse goes should goes to negative and when reverse less than 3 then there should be exception thrown.
Are you running this code without exception handling?
to me this smells like shift and add. is there a requirement that you may use operations simulating logical gates only?
for your full adder you have 3 inputs s(s[j]), b(BeforeDecimal1[j]), c(carry), and two outputs ns(new s[j]), nc (new carry)
the table looks like this
s b c ns nc
0 0 0 0 0 handled in v5 clause 4
0 0 1 1 0 handled in v5 clause 3
0 1 0 1 0 handled in v6 clause 5
0 1 1 0 1
1 0 0 1 0
1 0 1 0 1 handled in v5 clause 2
1 1 0 0 1 handled in v5 clause 1
1 1 1 1 1
your code covers only 4 (now 5) of these 8 clauses
to avoid the ugly if-else-if rake i recommend to use temporary result variables (carry and s still valid in the next if clause)
when you analyze the table you could also do (pseudo bool notation)
nc = s && b || s && c || b && c;
ns = s XOR b XOR c; // there is no XOR in C++: axb = a&&!b || !a&&b
arithmetic notation
nc = (s + b + c) / 2;
ns = (s + b + c) % 2;
// [...]
for(int j=7;j>=0;j--)
{
// start changed code
const int sum = s[j] + BeforeDecimal1[j] + carry;
s[j]=sum % 2;
carry=sum / 2;
// end changed code
}
// [...]
here is a nice simulation of your problem Sequential Multiplication
Unless your requirement precisely states otherwise, which isn't clear from your question or any of your comments so far, it is not necessary to process arrays of bits. Arrays of bytes are much more efficient in both space and time.
You don't need this exhaustive explosion of cases either. The only special case is where either operand is zero, i.e. a[i]|b[i] == 0, when
result[i] = carry;
carry = 0;
All other cases can be handled by:
result[i] = a[i]*b[i]+carry;
carry = (result[i] >>> 8) & 1;
result[i] &= 0xff;
I don't see much point in the names BeforeDecimal1 and BeforeDecimal2 either.
I am basically trying to solve the coin change problem through recursion and here is what i have so far -:
#include<iostream>
#include<conio.h>
using namespace std;
int a[]={1,2,5,10,20,50,100,200},count=0;
//i is the array index we are working at
//a[] contains the list of the denominations
//count keeps track of the number of possibilities
void s(int i,int sum) //the function that i wrote
{
if (!( i>7 || sum<0 || (i==7 && sum!=0) )){
if (sum==0) ++count;
s(i+1,sum);
s(i,sum-a[i]);
}
}
int c(int sum,int i ){ //the function that I took from the algorithmist
if (sum == 0)
return 1;
if (sum < 0)
return 0;
if (i <= 0 && sum > 0 )
return 1;
return (c( sum - a[i], i ) + c( sum, i - 1 ));
}
int main()
{
int a;
cin>>a;
s(0,a);
cout<<c(a,7)<<endl<<count;
getch();
return 0;
}
The first function that is s(i,sum) has been written by me and the second function that is c(sum,i) has been taken from here - (www.algorithmist.com/index.php/Coin_Change).
The problem is that count always return a way higher value than expected. However, the algorithmist solution gives a correct answer but I cannot understand this base case
if (i <= 0 && sum > 0 ) return 1;
If the index (i) is lesser than or equal to zero and sum is still not zero shouldn't the function return zero instead of one?
Also I know that the algorithmist solution is correct because on Project Euler, this gave me the correct answer.
I guess that your problem is "Assuming that I have unlimited support of coins, on how many ways can I change the given sum"?
The algoritimists solution you gave assumes also, that the smallest denomination is 1. Otherwise it will won't work correctly.
Now your question:
if (i <= 0 && sum > 0 ) return 1;
Notice, that the only possibility that i<0 is that you called it with this value - no recursive call will be made with negative value of i. Such case (i<0) is an error so no result is proper (maybe assertion or exception would be better).
Now if i=0, assuming that at index 0 there is coin of value 1 means that there is only one way to exchange sum with this denomination - give sum coins of value 1. Right?
After a moment of thought I found out how to remove assumption that a[0] == 1. Change
if (i <= 0 && sum > 0 ) return 1;
into
if (i <= 0 && sum > 0 ) return sum % a[0] == 0 ? 1 : 0;
I believe the algorithm to be biased towards the choice of denominations, and assumes that there will be only one coin of the smallest denomination. Consider as a counter example of the correctness that there was no 2 coins, just 1,5,... And that the target to return was 4:
(4,1)
(-1,1) -> cut, sum<0 a[1]==5
(4,0) -> i==0 => 1
Either that or you misimplemented the algorithm (can there be an off by one error? Could it be i<0, or the original array be 1-based?)