To input in boolean array vertically, Question given on the post - c++

the Question was
Q.You are given an array of n elements. Each element depicts the height of a vertical bar.
For example, if you take the input array as [6,2,1,3] then the output should be.
what i though was
take value from user as a array
find the max value in that array
create a 2d boolean array with height as max value and width as array size of the user input array.
fill the boolean array vertically instead of horizontaly (methord how i did it is in the code below).
print the boolean array.
CODE:
#include <iostream>
using namespace std;
int main()
{
int n, i, j;
cout << "enter the size of array: ";
cin >> n;
int arr[n];
//INPUTING IN ARRAY!
for (i = 0; i < n; i++) {
cin >> arr[i];
}
//Calculating max-element
int max = arr[0];
for (i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
}
}
//creating a boolean array with height - max , width - n
bool new_arr[max][n];
//varables to input in the array vertically.
int k = 0, Q = 0;
for (i = 0; i < n; i++) {
for (j = max; j > 0; j--) {
Q = max - j; //to input in the array vertically, i.e at i =0 ,Q =0,1,2,3,4,5.
if (arr[i] >= j) {
new_arr[k][Q] = 1;
}
else {
new_arr[k][Q] = 0;
}
}
k++;
}
//printing the boolean array
cout << "FINAL ARRAY :" << endl;
for (i = 0; i < max; i++) {
for (j = 0; j < n; j++) {
cout << new_arr[i][j] << "\t";
}
cout << endl;
}
return 0;
}
I know there other far better methods but my mind is taken aback by this thought of doing
this question by this way only, I have tried another way and was successful but I am currently failing to do this question by this method(which my mind though of), please help.

Related

How to get a range of elements in an array C++

I need to calculate the sum of negative elements of an array located between the largest and the smallest elements. Here's the code I've got so far:
#include <iostream>
using namespace std;
int main() {
int i = 0;
int arrSize = 0;
cout << "Enter an array size" << endl;
cin >> arrSize;
if (arrSize <= 0) {
cerr << "Entered number is negative or 0" << endl;
return 0;
} // check if arrSize is 0 or negative, print error if so
double* arr = new double [arrSize]; //declare array
for (i = 0; i < arrSize; i++) {
cout << "Enter array element " << i+1 << endl;
cin >> arr[i];
} // get elements of array
int max = arr[0];
for (int i = 1; i < arrSize; i++) {
if (max < arr[i])
max = arr[i];
} //find max value of array
int min = arr[0];
for (int i = 1; i < arrSize; i++) {
if (min > arr[i])
min = arr[i];
} //find min value of array
How would I go about finding the positions of max and min elements and getting the range in between them?

Push to vector only one element, without repeating

I have a code where i should introduce 3 numbers and an multi-dimensional array. I should print all numbers from array that are divisors with 3 numbers from start..
Here's my code:
#include <vector>
#include <iostream>
using namespace std;
int main() {
int r, p, k, nr, n, m, counter=0, temp;
vector <int> numbers;
cout << "Enter value of r, p, k: ";
cin >> r >> p >> k;
cout << "Enter the number of rows and columns: ";
cin >> n >> m;
int T[n][m];
cout << "Enter values: ";
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
cin >> T[i][j];
}
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
for(int a = 0; a < 1; a++) {
numbers.push_back(T[i][j]);
counter++;
}
}
}
for(int f = 0; f < counter; f++) {
if(r%numbers[f]==0 && p%numbers[f]==0 && k%numbers[f]==0) {
cout << numbers[f] << ' ';
}
}
return 0;
}
So, my question is.. how to push in vector numbers that repeats only 1 time.. I mean if in array are 2 the same number, dont print both of them but just one of them.
Thanks in advance.
Use a set: http://en.cppreference.com/w/cpp/container/set
A set does not allow duplicates. For example, if you insert the number 5 more than once, there will still only be one 5 in the set.
First #include<set>.
Then replace vector <int> numbers; with set<int> numbers;
Then replace
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
for(int a = 0; a < 1; a++) {
numbers.push_back(T[i][j]);
counter++;
}
}
}
with
for(int i = 0; i < n; i++)
for(int j = 0; j < m; j++)
numbers.insert(T[i][j]);
Then replace
for(int f = 0; f < counter; f++) {
if(r%numbers[f]==0 && p%numbers[f]==0 && k%numbers[f]==0) {
cout << numbers[f] << ' ';
}
}
with
for (auto i = numbers.cbegin(); i != numbers.cend(); ++i)
if(r % *i == 0 && p % *i == 0 && k % *i == 0)
cout << *i << ' ';
That should do it. You can eliminate the counter variable from the program because numbers.size() gives you the number of objects in the set. Also, your temp variable is not used, so eliminate that as well. Also, note that set is an ordered container, so printing it like this will print the numbers in ascending order.
(Also note that the length of an array such as int arr[3]; must be known at compile time to be strictly valid C++. Here 3 is a literal and so is known at compile time. Asking the user to input the length of the array means that it is not known at compile time.)
After you fill your vector, you can first sort all elements in it and than call std::unique, to remove all duplicates from it.
Try to look references for std::unique and std::sort

