how to get the difference of two points in a 2D array - c++

#include <iostream>
using namespace std;
int main (int argc, char ** argv)
{
int c;
int distance=0;
int largestdistance=0;
int sum=0;
cin >> c;
int point[c][2];
for (int i=0; i<c; i++){
for (int j=0; j<2; j++){
cin >> point[i][j];
}
}
cout << point[2][0] << " ";
for (int i=0; i<c; i++){
for (int j=0; j<2; j++){
sum += abs(point[0][0]-point[1][0])+abs(point[0][1]-point[1][1]);
}
if (sum > largestdistance){
largestdistance=sum;
}
cout << '\n';
return 0;
}
}
This program prints out the value of the absolute value of the first row first number minus the second row first number added to the absolute value of the first row second number minus the second row second number. I was wondering that how do I make the program so that it automatically does the sum += abs(point[0][0]-point[1][0])+abs(point[0][1]-point[1][1]) for all point[][] all the way up to sum += abs(point[c-1][0]-point[c][0])+abs(point[c-1][1]-point[c][1]).

This would be a lot clearer if you introduced a point type:
struct Point {
int x, y;
};
int manhattan_dist(const Point& p, const Point& q) {
return abs(p.x - q.x) + abs(p.y - q.y);
}
Armed with that, it's a lot easier to loop:
int sum = 0;
for (int i = 0; i < c - 1; ++i) { // stop before c-1, so i and i+1 are valid
sum += manhattan_dist(points[i], points[i+1]);
}
Btw int point[c][2]; is non-standard code because c is not a compile-time constant. You need to dynamically allocate the array:
Point* points = new Point[c];
or, preferably:
std::vector<Point> points(c);

Related

How to correctly use pointers in code

For the following code, how can I find [A^-1] using pointers(equation for [A^-1]= 1/ det (A)? I am not sure whether pointers are used in the arithmetic or if they are used to call a value. Explaining what a pointer would be nice as I'm not exactly sure what they even do. I have most of the code written, except for this one part, so any help is much appreciated. Thanks in advance.
#include <iostream>
#include <cmath>
#include <string>
#include <fstream>
#include <ctime>
#include <cstdlib>
#include <bits/stdc++.h>
#define N 3
using namespace std;
template<class T>
void display(T A[N][N])
{
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
cout << A[i][j] << "\t\t";
cout << endl;
}
}
template<class T>
void display(T A[N])
{
for (int i=0; i<N; i++)
{
cout << A[i]<< "\n";
}
}
void getCofactor(int A[N][N], int temp[N][N], int p, int q, int n)
{
int i = 0, j = 0;
for (int row = 0; row < n; row++)
{
for (int col = 0; col < n; col++)
{
if (row != p && col != q)
{
temp[i][j++] = A[row][col];
if (j == n - 1)
{
j = 0;
i++;
}
}
}
}
}
int determinant(int A[N][N], int n)
{
int D = 0;
if (n == 1)
return A[0][0];
int temp[N][N];
int sign = 1;
for (int f = 0; f < n; f++)
{
getCofactor(A, temp, 0, f, n);
D += sign * A[0][f] * determinant(temp, n - 1);
sign = -sign;
}
return D;
}
void adjoint(int A[N][N],int adj[N][N])
{
if (N == 1)
{
adj[0][0] = 1;
return;
}
int sign = 1, temp[N][N];
for (int i=0; i<N; i++)
{
for (int j=0; j<N; j++)
{
getCofactor(A, temp, i, j, N);
sign = ((i+j)%2==0)? 1: -1;
adj[j][i] = (sign)*(determinant(temp, N-1));
}
}
}
bool inverse(int A[N][N]){
int det = determinant(A, N);
if (det == 0){
cout << "Singular matrix, can't find its inverse";
return false;
}
return true;
}
void computeInverse(int A[N][N], float inverse[N][N]){
int det = determinant(A, N);
int adj[N][N];
adjoint(A, adj);
for (int i=0; i<N; i++)
for (int j=0; j<N; j++)
inverse[i][j] = adj[i][j]/float(det);
cout<<"\nThe Inverse of the Matrix A is:"<<endl;
display(inverse);
}
int main()
{
system("cls");
int A[N][N] = {{-1, 4, -2}, {-3, -2, +1}, {+2, -5, +3}};
char X[N];
int B[N];
float inv[N][N];
cout<<"\nEnter a 3*3 Matrix A"<<endl;
for(int i=0;i<N;i++){
for(int j=0;j<N;j++){
cin>>A[i][j];
}
}
cout<<"\nEnter variables x, y, z for Matrix X"<<endl;
for(int i=0;i<N;i++){
cin>>X[i];
}
if (X[0] == 'x' && X[1] == 'y' && X[2] == 'z')
cout<<"\nMatrix X is Valid"<<endl;
else{
cout<<"\nMatrix X is Invalid"<<endl;
return -1;
}
cout<<"\nEnter values for Matrix B"<<endl;
for(int i=0; i<N; i++)
cin>>B[i];
cout<<"\nMatrix A is:------->\n";
display(A);
cout<<"\nMatrix X is:------->\n";
display(X);
cout<<"\nMatrix B is:------->\n";
display(B);
bool isInverseExist = inverse(A);
if (isInverseExist)
computeInverse(A, inv);
return 0;
}
Okay, Here is a simple pointer example using a char array. This can work with other data types as well. Don't remember where I read it; Think of a pointer as an empty bottle.
lets break this down in English first then I'll share a simple example that can be compiled. Imagine that you have 10 m&m's sitting in front of you on a table.
These m&m's represent a character array that we will call char mm[10]; Assume that this array is filled with chars that represent the color of all 10 of the m&m's
Now, we don't want to leave our candy's on the table all day so we will store all ten of the m&m's in a special jar specifically made for the m&m's. this jar will be called char* mm_ptr;
So now we are left with a table of m&m's and a jar sitting next to the pile. The next step is to fill the jar with the m&m's and you do it like this: mm_ptr = mm;
You now have a "jar full of m&m's". This allows you to access the m&m's directly from the jar!
Here is a Working example of of putting m&m's into a jar:
#include <iostream>
//using namespace std;
int main(){//The main function is our table
char mm[10]; //Our pile of m&m's
for(int i=0; i<10; i++){
if(i < 5){
mm[i] = 'b'; //Lets say that half of the m&m's are blue
}else{
mm[i] = 'r'; //and that the other half is red
}
}
char* mm_ptr; //This is our bottle that we will
//use to store our m&m's
mm_ptr = mm; //this is us storing the m&m's in the jar!
for(int i=0; i<10; i++){//Lets dump those candies back onto the table!
std::cout<<mm_ptr[i]<<std::endl;
}
return 0;
}
A correctly initialized pointer will work almost exactly like a normal array

