How to display Non Diagonal 2D Array elements - c++

I am successful in displaying Diagonal Array elements, but failed to display Non Diagonal array elements I tried a lot but unsuccessful. Here is the code what I am try with I am using Turbo C++ -
#include<conio.h>
#include<iostream.h>
void accept(int a[4][4],int size)
{
cout<<"Diagonal One:";
for (int i=0;i<size;i++)
for(int j=0;j<size;j++)
if (i!=j)
cout<<"\n"<<i <<" "<<j<<" "<<a[i][j];
}
void main()
{
int a[4][4]={{5,4,3,4},{6,7,9,1},{8,0,3,7},{2,4,5,9}};
clrscr();
accept(a,4);
getch();
}
Example : if the array content is
5 4 3 4
6 7 9 1
8 0 3 7
2 4 5 9
Output through the function should be :
4 3 6 1 8 7 4 5
Output is displaying some of the diagonal elements also.

The function skips all elements in the diagonal 5739 (i != j takes care of this), but, based on the desired output, you also wish to skip all elements in the diagonal 4902.
To also check for the other diagonal, replace
if (i != j)
with
if (i != j && i != size-j-1)
Test.

Related

N X 3 matrix shorting and unique element matrix extraction

I am facing problem with a 2D matrix consist of 3 column and N rows. Now I wanted to sort the matrix in such a way that the smallest of the first row is the first element, and so on. The first element of the second row is the smallest number with the smallest value of the first row. and similar to 3rd row. For example,
A B C
5 2 6
6 5 8
2 9 4
4 5 8
2 3 5
2 9 2
so the sorted matrix will be
A B C
2 3 5
2 9 2
2 9 4
4 5 8
5 2 6
6 5 8
Also, it will store the index of them such that
A_i B_i C_i
5 5 5
6 6 6
3 3 3
and so on...
I implemented this using C++ which is not computationally efficient and takes so much time for a very big matrix. How I can Implement this a computationally efficient way and fast?
My current C++ code for the same is as follow
for(int tii=0; tii<f_sizee; tii++){
track_index(tii)=tii+1;
}
for(int chkhk=0;chkhk<f_sizee;chkhk++){
if(check_index(chkhk)==1){
for(int chkhk1=chkhk+1;chkhk1<f_sizee;chkhk1++){
if((Va_mat(chkhk,0)==Va_mat(chkhk1,0))&&(Va_mat(chkhk,1)==Va_mat(chkhk1,1))&&(Va_mat(chkhk,2)==Va_mat(chkhk1,2))){
check_index(chkhk1)=0;
track_index(chkhk1)=seed_ind;
}
else track_index(chkhk)=seed_ind;
}
seed_ind=seed_ind+1;
}
}
int new_dim=sum(check_index);
int new_count=0;
mat unsort_vmat=zeros(new_dim,Va_mat.n_cols);
for(int iij=0; iij<f_sizee; iij++){
if(check_index(iij)==1){
unsort_vmat.row(new_count)=Va_mat.row(iij);
new_count++;
}
}
mat sort_vmat=zeros(new_dim,Va_mat.n_cols);
uvec indices = stable_sort_index(unsort_vmat.col(0));
int contrrS=0;
for(int sort_f=0; sort_f < new_dim; sort_f++){
for(uword sort_f2=0; sort_f2 < Va_mat.n_cols; sort_f2++){
contrrS=indices(sort_f);
sort_vmat(sort_f,sort_f2)=unsort_vmat(contrrS,sort_f2);
}
}
mat sort_vmat2 = zeros(new_dim,Va_mat.n_cols);
sort_vmat2 = sort_vmat ;
double element_tmp=0;
for(int iitr=0; iitr < new_dim; iitr++){
for(int iitk=iitr; iitk < new_dim; iitk++){
if(sort_vmat(iitk,0)==sort_vmat(iitr,0)){
if(sort_vmat(iitk,1)>sort_vmat(iitr,1)){///if error, delete this brace
element_tmp=sort_vmat(iitr,1);
sort_vmat(iitr,1)=sort_vmat(iitk,1);
sort_vmat(iitk,1)=element_tmp;
}
}
}
}
vec new_ind=zeros(f_sizee);
int start_ind=0;
for(int new_index=0; new_index<f_sizee; new_index++){
new_ind(new_index)=start_ind;
start_ind++;
}
int itr_count=0;
for(uword itr1=0; itr1<Va_mat.n_rows; itr1++){
for(int itr2=0; itr2<new_dim; itr2++){
if((Va_mat(itr1,0)==sort_vmat2(itr2,0))&&(Va_mat(itr1,1)==sort_vmat2(itr2,1))&&(Va_mat(itr1,2)==sort_vmat2(itr2,2))){
new_ind(itr_count)=itr2+1;
itr_count++;
}
}
}
int funda=0;
for(unsigned int Faa=0; Faa<Fa_mat.n_rows; Faa++){
for(unsigned int Fab=0; Fab<Fa_mat.n_cols; Fab++){
Fa_mat(Faa, Fab)=new_ind(funda);
funda++;
}
}

