Create A Number Pattern - c++

I am trying to get this number pattern
Input: 7
Output:
1 1 1 1 1 1 1
1 2 2 2 2 2 1
1 2 3 3 3 2 1
1 2 3 4 3 2 1
1 2 3 3 3 2 1
1 2 2 2 2 2 1
1 1 1 1 1 1 1
But I can't figure out how to make it like that, any suggestion how to make that pattern??
My code so far :
int n, temp1, temp2,i,j;
cin >> n;
for (i = 1; i <= n; i++) {
for (j = 1; j <= n; j++) {
temp1 = j;
temp2 = n-j+1;
if (temp1 < temp2) cout << temp1;
else cout << temp2;
}
cout << endl;
}
The output so far is
1 2 3 4 3 2 1
1 2 3 4 3 2 1
1 2 3 4 3 2 1
1 2 3 4 3 2 1
1 2 3 4 3 2 1
1 2 3 4 3 2 1
1 2 3 4 3 2 1
Thanks in advance.

I hope this code(working) might give you a better idea about the implementation.
int main() {
int n;
cin >> n;
int arr[n][n];
//Numbers in the grid vary from 1 - (n/2 + 1)
for(int i = 0; i <= n / 2; i++) {
//Start filling the array in squares
//Like fill the outer square with 1 first followed by 2...
for(int j = i; j < n - i; j++) {
arr[i][j] = i + 1;
arr[n - 1 - i][j] = i + 1;
arr[j][i] = i + 1;
arr[j][n - 1 - i] = i + 1;
}
}

The main thing that solves the problem is to divide this square into 4 quadrants:
---n-->
111|222 |
111|222 |
111|222 |
------- n
333|444 |
333|444 |
333|444 v
Each quadrant can be presented with limits:
1 - row <= (n + 1) / 2 && column <= (n + 1) / 2
2 - row <= (n + 1) / 2 && column > (n + 1) / 2
3 - row > (n + 1) / 2 && column <= (n + 1) / 2
4 - row > (n + 1) / 2 && column > (n + 1) / 2
Then every quadrant has to be divided into two slices
\ | /
\ | /
\|/
-------
/|\
/ | \
/ | \
These diagonals can be described using equations:
column_index = row_index
column_index = (n + 1) - row_index
Right now you just have to check if current 'cell' is under or above one of the diagonals, and use row or column index accordingly. Of course if row or column index is larger than (n + 1) / 2 then you have to adjust by subtracting it from n.
If you understand this, writing your own code shouldn't be a problem. It is good idea if you have to print everything immediately without storing it in some kind of array. If you can use array then #baymaxx solution is a lot cleaner.
It is my code if you would like to compare your implementation:
#include <iostream>
int main() {
int n;
std::cin >> n;
for (int row_index = 1; row_index <= n; row_index++) {
for (int column_index = 1; column_index <= n; column_index++) {
if (row_index <= (n + 1) / 2 && column_index <= (n + 1) / 2) {
if (column_index < row_index) {
std::cout << column_index << " ";
} else {
std::cout << row_index << " ";
}
} else if (row_index <= (n + 1) / 2 && column_index > (n + 1) / 2) {
if (column_index < (n + 1) - row_index) {
std::cout << row_index << " ";
} else {
std::cout << (n + 1) - column_index << " ";
}
} else if (row_index > (n + 1) / 2 && column_index <= (n + 1) / 2) {
if (column_index < (n + 1) - row_index) {
std::cout << column_index << " ";
} else {
std::cout << (n + 1) - row_index << " ";
}
} else {
if (column_index > row_index) {
std::cout << (n + 1) - column_index << " ";
} else {
std::cout << (n + 1) - row_index << " ";
}
}
}
std::cout << "\n";
}
}

Related

Incorrect output in Pascal's triangle program in C++

I was creating a Pascal's triangle program in C++, but the output displayed is not as expected.
Output Expected
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Output got
1
1 1
1 2 1
1 3 3 1
1 2 2 2 1
1 6 6 6 6 1
Till i = 4, output displayed is correct, but after that I couldn't figure out how it goes wrong. Hers is the source code to get reviewed
int main()
{ int num, a[37680], t = 0, b = 2, l;
cout<<"Enter the number of rows: ";
cin>>num;
for (int i = 1; i <= num; i++)
{
for (int j = 1; j <= (num - i); j++)
{
cout<<" ";
}
for (int k = 1; k <= i; k++)
{
l = k;
if (k == 1 || k == i)
{
a[t] = 1;
cout<<a[t]<<" ";
t+=1;
}
else
{
a[t] = a[t - b] + a[t - b - 1];
cout<<a[t]<<" ";
t+=1;
if ( l = (i - 1) )
{
b+=1;
}
}
}
cout<<endl;
}
return 0;}
Equality checking in c++ is done using == and not =, so:
if(l=(i-1))
Should be:
if(l==(i-1))

Coursera DSA Algorithmic toolbox week 4 2nd question- Partitioning Souvenirs

Problem Statement-
You and two of your friends have just returned back home after visiting various countries. Now you would
like to evenly split all the souvenirs that all three of you bought.
Problem Description
Input Format- The first line contains an integer ... The second line contains integers v1, v2, . . . ,vn separated by spaces.
Constraints- 1 . .. . 20, 1 . .... . 30 for all ...
Output Format- Output 1, if it possible to partition 𝑣1, 𝑣2, . . . , 𝑣𝑛 into three subsets with equal sums, and
0 otherwise.
What's Wrong with this solution? I am getting wrong answer when I submit(#12/75) I am solving it using Knapsack without repetition taking SUm/3 as my Weight. I back track my solution to replace them with 0. Test cases run correctly on my PC.
Although I did it using OR logic, taking a boolean array but IDK whats wrong with this one??
Example- 11
17 59 34 57 17 23 67 1 18 2 59
(67 34 17)are replaced with 0s. So that they dont interfare in the next sum of elements (18 1 23 17 59). Coz both of them equal to 118(sum/3) Print 1.
#include <iostream>
#include <vector>
using namespace std;
int partition3(vector<int> &w, int W)
{
int N = w.size();
//using DP to find out the sum/3 that acts as the Weight for a Knapsack problem
vector<vector<int>> arr(N + 1, vector<int>(W + 1));
for (int k = 0; k <= 1; k++)
{
//This loop runs twice coz if 2x I get sum/3 then that ensures that left elements will make up sum/3 too
for (int i = 0; i < N + 1; i++)
{
for (int j = 0; j < W + 1; j++)
{
if (i == 0 || j == 0)
arr[i][j] = 0;
else if (w[i - 1] <= j)
{
arr[i][j] = ((arr[i - 1][j] > (arr[i - 1][j - w[i - 1]] + w[i - 1])) ? arr[i - 1][j] : (arr[i - 1][j - w[i - 1]] + w[i - 1]));
}
else
{
arr[i][j] = arr[i - 1][j];
}
}
}
if (arr[N][W] != W)
return 0;
else
{
//backtrack the elements that make the sum/3 and = them to 0 so that they don't contribute to the next //elements that make sum/3
int res = arr[N][W];
int wt = W;
for (int i = N; i > 0 && res > 0; i--)
{
if (res == arr[i - 1][wt])
continue;
else
{
std::cout << w[i - 1] << " ";
res = res - w[i - 1];
wt = wt - w[i - 1];
w[i - 1] = 0;
}
}
}
}
if (arr[N][W] == W)
{
return 1;
}
else
{
return 0;
}
}
int main()
{
int n;
std::cin >> n;
vector<int> A(n);
int sum = 0;
for (size_t i = 0; i < A.size(); ++i)
{
int k;
std::cin >> k;
A[i] = k;
sum += k;
}
if (sum % 3 == 0)
std::cout << partition3(A, sum / 3) << '\n';
else
std::cout << 0;
}
Sum/3 can be achieved by multiple ways!!!! So backtracking might remove a subset that has an element that should have been a part of some other subset
8 1 6 is 15 as well as 8 2 5 makes 15 so better is u check this
if(partition3(A, sum / 3) == sum / 3 && partition3(A, 2 * (sum / 3)) == 2 * sum / 3 && sum == partition3(A, sum))

How to write this recursion with loops

I saw the following as an exercise in a website. It basically says write the following function without using recursion and without using structures like vector, stack, etc:
void rec(int n) {
if (n != 0) {
cout << n << " ";
rec(n-1);
rec(n-1);
}
}
At first I thought it was going to be easy, but I'm suprisingly struggling to accomplish it.
To understand it better, I defined it like a math function as the following:
f(x) = {1 if x = 0, f(x-1) + f(x-1) otherwise} (where + operator means concatenation and - is the normal minus)
However, Unrolling this made it harder, and I'm stuck. Is there any direct way to write it as a loop? And also, more generally, is there an algorithm to solve this type of problems?
If you fiddle with it enough, you can get at least one way that will output the ordered sequence without revisiting it :)
let n = 5
// Recursive
let rec_str = ''
function rec(n) {
if (n != 0) {
rec_str += n
rec(n-1);
rec(n-1);
}
}
rec(n)
console.log(rec_str)
// Iterative
function f(n){
let str = ''
for (let i=1; i<1<<n; i++){
let t = i
let p = n
let k = (1 << n) - 1
while (k > 2){
if (t < 2){
break
} else if (t <= k){
t = t - 1
p = p - 1
k = k >> 1
} else {
t = t - k
}
}
str += p
}
console.log(str)
}
f(n)
(The code is building a string, which I think should be disallowed according to the rules, but only for demonstration; we could just output the number instead.)
void loop(int n)
{
int j = 0;
int m = n - 1;
for (int i = 0; i < int(pow(2, n)) - 1; i++)
{
j = i;
if (j == 0)
{
std::cout << n << " ";
continue;
}
m = n - 1;
while (true)
{
if (m == 1)
{
std::cout << m << " ";
m = n - 1;
break;
}
if (j >= int(pow(2, m)))
{
j = j - int(pow(2, m)) + 1;
}
if (j == 1)
{
std::cout << m << " ";
m = n - 1;
break;
}
else
{
j--;
}
m--;
}
}
std::cout << std::endl;
}
For n = 3 for instance
out = [3 2 1 1 2 1 1]
indexes = [0 1 2 3 4 5 6]
Consider the list of indexes; for i > 0 and i <= 2^(m) the index i has the same value as the index i + 2^(m)-1 where m = n - 1. This is true for every n. If you are in the second half of the list, find its correspondent index in the first half by this formula. If the resulting number is 1, the value is m. If not, you are in a lower level of the tree. m = m - 1 and repeat until the index is 1 or m =1, in which case you've reached the end of the tree, print 1.
For instance, with n = 4, this is what happens with all the indexes, at every while step. p(x) means the value x gets printed at that index. A / means that index has already been printed.:
n = 4,m = 3
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
m = 3
[p(n=4) 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
if(i >=2^3) -> i = i -2^3 + 1)
[/ 1 2 3 4 5 6 7 1 2 3 4 5 6 7]
if(i == 1) -> print m, else i = i -1
[/ p(3) 1 2 3 4 5 6 p(3)1 2 3 4 5 6]
m = 2
if (i >=2^2) -> i = i - 2^2 +1
[/ / 1 2 3 1 2 3 / 1 2 3 1 2 3]
if(i == 1) -> print m, else i = i -1
[ / / p(2) 1 2 p(2) 1 2 / p(2) 1 2 p(2) 1 2]
m = 1
if (m == 1) -> print(m)
[ / / / p(1) p(1) / p(1) p(1) / / p(1) p(1) / p(1) p(1)]
Therefore the result is:
[4 3 2 1 1 2 1 1 3 2 1 1 2 1 1]
void via_loop(int n) {
string prev = "1 ", ans = "1 ";
for (int i = 2; i <= n; i++) {
ans = to_string(i) + " " + prev + prev;
prev = ans;
}
cout << ans;
}
Idea is to save result from the previous computation of each number. Full code:
void rec(int n) {
if (n != 0) {
cout << n << " ";
rec(n-1);
rec(n-1);
}
}
void via_loop(int n) {
string prev = "1 ", ans = "1 ";
for (int i = 2; i <= n; i++) {
ans = to_string(i) + " " + prev + prev;
prev = ans;
}
cout << ans;
}
int main() {
int n = 5;
cout << "Rec : ";
rec(n);
cout << endl;
cout << "Loop: ";
via_loop(n);
cout << endl;
}
Output:
Rec : 5 4 3 2 1 1 2 1 1 3 2 1 1 2 1 1 4 3 2 1 1 2 1 1 3 2 1 1 2 1 1
Loop: 5 4 3 2 1 1 2 1 1 3 2 1 1 2 1 1 4 3 2 1 1 2 1 1 3 2 1 1 2 1 1