adding arrays using malloc in c++

i dont know whats wrong with my code but im getting same value of "sum" on the
screen..
assume that m and n are entered equal ....enter image description here
#include<stdio.h>
#include<malloc.h>
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
int n,m;
int *ptr1, *ptr2, *sum;
cout<<" enter the size of 1st and 2nd array : "<<endl;
cin>>n>>m;
ptr1=(int*)malloc(n*sizeof(int));
ptr2=(int*)malloc(m*sizeof(int));
sum=(int*)malloc((n)*sizeof(int));
cout<<"enter 1st array element :";
for(int i=0;i<n;i++)
{
cin>>*(ptr1+i) ;
}
cout<<"enter 2st array element :";
for(int i=0;i<m;i++)
{
cin>>*(ptr2+i);
}
for(int j=0;j<m||j<n;j++)
{
*(sum+j) = (*(ptr1) + *(ptr2)) ;
}
cout<<" the sum is "<<endl;
for(int j=0;j<m||j<n;j++)
{
cout<<*(sum+j)<<endl;
}
}
First, the reason you get the same number springs from where you form the sums.
In this loop
for (int j = 0; j<m || j<n; j++)
{
*(sum + j) = (*(ptr1)+*(ptr2));
}
you find the sum of the contents of ptr1 and ptr2 over and over which never change - this is always the first two numbers.
So, we could iterate over the arrays by indexing in j along as follows
for (int j = 0; j<m || j<n; j++)
{
*(sum + j) = (*(ptr1 + j) + *(ptr2 + j));
}
BUT what happens if m!=n? You'll walk off the end of the array.
If you change the loop to
for (int j = 0; j<m && j<n; j++)
{
*(sum + j) = (*(ptr1 + j) + *(ptr2 + j));
}
then you find the sum for pairs of numbers up to the smaller of m and n.
You will have to do likewise with the display of the results
for (int j = 0; j<m && j<n; j++)
{
cout << *(sum + j) << endl;
}
However, I believe you wanted to either display n numbers, regardless of which is bigger, or perhaps assume a 0 if there is no element. Also, I notice you have malloced and not freed - perhaps using a C++ array rather than C-style arrays is better? I'll come to that in a moment.
Let's do the C appraoch and have a 0 if we go beyond the end of an array.
This will work, but can be tidied up - comments inline about some important things
#include<stdlib.h>
#include <algorithm> //for std::max
#include <iostream>
using namespace std;
int main()
{
int n, m;
int *ptr1, *ptr2, *sum;
cout << " enter the size of 1st and 2nd array : " << endl;
cin >> n >> m;
ptr1 = (int*)malloc(n * sizeof(int));
ptr2 = (int*)malloc(m * sizeof(int));
sum = (int*)malloc((std::max(n, m)) * sizeof(int));
// ^--- sum big enough for biggest "array"
// data entry as before - omitted for brevity
for (int j = 0; j<m || j<n; j++)
{
*(sum + j) = 0;
if (j < n)
*(sum + j) += *(ptr1 + j);
if (j < m)
*(sum + j) += *(ptr2 + j);
}
cout << " the sum is " << endl;
for (int j = 0; std::max(n, m); j++)//however big it is
{
cout << *(sum + j) << endl;
}
free(ptr1); //tidy up
free(ptr2);
free(sum);
}
I know you said you wanted to use malloc and perhaps this is a practise with pointers, but consider using C++ idioms (at least you won't forget to free things you have maoolced this way).
Let's nudge your code towards using a std::vector:
First the include and the input:
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n, m;
vector<int> data1, data2, sum;
cout << " enter the size of 1st and 2nd array : " << endl;
cin >> n >> m;
cout << "enter 1st array element :";
for (int i = 0; i<n; i++)
{
int number;
cin >> number;
data1.push_back(number); //there is a neater way, but start simple
}
cout << "enter 2st array element :";
for (int i = 0; i<m; i++)
{
int number;
cin >> number;
data2.push_back(number);
}
This post shows a way to neaten up the data entry. However, let's do something simple and get the sum:
for (int j = 0; j < std::max(m, n); j++)
{
int number = 0;
if (j < n)
number += data1[j];
if (j < m)
number += data2[j];
sum.push_back(number);
}
And now for a C++ way to do output
cout << " the sum is " << endl;
for (auto item : sum)
{
cout << item << '\n';
}
}
Finally, let's have a brief think about the sum.
If you now #include <iterator> you can use an algorithm to put your sum into sum
std::transform(data1.begin(), data1.end(),
data2.begin(), std::back_inserter(sum), std::plus<int>());
However, note this won't fill with zeros. You could either make the vectors the same size, filled with zeros first, or lookup/discover ways to zip vectors of different sizes. Or stick with ifs in a loop as I demonstrated above.
Avoid malloc in C++. Just saying.
I highly encourage you to use a modern cpp data structure like a vector for storing your data. Thus, you don't have to worry about malloc and can access them far more easyly.
But now to your question: Your summation for loop is broken. Use
for(int j=0;j<m||j<n;j++)
{
*(sum+j) = (*(ptr1+j) + *(ptr2+j)) ;
}
Best regrads, Georg