Finalize the magic square generator

This code that runs only for odd N. The problem is that there are no ideas how to add support for even values N
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
setlocale(0, "");
int n;
cout << "Enter the size of the magic square - ";
cin >> n;
int **matrix = new int *[n];
for (int i = 0; i < n; ++i)
{
matrix[i] = new int[n];
}
int nsqr = n * n;
int i = 0, j = n / 2;
for (int k = 1; k <= nsqr; ++k)
{
matrix[i][j] = k;
i--;
j++;
if (k % n == 0)
{
i += 2;
--j;
}
else
{
if (j == n)
{
j -= n;
}
else if (i < 0)
{
i += n;
}
}
}
cout << "\n\nMagic square size - " << n << "\n\n";
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << matrix[i][j] << "\t";
}
cout << endl;
}
for (i = 0; i < n; i++)
delete[] matrix[i];
delete[] matrix;
system("pause >> null");
return 0;
}
I would be grateful for tips on troubleshooting.
If i'm not mistaken, the problem is in this line:
int i = 0, j = n / 2;
But i don't know how to change the code to support even values
I would assume that you meant normal magic square (where the number are restricted to 1,2..n^2)
First of all, it's impposible to construct such magic square for n=2.
2nd, you would need an whole new algorithm for it, which is much more complicated. The problem (constructing magic square for any even number) is solved in this paper and while there isn't any psaudo code there, the implementation from the explenation is quite straightforward (long one though).
the problem is here:
i = 0;
int j = n / 2;
for (int k = 1; k <= nsqr; ++k)
{
matrix[i][j] = k;
i--;
}
look how you decrement i inside the loop and making it as an index of the array so:
matrix[-3][j] = k; // will be in your code
you are messing deliberately with the indexes of the array
I found answer on my question in this artcile
I made full revision my algorithm based on this article. Later posted listing the resulting program

C++ Bubble Sort Using Swap Function and Pointers

I'm having problems figuring out where my bubble sort code went wrong. I'm almost positive it's in the sorting algorithm. Here is what I need my code to accomplish:
-Initialize an array a fill it with random numbers (I use getNumbers() to accomplish this)
-Compare the first element with all later elements. If the first element is larger, swap them.
-Compare the second element with all later elements one by one. If the second element is larger, swap them.
-Continue comparing and swap operations until the second to last element.
-Print out the sorted array
And here's my code:
#include <iostream>
#include <cstdlib>
using namespace std;
void swap(int *, int *);
int *getNumbers(int);
int main()
{
//Get the size of the array from keyboard
int arraySize;
cout << "How many integers would you like to declare: ";
cin >> arraySize;
//Initialize array
int *array;
array = getNumbers(arraySize); //getNumbers should return a pointer
//Print out original array
cout << "Original array" << endl;
for(int count = 0; count < arraySize; count++)
{
cout << *(array + count) << " ";
}
//Sort array using the swap function
//Have a for loop to swap numbers one by one from min to max
//Compare values using a second for loop
//Swap values if former value is larger
//swap(&array[i],&array[j]);
for(int i = 0; i < arraySize; i++)
{
for(int j = 0; j < (arraySize - 1); j++)
{
if(array[j] > array[j + 1])
{
swap(&array[i], &array[j]);
}
}
}
//Print out sorted array
cout << "\nSorted Array" << endl;
for(int count = 0; count < arraySize; count++)
{
cout << *(array + count) << " ";
}
return 0;
}
void swap(int *num1, int *num2)
{
//Keep record of original value of num1
int tempNum;
tempNum = *num1;
*num1 = *num2; //num1 value has been changed
*num2 = tempNum; //Fetch the original value of num1 and assign it to num2
}
int *getNumbers(int size)
{
int *array;
array = new int[size];
srand(time(0));
for(int i = 0; i < size; i++)
{
array[i] = rand() % 100;
}
return array;
}
Here is the correct code.
#include <iostream>
#include <cstdlib>
using namespace std;
void swap(int *, int *);
int *getNumbers(int);
int main() {
//Get the size of the array from keyboard
int arraySize;
cout << "How many integers would you like to declare: ";
cin >> arraySize;
//Initialize array
int *array;
array = getNumbers(arraySize); //getNumbers should return a pointer
//Print out original array
cout << "Original array" << endl;
for (int count = 0; count < arraySize; count++) {
cout << *(array + count) << " ";
}
//Sort array using the swap function
//Have a for loop to swap numbers one by one from min to max
//Compare values using a second for loop
//Swap values if former value is larger
//swap(&array[i],&array[j]);
for (int i = 0; i < arraySize; i++) {
for (int j = 0; j < (arraySize - 1); j++) {
if (array[j] > array[j + 1]) {
/*********** This line was changed ***********/
swap(&array[j+1], &array[j]); // You were earlier swapping ith and jth entries.
/*********************************************/
}
}
}
//Print out sorted array
cout << "\nSorted Array" << endl;
for (int count = 0; count < arraySize; count++) {
cout << *(array + count) << " ";
}
return 0;
}
void swap(int *num1, int *num2) {
//Keep record of original value of num1
int tempNum;
tempNum = *num1;
*num1 = *num2; //num1 value has been changed
*num2 = tempNum; //Fetch the original value of num1 and assign it to num2
}
int *getNumbers(int size) {
int *array;
array = new int[size];
srand(time(0));
for (int i = 0; i < size; i++) {
array[i] = rand() % 100;
}
return array;
}
You were swapping array[i] with array[j] in line 32. array[j] and array[j+1] should be swapped. Also, as pointed out by dd2, your loop bounds are not strict. The code would work correctly nonetheless but would take more steps. You can change the bound to j < (arraySize - i - 1)
Your loop bounds are not correct and swapping was wrong as well.
for(int i = 0; i < arraySize; i++)
{
for(int j = 0; j < (arraySize - i - 1); j++)
{
if(array[j] > array[j + 1])
{
swap(&array[j], &array[j+1]);
}
}
}

