I am trying to create a program in c++ that takes in triangle pattern of numbers into a 2-D array.
Example:
1
3 4
5 9 2
9 4 6 1
The top row is one number(integer) and each row of the triangle has one more number than the row above it.
Once the triangle has been entered and/or examined via for loops, the program needs to traverse the triangle from top to bottom and record all possible sums of each path;
The path taken down the triangle must always be adjacent to the number in the row above it.
While traversing down the triangle each "path" should be stored in a new array so the path can be displayed.
After recording the sum for each path down the triangle the program should compare them and display the path with the smallest sum.
With the changes i made so far thanks to #Beta i have this so far:
int main()
{
int row = 0;
int col = 0;
int A[4][4] = {{2},{8,9},{3,4,5},{6,2,9,1}};
for (row = 0; row < 4; row++)
{
for (col = 0; col <= row; col++)
{
cout << A[row][col] << " ";
}
cout << endl;
My Output is so far is:
2
8 9
3 4 5
6 2 9 1
I think the trick you're looking for is this:
for (col = 0; col <= row; col ++)
I couldn't parse the last part of your question ("After that...").
EDIT:
The problem of making the triangle look symmetrical is a problem of printing spaces at the beginning of each line. With the trick above, you should be able to figure than one out.
As for considering all paths and displaying the one with the smallest sum, what have you tried? If you are not familiar with Breadth-First Search and Depth-First Search, copying arrays and arrays of pointers, you're probably not ready for this exercise.
Related
There's a problem, which I've to solve in c++. I've written the whole code and it's working in the given test cases but when I'm submitting it, It's saying wrong answer. I can't understand that why is it showing wrong answer.
I request you to tell me an input for the given code, which will give incorrect output so I can modify my code further.
Shrink The Array
You are given an array of positive integers A[] of length L. If A[i] and A[i+1] both are equal replace them by one element with value A[i]+1. Find out the minimum possible length of the array after performing such operation any number of times.
Note:
After each such operation, the length of the array will decrease by one and elements are renumerated accordingly.
Input format:
The first line contains a single integer L, denoting the initial length of the array A.
The second line contains L space integers A[i] − elements of array A[].
Output format:
Print an integer - the minimum possible length you can get after performing the operation described above any number of times.
Example:
Input
7
3 3 4 4 4 3 3
Output
2
Sample test case explanation
3 3 4 4 4 3 3 -> 4 4 4 4 3 3 -> 4 4 4 4 4 -> 5 4 4 4 -> 5 5 4 -> 6 4.
Thus the length of the array is 2.
My code:
#include <bits/stdc++.h>
using namespace std;
int main()
{
bool end = false;
int l;
cin >> l;
int arr[l];
for(int i = 0; i < l; i++){
cin >> arr[i];
}
int len = l, i = 0;
while(i < len - 1){
if(arr[i] == arr[i + 1]){
arr[i] = arr[i] + 1;
if((i + 1) <= (len - 1)){
for(int j = i + 1; j < len - 1; j++){
arr[j] = arr[j + 1];
}
}
len--;
i = 0;
}
else{
i++;
}
}
cout << len;
return 0;
}
THANK YOU
As noted in the comments: Just picking the first two neighbours that have the same value and combining those will lead to suboptimal results.
You will need to investigate which two neighbours you should combine somehow. When you have combined two neighbours you then need to investigate which neighbours to combine on the next level. The number of combinations may become plentiful.
One way to solve this is through recursion.
If you've followed the advice in the comments, you now have all your input data in std::vector<unsigned> A(L).
You can now do std::cout << solve(A) << '\n'; where solve has the signature size_t solve(const std::vector<unsigned>& A) and is described below:
Find the indices of all neighbour pairs in A that has the same values and put the indices in a std::vector<size_t> neighbours. Example: If A contains 2 2 2 3, put 0 and 1 in neighbours.
If no neighbours are found (neighbours.empty() == true), return A.size().
Define a minimum variable and initialize it with A.size() - 1 which is the worst result you know you can get at this point. So, size_t minimum = A.size() - 1;
Loop over all indices stored in neighbours (for(size_t idx : neighbours))
Copy A into a new std::vector<unsigned>. Let's call it cpy.
Increase cpy[idx] by one and remove cpy[idx+1].
Call size_t result = solve(cpy). This is where recursion comes in.
Is result less than minimum? If so assign result to minimum.
Return minimum.
I don't think I ruined the programming exercise by providing one algorithm for solving this. It should still have plenty of things to deal with. Recursion won't be possible with big data etc.
hello stack overflowers!
haha I am relatively new to c++ and I have a small problem figuring out small piece of the code. Basically I need to print out a full array of ints in 5 different columns. The thing that throws me off is that I have no clue how many ints are in the array and how many rows it'd create?(it is a 1d array) 2d is very easy to process. I just dont know how to go about this. Any logical help would be much appreciated. I have no problem coding it i just don't know how to set this up. Ive been thinking about it for some time now.
You need to know the total number of elements in the 1d-array and we need decompose the number of these elements in the 1d array on the two multiplier.
First multiplier will be lines, second - rows.
For example if we have 50 elements in the 1d-array
we can assume that we have 10 lines and 5 columns
and then write something like this:
for(int line = 0; line < 10; line++)
{
for( int col = 0; col < 5; col++)
{
cout << setw(5) << arr[line*5 + col];
}
cout << endl;
}
I'm currently working on a project for my upper-level C++ class, and we are building a program that makes a maze, then solves it, the makes a PNG of said maze. Pretty cool stuff. Anyways, I'm current on the bit where I need to make the maze.
My program makes valid mazes just fine, but I have to make each number output unique. The output just spits out two indicies in a 2d matrix that have walls between them, sample output for a 3X4 maze is as follows:
rjeffor1:hydra20 ~/cs302/labs/lab5> ./mazemake 3 4 <- 9:49AM
1 2
1 5
2 1
2 3
3 2
5 1
5 9
6 7
7 6
8 9
9 8
9 5
However, my last problem is that I need to get rid of duplicate walls, for example 1 2 and 2 1. EDIT: and by this I mean just get rid of the 2 1, I still need the wall and therefore the 1 2.
Here is my function in which I attempt to fix the problem:
void aL::make_unique()
{
vector<int>::iterator it, it0;
//need to iterate thru all but last index
for (int i=0; i<(int)adjList.size()-1; i++) {
for (int j=0; j<(int)adjList.size(); j++) {
//find it
if (i!=j) {
it0 = std::find(adjList[i].begin(), adjList[i].end(), j);
it = std::find(adjList[j].begin(), adjList[j].end(), i);
if (it!=adjList[j].end() && it!=adjList[j].end())
//erase it if anything is there
adjList[j].erase(it);
}
}
}
}
Help is appreciated, my brain is so done at this point
EDIT: here is how I populate the adjancency lists, based on indicies directly left right above and below each index
aL::aL (const int &rows, const int &cols)
{
adjList.resize(rows*cols);
//run thru and figure out where indicies AREN'T
//to fill in their adjacency list
for (int i=0; i<(int)adjList.size(); i++) {
//if not on the left edge
if (i%cols!=0)
adjList[i].push_back(i-1);
//not on the right edge
if ((i+1)%cols!=0)
adjList[i].push_back(i+1);
//not on the top edge
if (i>=cols)
adjList[i].push_back(i-cols);
//not on the bottom edge
if (i<(rows*cols)-cols)
adjList[i].push_back(i+cols);
}
}
You could remove the need to post-process and make it unique at the end if you check as you are adding to your list. Don't add "a b" if "b a" is already there.
Let's say that I have a 2D array that looks like:
________________
|10|15|14|20|30|
|14|10|73|71|55|
|73|30|42|84|74|
|14|74|XX|15|10|
----------------
As I showed, the columns don't need to be same size.
Now I need to find the best matching for each column (the one that has most exactly the same items and lowest different). Of course, I could do that in n^2 but it's too slow for me. How can I do it?
I thought about a k-dimension tree and finding the closest neighbor for every one, but I don't know if it's good and it will work as I want (probably not).
Result for example:
First column is most likely third (only three different - 10, 14, 42)
Second column -> fifth (only two different - 15 and 55)
and so on and so on... :)
If you know that all the numbers in the table are 2-digit numbers (i.e. 10 =< x <100), for each column create an array of booleans where you will mark the existing numbers:
bool array[5][100];
std::fill( &array[0][0], &array[0][0] + sizeof(array) , false ); // init to false
for (int i = 0; i < 5; i++)
{
for (int j = 0; j <5; j++)
{
array[i][table[i][j]] = true;
}
}
Should be easy from there.
I'm not sure if this question has been either asked
or quite possibly already answered. If I start with
an original 3x3 matrix:
1 2 3
4 5 6
7 8 9
, how would I produce the following 3x3 matrix:
9 6 3
8 5 2
7 4 1
??
For an N*N square matrix :
for(int i=0;i<n-1;i++)
for(int j=0;j<n-1-i;j++) //Swap elements above anti-diagonal
std::swap(mat[i][j],mat[n-1-j][n-1-i]); //with elements below it
Since you're trying to reflect about the secondary diagonal (that's NOT transposition), here's the code, a slightly modified copy of Peter's:
for (int i = 0; i < n; i++)
{
for (int j = 0; j < i; j++)
{
int temp = a[i][j];
a[i][j] = a[n - 1 - j][n - 1 - i];
a[n - 1 - j][n - 1 - i] = temp;
}
}
For a reflection, pairs of items in the matrix are swapped, so the "do something" (within the loops) will be a swap operation. Loops will be used to pick an item to swap, and some basic arithmetic is used to choose which item to swap it with. The loops should iterate over the triangle of items that are one side of the axis to reflect around, excluding those on the reflection axis and on the other side of it. To visualise that...
0 1 2
0 * * /
1 * / .
2 / . .
The asterisks are the items to use as first parameters for the swap. The dots are the items to use as second parameters to the swap. The slashes are on the reflection axis.
Therefore...
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < (n-1)-i; j++) // Thanks to Bugaboo for bugfix
{
std::swap (a[i][j], a[2-j][2-i]);
}
}
With a 3x3 matrix, the loops are a bit excessive - they are shown here for the principle, and to show how to extend it. There are only three asterisks in that visualisation, and only three swap operations needed...
std::swap (a[0][0], a[2][2]);
std::swap (a[0][1], a[1][2]);
std::swap (a[1][0], a[2][1]);
I think I found a way in the MatLab that combines a series of other existing flipping method.
fliplr (flip left and right)
transpose
fliplr
Ham is the target then the code is the following.
Maybe it is wrong, but let me know.
fliplr(fliplr(Ham)')