Getting funny output for insertion sort

I'm trying to implement insertion sort. My logic may be wrong because I was unable to complete my code due to some error.
I want help with values changing absurdly while executing. Also, there is a similar repeating element question but it is in python and it went over my head. so, please don't mark it duplicate.
As you can see I have initialized a temporary variable index, why you ask? because the value of N is changing during run time.
secondly, Value is getting repeated when sorting is taking place.
I'm using codeblocks 17.2.
#include<iostream>
#include<utility>
#include<algorithm>
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
int arr[100];
int N,index;
cin>>N;
for(int i=0;i<N;i++)
{
cin>>arr[i];
}
index=N; // using temperory variable
for(int l=0;l<index;l++)
{
for(int j=l+1;j>=0;j--)
{
if(l==index-1 || j==0) //Working fine now
break;
if(arr[j]<arr[j-1])
{
swap(arr[j],arr[j-1]);
}
}
cout<<N<<endl; //value of n is changing but why
for(int k=0;k<index;k++)
{
cout<<arr[k]<<" "; //value of array is also coming wrong
}
cout<<"\n";
}
return 0;
}
N=7
and elements of the array to be
7 8 5 2 4 6 3
output is
7 //these are the values of N which is changing
7 8 5 2 4 6 3
5
7 7 8 2 4 6 3
2
5 7 7 8 4 6 3
2
4 5 7 7 8 6 3
2
4 5 6 7 7 8 3
2
3 4 5 6 7 7 8
0
2 3 4 5 6 7 7
check for boundary condition and when non-existing array index is accessed it will give undefined behavior. In this case, it appears that N was stored right before arr and it changed when you modified arr[-1].

Problem with my quicksort, it doesn't sort correctly