Replacing values in a 2D array

I have to create a program that allows a user to fill in a (partial) Latin Square of order 4. You can use 0's to represent empty cells. The user will give the number to place, the row and column. The number should only be placed if it does not violate the properties of a partial Latin square and it shouldn't rewrite numbers that have already been placed.
I have an matrix that is outputting all zeroes now. So next I have to replace each of these values by what the user is inputting. The problem is I don't know how to do this.
Here is my code:
#include <iostream>
using namespace std;
const int ORDER = 4;
void fill (int m[], int order);
void outputMatrix (int m[], int order);
void replaceValue (int m[], int order, int n, int row, int column);
int main(){
int matrix[ORDER];
int row;
int column;
int n;
fill (matrix, ORDER);
outputMatrix (matrix, ORDER);
do {
cout << "Enter the number to place, the row and the column, each seperated by a space: ";
cin >> n;
cin >> row;
cin >> column;
}while (n > 0 || n <= ORDER);
if (n <= 0 || n >= ORDER){
cout << "Thank you";
cout << endl;
}
return 0;
}
void fill (int m[], int order){
for (int i = 0; i < order*order; i++){
m[i] = 0;
}
}
void outputMatrix (int m[], int order){
int c = 0;
for (int i = 0; i < order*order; i++){
c++;
cout << m[i] << ' ';
if (c == order){
cout << endl;
c = 0;
}
}
cout << endl;
}
void replaceValue (int m[], int order, int n, int row, int column){
for (int i = 0; i < order; i++){
m[order] = m[row][column];
m[row][column] = n;
}
}
How do I replace values in a Matrix in C++?
If you have a matrix, matrix[row][col] = value; would do the trick. However, I see that you allocate a single array. Make sure you look at this.
EDIT:
I looked closer at you code and you are doing some things wrong.
First:
matrix[ORDER]
will create a single array of ORDER values. If you want and ORDER by ORDER matrix try:
matrix[ORDER][ORDER]
Second:
You are calling:
void fill (int m[], int order){
for (int i = 0; i < order*order; i++){
m[i] = 0;
}
}
with an of size 4 and order == 4. This will loop outside the array and give you problems.
Try something like:
matrix[ORDER][ORDER];
for (int row = 0; row != ORDER; ++row)
{
for (int col = 0; col != ORDER; ++col)
{
matrix[row][col] = 0;
}
}
Hope this helps.
You can't really write arr[i][j] if arr is defined as arr[]. There's no information about the length of the row (how many columns there are).
You could use arrays of type arr[][4], and write your functions like so:
// The & is to pass by reference.
void print(int (&arr)[][4], int length)
{
for(int i = 0; i < length; i++) {
for(int j = 0; j < 4; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
But in my opinion for a low-order multidimensional array like this one, using a typedef for a vector of vectors is the better option:
typedef vector<vector<int> > Matrix;
void print(Matrix& arr)
{
for(int i = 0; i < arr.size(); i++) {
for(int j = 0; j < arr[i].size(); j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
In either case, writing arr[i][j] = k will behave as you expect.
The easiest way to clear/zero your matrix is that:
memset( &matrix, 0, sizeof(matrix));
;-)