Frequency of Numbers in a 1D Array

its been 6 hours since I have been writing the code but to no avail, I don't no where I am making the mistake but I am making some. Its a frequency output program and output should be like this:
array[8] = {6,1,7,8,6,6,1,9}
Output:
6:3
1:2
7:1
8:1
9:1
But its repeating the same numbers in my code. Any help would be much appreciable.
int array[8] = {6,1,7,8,6,6,1,9};
int store[8];
int a =0;
int b =0;
int c=0;
int d = 0;
store[d] = array[b];
for (d = 0; d < 8; d++){
int count=0;
c = d;
b = d;
for (int e = 0; e < d; e++){
if (array[b] == store[e]){
store[d] = array[b];
b++;
e = 0;
}
else
{
store[d] = array[b];
break;
}
}
for ( int z = 0; z < 7; z++){
if (store[d] == array[z])
{
count++;
}
}
cout << store[d] << ":" << count << endl;
}
You may use a map first to store num->frequency and then a multimap to store freqeuncy => num.
Here is the working solution.
#include <map>
#include <algorithm>
#include <iostream>
int main()
{
int array[8] = {6,1,7,8,6,6,1,9};
// A map to store num => freq
std::map <int, int> freq;
// A map to store freq(can be duplicate) => num
std::multimap <int, int> freqCounts;
// Store num => frequency
for (int i = 0 ; i < 8; i++)
{
freq[array[i]] += 1;
}
// Now Store freq => num
for(auto const & iter : freq)
{
freqCounts.insert (std::pair<int,int>(iter.second, iter.first));
}
// Print in reverse order i.e. highest frequency first
for (std::multimap<int,int>::reverse_iterator rit=freqCounts.rbegin(); rit!=freqCounts.rend(); ++rit)
{
std::cout << rit->second << " : " << rit->first << '\n';
}
return 0;
}
You never seem to update the counters. Try this:
int array[8] = {6,1,7,8,6,6,1,9};
unsigned int store[10] = {}; // large enough to hold the largest array value,
// initialized to zero
for (int n : array) ++store[n]; // update counts
for (int i = 0; i != 10; ++i)
{
std::cout << "Frequency of int " << i << " is " << store[i] << "\n";
}
If the set of values that occur is sparse, or includes negatives, or simply does not fit into a dense range of integers nicely, you can replace unsigned int[10] with an associative container, e.g.:
std::map<int, unsigned int> store;
// algorithm as before
for (auto const & p : store)
{
std::cout << "Frequency of " << p.first << " is " << p.second << "\n";
}
I'm not sure what you are trying to do with the arrays. I have tried to follow the logic, but it's hard to see it with all the anonymous variable names. It seems like you are trying to look for duplicates earlier in the array, but the variable e never gets any other value than 0, so you will only be comparing with the first item in the array.
You can just look in the array itself for previous occurances, and once you know that the number is the first occurance, you only need to look for more occurances after it in the array:
int array[8] = {6,1,7,8,6,6,1,9};
for (int i = 0; i < 8; i++) {
// look to the left in the array if the number was used before
int found = 0;
for (int j = 0; j < i; j++) {
if (array[i] == array[j]) found++;
}
// go on if it's the first occurance
if (found == 0) {
// we know of one occurance
int count = 1;
// look to the right in the array for other occurances
for (int j = i + 1; j < 8; j++) {
if (array[i] == array[j]) count++;
}
cout << array[i] << ":" << count << endl;
}
}
I wanted to submit my solution which I think it´s a more easy one:
#include <iostream>
using namespace std;
int main() {
int n; //number of Elements in the vector
cin>>n;
int vec[n]; //vector with all elements
int v[n]; //vector with Elements without repetition
int c[n]; // vector which stores the frequency of each element
for(int i=0; i<n; i++)
cin>>vec[i];
int k=0; // number of Elements of the vector without Repetition, in the begining, it has 0 Elements
int j=0; //logic Counter, could be replaced with bool
for(int i=0; i<n; i++) {
for(int h=0; h<=k; h++) {
if(vec[i]==v[h]) {
c[h]++;
j=1;
break;
}
}
//if element i of the original vector is equal to element h of the second vector, then increment the frequency of this element
if(j==0) { //else if the element is not equal to any of the second vector, the Position of the 2nd vector is filled with the element, which in this case is the first of ist Kind.
v[k]=vec[i];
c[k]=1;
k++;
} //the number of Elements is increased by one to store another element;
else {
j=0;
}
}
cout<<endl<<endl;
for(int i=0; i<k; i++)
cout<<v[i]<<":"<<c[i]<<endl;
return 0;
}
#include<iostream>
#include<conio.h>
using namespace std;
main()
{ int count[10],key[10],n=10,m;
int i,j,k,temp;
cout<<"Enter The Size Of Array:-\n";
cin>>n;
int a[n];
cout<<"Enter The Elements in Array:-\n";
for(i=0; i<n; i++)
cin>>a[i];
for(i=0; i<n; i++)
for(j=0; j<n-1; j++)
{ if(a[j]>a[j+1])
{ temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
for(i=0; i<n; i++)
cout<<a[i]<<"\t";
for(i=0,k=0; i<n; k++)
{ count[k]=0;
key[k]=a[i];
for(j=i; j<n; j++)
{ if(a[i]==a[j])
count[k]++;
}
i=i+count[k];
}
for(i=0; i<k; i++)
cout<<endl<<key[i]<<" Occurred "<<count[i]<<" Times\n";
getch();
}
/**
* The methods counts the frequency of each element in an array.
*
* Approach: The method checks if the element is already present in the <strong>Map of frequency</strong>.
* If it is not present, add it to the map with the frequency 1 else put it in the map with
* an increment by one of it's existing frequency.
*
* #param arr list of elements
* #return frequency of each elements
*/
public static Map<Integer, Integer> countFrequency(int[] arr) {
Map<Integer, Integer> frequency= new HashMap<Integer, Integer>();
for(int i = 0; i < arr.length; i++) {
if(frequency.get(arr[i])==null) {
frequency.put(arr[i], 1);
}
else {
frequency.put(arr[i],frequency.get(arr[i])+1);
}
}
System.out.println("\nMap: "+frequency);
return frequency;
}

how print an array row with pointers

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
ifstream fin("C:\\Users\\rati\\Desktop\\iris_flower.txt");
float s=0;
int x,n=5,m=150,i,j;float d[5]={0};
float **iris;
float ss=n;
iris=new float *[n];
for(i=0;i<n;i++)
iris[i]=new float [m];
for(i=0;i<n;i++)
for(j=0;j<m;j++)
fin>> iris[i][j];
for(i=0;i<n;i++){
for(j=0;j<m;j++)
cout<<iris[i][j]<<" ";
cout<<endl;
}
for(j=0;j<m;j++){
for(i=0;i<n;i++)
s+=iris[i][j];
d[j]+=s/ss;
cout<<s<<endl;
}
system ("pause");
}
this is my full code. I want to print a row from 2d array with pointer(no loops).I hope you can write a fragment to add that it did what I want
You can modify the array with pointers but if you want to print the array, you have to use loops.
Check out this example:-
int main() {
int n = 3, m = 4, a[n][m], i, j, (* p)[m] = a;
for (i = 0; i < n; i++)
for (j = 0; j < m; j++)
a[i][j] = 1;
p++;
(*p)[2] = 9;
return 0;}
Here
p is a pointer to a 4-element int arrays (i.e. a pointer to pointer to int, where the first dimension is 4 and the second is unknown). When you increment p, it points to the next 4-element int array, i.e. the fifth int altogether. Then p is dereferenced with offset 2, which means that the seventh int changes, so you get
1 1 1 1
1 1 9 1
1 1 1 1
For converting integer array pointed by p to string, try this :-
string int_array_to_string(int *p, int size_of_array){
string returnstring = "";
for (int temp = 0; temp < size_of_array; temp++)
returnstring += itoa((* p)[temp]);
return returnstring;
}
You get the row array from here.
With array of ints it wont be so easy like array of chars.
int n=10, m=10;
int width, height;
char **tab = new char*[n];
for (int x = 0; x < n; x++) {
tab[x] = new char[m];
}
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
tab[i][j] = rand()%10 + '0';
for (int i=0; i<n; i++) { for(int j=0; j<n; j++) cout << tab[i][j]; cout << endl; }
cout << endl;
cout << tab[5];
ideone
/// edit ///
if u cant use loop and recursion u can do this
const int n=3;
float *k =new float [n];
k[0]=6.123;
k[1]=9.5345;
k[2]=1.32423;
int i=0;
label:
if(i<n){
cout << *(k+i) << " ";
i++;
goto label;
}

For loops and addition

So I'm trying to use a for loop to fill the array with the numbers 1-8. Then add:
1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + numb = x
And then save it to an variable called x. I've done filling the array, but I don't know how to calculate the summary of the array + the number you enter. Would appreciate some help a lot.
#include <iostream>
using namespace std;
int main()
{
int array[8];
int numb;
int x; // x = summary of array + numb;
cin >> numb; // insert an number
for (int i = 0; i <= 8; i++)
{
array[i]=i+1;
}
for (int i = 0; i < 8; i++)
{
cout << array[i] << " + ";
}
}
Change the last part to:
x = numb;
for (int i = 0; i < 8; i++)
{
x = x + array[i];
}
cout<<x<<endl;
Realistically though, if you wanted to add the first n whole numbers, there's a formula:
(n*(n+1))/2;
so your whole program would be:
#include <iostream>
using namespace std;
int main()
{
int n = 8;
int numb;
cin >> numb; // insert an number
int x = n*(n+1)/2+numb;
cout<<x<<endl;
}
For the initial loop, remove the =:
for (int i=0; i<8; i++) { array[i]=i+1; }
For adding all the elements of an array, then adding numb:
var x=0;
for (int i=0; i<8; i++) { x += array[i]; }
x+=numb;
Then you can cout you x variable.
Unless you're required to use for loops and arrays (e.g., this is homework), you might want to consider code more like:
std::vector<int> array(8);
// fill array:
std::iota(begin(array), end(array), 1);
int numb;
std::cin >> numb;
int total = std::accumulate(begin(array), end(array), numb);
std::cout << "Result: " << total;