OK I am trying to make Prima algorithm so i need my edges array sorted, I tried to use quicksort here but it didn't work as I planned.
#include <iostream>
using namespace std;
void Sort (int arr[100][4], int m, int l) {
int i,j,x,v;
i=m;
j=l;
x=(i+j)/2;
do
{
while (((arr[i][3]<arr[x][3]))and(i<=l)) i++;
while (((arr[j][3]>arr[x][3]))and(j>=m)) j--;
if (i<=j)
{
v=arr[i][1];
arr[i][1]=arr[j][1];
arr[j][1]=v;
v=arr[i][2];
arr[i][2]=arr[j][2];
arr[j][2]=v;
v=arr[i][3];
arr[i][3]=arr[j][3];
arr[j][3]=v;
i++;
j--;
}
}
while (i<=j);
if (i<l) Sort(arr,i,l);
if (m<j) Sort(arr,m,j);
}
int main () {
int i,x,y,z,n,m;
int a[100][4];
fill(&a[0][0],&a[0][0]+400,0);
cout<<"Enter number of nodes and edges\n";
cin>>n>>m;
cout<<"Enter edges and their weights\n";
for (i=0;i<m;i++) {
cin>>x>>y>>z;
a[i][1]=min(x,y);
a[i][2]=max(x,y);
a[i][3]=z;
}
Sort (a,0,m-1);
for (i=0;i<m;i++) {
cout<<i+1<<") "<<a[i][1]<<' '<<a[i][2]<<' '<<a[i][3]<<endl;
}
return 0;
}
what I put is
5 10
1 2 4
1 3 7
4 1 5
5 1 8
2 3 3
2 4 6
2 5 6
3 4 8
3 5 2
4 5 4
what I get is
1) 3 5 2
2) 2 3 3
3) 1 4 5
4) 1 2 4
5) 4 5 4
6) 2 5 6
7) 2 4 6
8) 1 3 7
9) 1 5 8
10) 3 4 8
I don't understand why 5 is going ahead of 4's. Hope you could help.
You choose the pivot element in the middle of the (sub)array, which is fine, but you leave it in that position when you run the partitioning loop, and rely on it to stay there, which is not ok. With your approach, the pivot is likely to be swapped to a different position during the ordinary course of partitioning, after which the remainder of the partitioning will be based on the key swapped into the pivot's original position, which is likely to be different.
The usual approach is to start by swapping the pivot element to one end of the array or the other, partition the rest of the array, and then afterward swap the pivot into its correct position, as discovered via the partitioning process.
Change the code to use the pivot value instead of the pivot index, and some fixes to make it more like conventional Hoare partition scheme:
i=m-1;
j=l+1;
x=arr[(i+j)/2][3];
while(1)
{
while (arr[++i][3] < x);
while (arr[--j][3] > x);
if(i >= j)
return j;
// ...

Creating a pyramid of numbers with a certain logic

I need a program that will output this figure:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
If you add the numbers on both ends, it will print the output beside it (inward). And then you will also add those two sums and print it again inwardly. Another thing, the input should be the largest number (in this case, number 8) It could be larger than 8 like the figure below.
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
In this case the input is 16. And so on. This is my latest program.
#include<iostream>
using namespace std;
int main(){
int i, j, k, b, a, space=10;
for(int i=0;i<=5;i++){
for(k=0;k<space;k++){
cout<<" ";
}
for(j=1;j<=2*i-1;j=j*2){
cout<<j<<" ";
}
space--;
cout<<endl;
}
system("pause");
return 0;
}
Please help me improve this. It's not yet a pyramid. Help me to output the desired figure at least.
To correctly format your pyramid, supposing you're using fixed width characters, you need to know beforehand some information, e.g.:
what is the largest number that you're going to print.
how many numbers have which width.
Since the pyramid is increasing downwards, this information is available when you print the last line.
So what you need to do is to calculate (but not output, of course) the last line first. Say that you want five rows, then the middle number will be 2^(5-1), i.e. 16. So you will have to output 1 2 4 8 16. The column positions will be 0 (beginning), 2 (0 plus length of "1" plus 1 space), 4 (2 plus 1 plus 1 space), 6 (4 plus 1 plus 1), 8, 11 (8 plus length of "16" which is 2, plus 1 space), 13, 15, 17.
At this point you start output of the first line, beginning at column 5, i.e. at position 8.
The second line will start at column 4, i.e. at position 6.
And so on.
Another possibility is to imagine you're filling a table (as if you were generating a HTML table):
- fill it top to bottom
- "explore" every cell size the same way as above, in any order
- generate column positions accordingly
- print the table top to bottom
This requires only one round of calculations, but needs memory storage for the table itself.
A shortcut is to verify what is the largest number you're gonna print, and format all columns with that width. In this case 16 is 2 characters, so you add one space padding and output all columns padded to 3 character width. This may waste unnecessary space.
The latter case can be implemented using cout.width:
int main() {
int line;
// Read input from standard input
cin >> line;
// We output the pyramid by allocating a fixed width to each number.
// This requires to know beforehand which will be the largest number.
// We can observe that at every line, the largest number is 2 to the
// power of that line number: on line 0, the largest number is 2^0
// which is 1, on line 1 it is 2 which is 2^1... on line 4 it is 16
// which is 2^4. So if we have five lines (from 0 to 4), the largest
// number will be 2 to the 4th.
// Now the length of a number in base 10 is given by the logarithm
// base 10 of that number, truncated, plus 1. For example log10 of
// 1000 is exactly 3, and 3+1 is 4 digits. Log10 of 999 is
// 2.9995654... which truncates to 2, 2+1 is 3 and 999 is 3 digits.
// Here our number is 2 to the power of (line-1).
// By the properties of the logarithm
// this is the same as (line-1)*log10(2), and log10(2) is around 0.3.
// So we multiply (line-1) by log10(2), truncate to integer and add 1
// (or vice versa: we add 1 and then assign to width, which is an
// integer, thereby truncating the value to integer.
// But we need to add another 1 for the padding space (we want 1 2 4
// 2 1, not 12421...). So before assigning, we add 2, not 1.
int width = 2+(line-1)*0.30102999566398119521373889472449;
//////////////////////
// TODO: we're gonna output 2*line+1 strings, each 'width' wide.
// So if (2*line+1)*width > 80 we'd better say it and stop, or the
// output will be sorely messed up, since a terminal is only 80 chars
// wide at the most. Which means that N=9 is the maximum number we
// can print out and still be "nice".
// Having not been asked to do this, we proceed instead.
//////////////////////
// For every line that we need to output...
for (int i = 0; i < line; i++) {
// Pad line-i empty spaces
for (int j = 0; j < (line-i); j++) {
// Set the width of the next cout to "width" bytes
cout.width(width);
cout<<" ";
}
int n = 1;
// output the forward sequence: 1, 2, 4... doubling each time
for (int j = 0; j < i; j++) {
cout.width(width);
cout <<n;
n *= 2;
}
// output the top number, which is the next doubling
cout.width(width);
cout <<n;
// output the sequence in reverse. Halve, output, repeat.
for (int j = 0; j < i; j++) {
n /= 2;
cout.width(width);
cout<<n;
}
// Now n is 1 again (not that we care...), and we output newline
cout <<"\n";
}
// Return 0 to signify "no error".
return 0;
}
Check the Code. This will give the desire output .
#include<iostream>
using namespace std;
int main(){
int line = 4;
for (int i =0; i < line; i++){
for(int j = line - i; j >0 ; j --){
cout<<" ";
}
int temp = 1;
for(int k = 0; k < i + 1; k ++){
cout << " "<<temp;
temp = temp *2;
}
temp /=2;
for(int k =0; k < i; k ++){
temp /=2;
cout << " "<<temp;
}
cout <<"\n";
}
return 0;
}
Output:
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1

Recursion questions

I'm making a sudoku solver using recursion and I'm having some problems. I put comments next to my vables and functions to try to make this as clear as possible. Does my logic sound like this would work? Everything else in my code works. It's just the solver/recursion it that is not.
bo
boourn
f nt j=0; j < 9; j++)
rowc c=0;
8) //if row is past 8 then the board is done
return true;
for (int < 10; i++)
{
nextr r; //save next row and col
next;
tcol++; /ncrement next col and row
(nextcol >8) {
nextcol =0;
nx
if(ncol==0 && nextrow ==9)
r(0, 0
}
As of your comment reply, Yes:
Code it properly.
Use methods as they should be used and name them properly.
Have InitilalizeBoard fill all zeros.
Have SetBoard put the start values on the board.
Have SolveBoard try to solve it.
It's a good programming habit to have each method do 1 thing, and make it's name clear.
Having said that, I did something similar a couple of years ago. It's much easier, faster, and takes less code to solve the sudoku with brute force approach using for/while loops, than doing it with recursion, or even coding it to be efficient and try to solve it like a human would (remove options that are obviously wrong and so on).
So, depending on your end result, you might want to code it appropriately ... (I did it to refresh my C++, so didn't care doing it the hard, long way first, and then doing it the short way).
The solver function you provided actually views the whole array, and - provided the other functions used in the code work correctly - should actually solve the puzzle. If you substitute cout << " TRUE TRUE "<<endl; for cout << "["<<r<<"]["<<c<<"]: "<<i<<endl;, you'll notice all indexes are checked.
So the problem must be in either one of the 3 functions you didn't provide code for: row_valid, col_valid or panel_valid.
Note: I don't think using recursion in this particular problem is a good idea. You probably should just do it using a for to check and solve the board. That would be both faster and easier.
Edit after first post was updated
The row_valid and col_valid functions aren't quite valid. You can't check the c !=i part, because it'll make all checks false. Change the if statements to this:
if (v == rowcol[i][c] && v!=0)
and
if (v == rowcol[r][j] && v!=0)
also you need to change the solver a bit:
bool sudoku :: solver(int r, int c) {
while( r < 9 && rowcol[r][c] !=0) {
c++;
if ( c>8) {
c=0;
r++;
}
if (r > 8) {
return true;
}
}
for (int i=1; i < 10; i++)
{
int nextrow, nextcol;
if (row_valid (r, c, i)&& col_valid(r, c, i)&& panel_valid(r,c, i)) {
rowcol[r][c]=i;
nextrow=r; //save next row and col
nextcol=c;
nextcol++; //increment next col and row
if (nextcol >8) {
nextcol =0;
nextrow++;
}
if(nextcol==0 && nextrow ==9) {
return true; //then it's done
}
if (solver(nextrow,nextcol)) {
return true;
}
else{
rowcol[r][c]=0;
}
}
}
return false;
}
This seems to work for me and give me an output of:
1 2 3 4 5 6 7 8 9
4 5 6 7 8 9 1 2 3
7 8 9 1 2 3 4 5 6
2 1 4 3 6 5 8 9 7
3 6 5 8 9 7 2 1 4
8 9 7 2 1 4 3 6 5
5 3 1 6 4 2 9 7 8
6 4 2 9 7 8 5 3 1
9 7 8 5 3 1 6 4 2