I can't figure out a sum and numbers solution

I am not that skilled or advanced in C++ and I have trouble solving a problem.
I know how to do it mathematically but I can't write the source code, my algorithm is wrong and messy.
So, the problem is that I have to write a code that reads a number ( n ) from the keyboard and then it has to find a sum that is equal to n squared ( n ^ 2 ) and the number of sum's elements has to be equal to n.
For example 3^2 = 9, 3^2 = 2 + 3 + 4, 3 elements and 3^2 is 9 = 2 + 3 + 4.
I had several attempts but none of them were successful.
I know I'm borderline stupid but at least I tried.
If anyone has the time to look over this problem and is willing to help me I'd be very thankful.
1
#include <iostream>
#include <list>
#include <algorithm>
using namespace std;
int main()
{
//1,3,5,7,9,11,13,15,17,19,21,23,25,27..
int n;
list<int> l;
cin >> n;
if ( n % 2 == 0 ){
cout << "Wrong." << endl;
}
for ( int i = 1; i <= 99;i+=2){
l.push_back(i);
}
//List is full with 1,3,5,7,9,11,13,15,17,19,21,23,25,27..
list<int>::iterator it = find(begin(l),end(l), n);
}
2
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
// 3^2 = 2 + 3 + 4
// 7^2 = 4 + 5 + 6 + 7 + 8 + 9 + 10
int n;
int numbers[100];
for (int i = 0; i <= 100; i++){
numbers[i] = i;
}
cin >> n;
int requiredSum;
requiredSum = n * n;
//while(sum < requiredSum){
// for(int i = 1; i < requiredSum; i++){
// sum += i;
// sumnums.push_back(sum);
// }
//}
int sum = 0;
std::vector<int> sumnums;
while(sum < requiredSum){
for(int i = 1; i < requiredSum; i++){
sum += i;
sumnums.push_back(sum);
}
}
for(int i=0; i<sumnums.size(); ++i)
std::cout << sumnums[i] << ' ';
}
Update:
The numbers of the sum have to be consecutive numbers.Like 3 * 3 has to be equal to 2 + 3 + 4 not 3 + 3 + 3.
So, my first try was that I found a rule for each sum.
Like 3 * 3 = 2 + 3 + 4, 5 * 5 = 3 + 4 + 5 + 6 + 7, 7 * 7 = 4 + 5 + 6 + 7 + 8 + 9 + 10.
Every sum starts with the second element of the previous sum and continues for a number of elements equal to n - 1, like 3 * 3 = 2 + 3 + 4, 5 * 5 , the sum for 5 * 5 starts with 3 + another 4 elements.
And another algorithm would be #molbdnilo 's, like 3 * 3 = 3 + 3 + 3 = 3 + 3 + 3 - 1 + 1, 3 * 3 = ( 3 - 1 ) + 3 + ( 3 + 1 ), but then 5 * 5 = (5 - 2) + ( 5 - 1 ) + 5 + 5 + 1 + 5 + 2
Let's do a few special cases by hand.
(The division here is integer division.)
3^2: 9
2 + 3 + 4 = 9
x-1 x x+1
1 is 3/2
5: 25
3 + 4 + 5 + 6 + 7 = 25
x-2 x-1 x x+1 x+2
2 is 5/2
7: 49
4 + 5 + 6 + 7 + 8 + 9 + 10
x-3 x-2 x-1 x x+1 x+2 x+3
3 is 7/2
It appears that we're looking for the sequence from n - n / 2 to n + n / 2.
(Or, equivalently, n / 2 + 1 to n / 2 + n, but I like symmetry.)
Assuming that this is correct (the proof left as an exercise ;-):
int main()
{
int n = 0;
std::cin >> n;
if (n % 2 == 0)
{
std::cout << "Must be odd\n";
return -1;
}
int delta = n / 2;
for (int i = n - delta; i <= n + delta; i++)
{
std::cout << i << " ";
}
std::cout << std::endl;
}
If there is not constraints on what are the elements forming the sum, the simplest solution is just to sum up the number n, n times, which is always n^2.
int main()
{
int n;
cout<<"Enter n: ";
cin >> n;
for(int i=0; i<n-1; i++){
cout<<n<<"+";
}
cout<<n<<"="<<(n*n);
return 0;
}
Firstly, better use std::vector<> than std::list<>, at least while you have less than ~million elements (it will be faster, because of inside structure of the containers).
Secondly, prefer ++i usage, instead of, i++. Specially in situation like that
...for(int i = 1; i < requiredSum; i++)...
Take a look over here
Finally,
the only error you had that you were simply pushing new numbers inside container (std::list, std::vector, etc.) instead of summing them, so
while(sum < requiredSum){
for(int i = 1; i < requiredSum; i++){
sum += i;
sumnums.push_back(sum);
}
change to
// will count our numbers
amountOfNumbers = 1;
while(sum < requiredSum && amountOfNumber < n)
{
sum += amountOfNumbers;
++amountOfNumbers;
}
// we should make -1 to our amount
--amountOfNumber;
// now let's check our requirements...
if(sum == requiredSum && amountOfNumbers == n)
{
cout << "Got it!";
// you can easily cout them, if you wish, because you have amountOfNumbers.
// implementation of that I am leaving for you, because it is not hard ;)
}
else
{
cout << "Damn it!;
}
I assumed that you need sequential sum of numbers that starts from 1 and equals to n*n and their amount equils to n.
If something wrong or need explanation, please, do not hesitate to contact me.
Upd. amountOfNumber < n intead <=
Also, regarding "not starting from 1". You said that you know how do it on paper, than could you provide your algorithm, then we can better understand your problem.
Upd.#2: Correct and simple answer.
Sorry for such a long answer. I came up with a great and simple solution.
Your condition requires this equation x+(x+1)+(x+2)+... = n*n to be true then we can easily find a solution.
nx+ArPrg = nn, where is
ArPrg - Arithmetic progression (ArPrg = ((n-1)*(1+n-1))/2)
After some manipulation with only unknown variable x, our final equation will be
#include <iostream>
int main()
{
int n;
std::cout << "Enter x: ";
std::cin >> n;
auto squareOfN = n * n;
if (n % 2 == 0)
{
std::cout << "Can't count this.\n";
}
auto x = n - (n - 1) / 2;
std::cout << "Our numbers: ";
for (int i = 0; i < n; ++i)
std::cout << x + i << " ";
return 0;
}
Math is cool :)

C++ summing multiples of 3 and 5

I just started C++ programming for three days now and I cannot figure out how to complete this exercise. Basically, I want to sum all multiples of 3 and 5 under 1000. Here is my code:
int sum3n5(int max){
int sum = 0;
for(int i = 1; i <= max; ++i){
if( i%3 == 0 && i%5 == 0 ) { sum += i;}
else if( i%3 == 0 || i%5 == 0 ) { sum +=i;}
return sum;
};
};
Sorry if it is a trivial mistake that I failed to realize.
I always get the result 0 after running this.
int sum3n5(int max){
int sum = 0;
for (int i = 1; i <= max; ++i){
if( i % 3 == 0 || i % 5 == 0 ){
sum += i;
}
}
return sum;
}
You only need the || (logical or) operator, not the && (and certainly not both!). And the return needs to be after the for loop so that the loop can complete before the function returns.
A version without loop:
int sum3n5(int max)
{
return 3 * (max / 3) * (max / 3 + 1) / 2
+ 5 * (max / 5) * (max / 5 + 1) / 2
- 15 * (max / 15) * (max / 15 + 1) / 2;
}
It uses the fact that 1 + 2 + .. + n == n * (n + 1) / 2