How to set up a partition without sorting? - c++

I am having trouble creating a partition for set inputs. I have tried two things, the first is commented out and it is just some basic pseudo code for a partition algorithm and the second is what I interpreted from the class notes. First off the main function is fine, that was given to us. I only need to finish coding the partition function. Everything commented in the partition function is my first attempt, everything not commented is my second attempt.
Here is some inputs we are supposed to test along with the proper results:
1 2 3 4 5 6 7  pivot is 4; elements less than pivot are in the left section
8 7 6 5 4 3 2 1  pivot is 5; elements less than pivot are in the left section
5 1 4 3 6 7 8 2  pivot is 3; elements less than pivot are in the left section
4 3 1 2 7 5  pivot is 1; the left section is empty
2 6 8 4 1 7  pivot is 8; the right section is empty
int partition(int a[], int first, int last) {
/* int pivot = a[last / 2];
//cout << pivot << endl;
int i = (first - 1);
for (int j = first; j <= last; j++) {
if (a[j] < pivot) {
i++;
//cout << pivot << endl << i << endl << j << endl;
swap(a[i], a[j]);
}
}
cout << pivot << endl << i << endl << first << endl << last << endl;
//swap(a[i + 1], a[last]);
return (i + 1);
}*/
swap(a[first],a[(first+last)/2]);
int pivot = a[first];
int i = a[first];
int j = a[last];
while (i <= j)
{
if (pivot > a[i])
{i++;}
if (pivot < a[j])
{j--;}
if (i <= j)
{swap(a[i],a[j]);}
}
swap(pivot, a[j]);
return i;
}
int main()
{
int x; // number of elements
int nums[10];
cout << "How many elements would you like to enter into the array? (must
be less than 10): ";
cin >> x;
cout << "Enter the elements one per line" << endl;
for (int i = 0; i < x; i++)
{ cin >> nums[i]; }
int pivot_index = partition(nums, 0, x-1);
cout << "The array was partitioned" << endl;
// display up to the pivot without endl
for (int i = 0; i < pivot_index; i++)
cout << nums[i] << " ";
// display the pivot
cout << "| " << nums[pivot_index] << " | " ;
// display from the pivot without endl
for (int i = pivot_index+1; i < x; i++)
cout << nums[i] << " ";
cout << endl;
}

Related

C++ How to the total number of duplicate elements in the array?

I am trying to finish my homework, but I have encountered some problems in the item of Duplicate Elements. I have tried to find out where the problem is, but I cannot find it. My code works fine when the sequence is small, but it becomes problematic when the sequence is large.
In this sequence, I expect to get the number in the picture, but I always get the number in the second picture. As you can see, there is always a problem in this item in the duplicate element.
#include <iostream>
using namespace std;
int main()
{
int count = 0;
int arrayA[25];
int arrayB[25];
int min,max;
int num;
int i = 0;
int n = 0;
int temp = 0;
int sum = 0;
//Input
cout << "Input the number of elements to store in the array: ";
cin >> n;
cout << n << endl;
cout << "Input "<< n <<" integers:" << endl;
//Store arrayA
if(count < n){
for(i = 0; i < n; i++){
cin >> num;
cout << "integer - " << count;
cout << " : " << num <<endl;
arrayA[count] = num;
count++;
}
}
//store arrayB
for(i = 0;i < count; i++){
arrayB[i] = arrayA[count - i - 1];
}
//Forwards Array
cout << "The values stored into the array are :" << endl;
for(i = 0;i < count; i++){
cout << arrayA[i] << " ";
}
cout << endl;
//Backwards Array
cout << "The values stored into the array in reverse are :" << endl;
for(i = 0; i < count; i++){
cout << arrayB[i] <<" ";
}
cout << endl;
//Sum
for(i = 0; i < count; i++){
sum += arrayA[i];
}
//Max & Min
for(i = 0; i < count;i++){
if(max < arrayA[i]){
max = arrayA[i];
}
}
for(i = 0; i < count; i++){
if(min > arrayA[i]){
min = arrayA[i];
}
if(arrayA[i]== 0){
min = 0;
break;
}
}
//Duplicate elements
count = 0;
for(i = 0; i < n; i++){
for(temp = i + 1; temp < n; temp++){
if(arrayA[i] == arrayA[temp] ){
count++;
break;
}
}
}
cout << "The sum of all elements of the array is ";
cout << " " << sum << endl;
cout << "The total number of duplicate elements in the array is ";
cout << count << endl;
cout << "The maximum and minimum element in the array are ";
cout << min << " , " << max;
return 0;
}
You should try debugging more by printing, to know what is happening. You are not really taking into account that a number can be repeated several times and depending on the spread, it will count them several times. And here is why:
//Duplicate elements
count = 0;
for(i = 0; i < n; i++){
for(temp = i + 1; temp < n; temp++){
//cout << "Comparing "<< arrayA[i] << " to "<< arrayA[temp]<<endl;
if(arrayA[i] == arrayA[temp] ){
cout << "ITEM DUPLICATED at i , "<<i<< " item "<< arrayA[i]<< " and temp "<< temp<< " item "<< arrayA[temp] << endl;
count++;
break;
}
}
}
ITEM DUPLICATED at i , 0 item 4 and temp 7 item 4
ITEM DUPLICATED at i , 2 item -2 and temp 10 item -2
ITEM DUPLICATED at i , 4 item -3 and temp 14 item -3
ITEM DUPLICATED at i , 5 item 3 and temp 11 item 3
ITEM DUPLICATED at i , 7 item 4 and temp 8 item 4
ITEM DUPLICATED at i , 12 item -1 and temp 13 item -1
As you can see, there is a 4 - 4 twice. It can be seen quite easily if you do it in paper (although you shouldn't)
4A -4B -2C 1D -3E 3F 5G 4H 4I 0J -2K 3L -1M -1N -3O
4a -4b -2c 1d -3e 3f 5g 4h 4i 0j -2k 3l -1m -1n -3o
Connections made:
4A 4h
-2C -2k
-3E -3o
3F 3l
4H 4i
So the code technically is doing what you are asking it to do. if you want to count UNIQUELY (if a 4 appears 15 times, count it as only that 4 is repeated), you should be checking if the number has already been checked. Using a vector or map (dictionaries in C++) can allow you to do that! Or lists with lists (the element, and the number of occurences)

How to call a function to search an element an a 2D array?

I'm trying to get my homework done, but there is something is going wrong.
If a 2D array was in the main function, and I want to call a function, which its task is searching for an element in the 2D array, which the user enters the wanted element in the main function. If the wanted element was found, call a function to find its factorial then print the result in the main function, otherwise, call another function to show that the wanted element was not found.
I've tried the lines of code using Visual Studio 2019 as well as Dev C++.
My program does about 13 tasks which I organized them in a Switch Statement,
and the case of doing that task is Case number 9.
But once I enter the element I want to search in the console.
if the element existed in the array, the output always shows up like this:
"
Number 3 Found at position: 4
Factorial of 3 is: 6
3
"
whether the user entered 3 or else number.
Even if it was not found, the output is the same.
#include <iostream>
using namespace std;
// declaring a function to search within B1 array.
int search_B1(int[][3], int, int);
// declaring a function to find the fatorial of the found element.
int fact_num(int);
// declaring a function to print out a searching error.
void search_error();
// This is the main function. Program execution begins and ends here.
int main()
{
int B1[3][3], i, j;
cout << " - Please enter the elements of B1 array: \n";
for (i = 1; i <= 3; i++)
{
for (j = 1; j <= 3; j++)
{
cout << "B1[" << i << "]" << "[" << j << "] = ";
cin >> B1[i][j];
}
}
...
...
...
case 9:
{
int num;
cout << endl << " Enter the element to search in B1 array: ";
cin >> num;
cout << endl << search_B1(B1, 3, num) << endl;
break;
}
}
/**********************************************************************/
// This function is called when user inserts '9'
int search_B1(int B1[][3], int num , int)
{
int i, j, flag = 0;
for (i = 1; i <= 3; i++)
{
for (j = 1; j <= 3; j++)
{
if (num == B1[i][j])
{
flag = 1;
cout << " Number " << num << " Found at position: " << j + 1 << endl;
fact_num(num);
break;
}
}
}
if (flag == 0)
{
search_error();
}
return num;
}
/**********************************************************************/
// This function relates to ' search_B1 ' function.
int fact_num(int num)
{
int fact = 1, f;
for (f = 1; f <= num; f++)
{
fact *= f;
}
cout << " Factorial of " << num << " is: " << fact;
return fact;
}
/**********************************************************************/
// This function relates to ' search_B1 ' function.
void search_error()
{
cout << " The wanted number was not Found in the array!";
}
/**********************************************************************/
I expected the output of searching will be like this:
Example:
If the user entered the elements of the array as '1 2 3 4 5 6 7 8 9' and searched about the element '9'
IF THE WANTED ELEMENTS WAS FOUND:
the output will be :
"Number 9 Found at position: 4
Factorial of 9 is: 362880"
IF THE WANTED ELEMENTS WAS NOT FOUND:
the output will be :
"The wanted number was not Found in the array!"
You have undefined behaviour filling and searching the array
for (i = 1; i <= 3; i++) // B[3][j] is never an element
{
for (j = 1; j <= 3; j++) // B[i][3] is never an element
Array indices start from 0. If you want to display indices from 1, do arithmetic in the output
for (i = 0; i < 3; i++)
{
for (j = 0; j < 3; j++)
{
std::cout << "B1[" << (i + 1) << "]" << "[" << (j + 1) << "] = ";
std::cin >> B1[i][j];
}
}

How to fix addition/multiplication table errors?

I am having troubles with some of the inputs for my addition/multiplication table, and am hoping to find some help towards fixing this. I will begin by posting what I have for the program.
The code is as follows :
#include <iostream>
using namespace std;
void die() {
cout << "BAD INPUT!" << endl;
exit(1);
}
int main() {
const int ADD = 1;
const int MULTIPLY = 2;
const int MAX_SIZE = 20;
int choice = 0, min = 0, max = 0;
cout << "Choose:\n";
cout << "1. Addition Table\n";
cout << "2. Times Table\n";
cin >> choice;
if (!cin) die();
if (choice != ADD and choice != MULTIPLY) die();
cout << "Please enter the smallest number on the table:\n";
cin >> min;
if (!cin) die();
cout << "Please enter the largest number on the table:\n";
cin >> max;
if (!cin) die();
if (min > max) die();
if (max - min >= MAX_SIZE) die();
if (choice == ADD) {
for (int i = 0; i <= max; i++) {
if (i == 0)
cout << '+';
else
cout << i;
cout << '\t';
for (int j = min; j <= max; j++) {
cout << i + j << '\t';
}
cout << '\n';
}
}
if (choice == MULTIPLY) {
for (int i = min; i <= max; i++) {
if (i == min) {
cout << 'X';
else
cout << i;
cout << '\t';
for (int j = min; j <= max; j++) {
cout << i * j << '\t';
}
cout << '\n';
}
}
}
Now, here are the mistakes that I am getting from this code that I cannot seem to resolve. First, when doing the MUlTIPLY table with min = 1, max = 1, I am getting:
X 1
when I should be getting (I believe)
X 1
1 1
Secondly, while doing the MULTIPLY table with min = 1, max = 12, I am getting:
X 1 2 3 4 ... 12
2 2 4 6 8 ... 24
3 3 6 9 12 ... 36
when I should be getting
X 1 2 3 4 ... 12
1 1 2 3 4 ... 12
2 2 4 6 8 ... 24
3 3 6 9 12 ... 36
And finally, when using the ADD table with min = 21, max = 40, I cannot post all of the code since it is such a mess, but basically the columns/rows are as follows:
+ 21 22 23 24 25 ...
5
1
6
2
7
3
8
When obviously, the code should output the rows and columns to be 21 - 40 evenly. As you can see in the last example, my rows are outputting properly, but somehow my columns are a complete, garbled mess.
I have been sitting and staring at this code for awhile, and can't seem to fix these issues at hand. Can anyone help lead me in the right direction? I really appreciate any help and hints :)
Check this out. Might not be fully optimized, but works
if (choice == ADD) {
cout << '+';
for (int i = min; i <= max; i++) {
cout << '\t' << i;
}
for (int i = min; i <= max; i++) {
cout << '\n' << i << '\t';
for (int j = min; j <= max; j++) {
cout << i + j << '\t';
}
}
}
if (choice == MULTIPLY) {
cout << 'X';
for (int i = min; i <= max; i++) {
cout << '\t' << i;
}
for (int i = min; i <= max; i++) {
cout << '\n' << i << '\t';
for (int j = min; j <= max; j++) {
cout << i * j << '\t';
}
}
}
See output here.
#include <iostream>
#include <iomanip>
#include <cstdio>
void die()
{
std::cout << "BAD INPUT!" << "\n";
exit(1);
}
int main() {
const int ADD = 1;
const int MULTIPLY = 2;
const int MAX_SIZE = 20;
int choice = 0, min = 0, max = 0;
std::cout << "Choose:\n";
std::cout << "1. Addition Table\n";
std::cout << "2. Times Table\n";
std::cin >> choice;
if (!std::cin) die();
if (choice != ADD and choice != MULTIPLY) die();
std::cout << "Please enter the smallest number on the table:\n";
std::cin >> min;
if (!std::cin) die();
std::cout << "Please enter the largest number on the table:\n";
std::cin >> max;
if (!std::cin) die();
if (min > max) die();
if (max - min >= MAX_SIZE) die();
if (choice == ADD) {
for (int i = 0; i <= max; i++) {
if (i == 0)
printf(" +");
else
printf("%3d", i);
printf(" ");
for (int j = min; j <= max; j++) {
printf("%3d ", i + j);
}
printf("\n");
}
}
if (choice == MULTIPLY) {
/* for printing header of the multiplication table */
std::cout << "X\t";
for (int j = min; j <= max; j++) {
std::cout << min * j << "\t";
}
std::cout << "\n";
/* for printing rest of the table */
for (int i = min; i <= max; i++) {
std::cout << i << "\t";
for (int j = min; j <= max; j++) {
std::cout << i * j << '\t';
}
std::cout << '\n';
}
}
}
The crucial mistake in your code for multiplication was that, you were trying to print (max - min + 1) + 1 rows in total, the extra +1 for the header. While your code was printing the first row as header and then starting directly with the second row.
Your code for addition table was correct, but 21 to 40 with tab character in between was too taking too much space for a typical laptop screen, not to say the output won't be pretty.
On my system, the output of tput lines and tput cols was 38 and 144 resp.
which wasn't sufficient for your code.
you can format the output with printf using printf fixed width output.
Considering you are not much familiar with C++, I would like to state that
using the std namespace as default namespace will work for this program, but when you working with larger projects, you should always prefix it.
I haven't enough reputation to add comment
if I were, I was commenting these lines
if (i == min) {
cout << 'X';
else
cout << i;
cout << '\t';

Multiplying elements in 2d array

I'm having a problem with the last row of my program. I can't figure out how to multiply the last row by the first row in my program. The multiplication table
works by multiplying the first row by the second, second by third, and so on.
int main() {
int temp;
const int row = 10;
const int col = 5;
int arr[row][col];
int arr2[10][5];
srand(((unsigned)time(0)));
cout << "Original" << endl;
for (int i = 0; i<10; i++) {
for (int j = 0; j<5; j++) {
temp = 1 + rand() % 99;
arr[i][j] = temp;
int arr2 = arr[i][j];
cout << setw(4) << arr2<< setw(5) << " | ";
}
cout << endl;
}
cout << "\n\nMultiplied rows" << endl;
for (int i = 0; i<row; i++) {
for (int j = 0; j < col; j++) {
if (i < 9)
arr[i][j] *= arr[i + 1][j];
else if (i == 9)
cout << setw(4) << arr[i][j]<< setw(5) << " | ";
}
cout << endl;
}
return 0;
}
(it's the last else statement I'm having a problem with)
i tried arr[i][j]=arr[1][i]*arr[9][j]
but that didn't work
First, the answer to your question.
You cant really multiply the last row with the first one because you overwrote it already when arr[i][j] *= arr[i + 1][j]; line executed for i = 0 and j = 0 to 9
The naive solution would be to either store the multiplied numbers in a new array, or don't overwrite the old array and just print the computed values.
Even with that, you will have to make other fixes but I am not really going to do your homework for you.
Just FYI, if you are handing this to an instructor they will call out a number of issues, like the fact that you have const int row and col defined but you only use them once .You should just use those variables; so instead of typing things like 10 , 5 and 9 you should type row, col , row -1.
Also the first arr2 variable is unused and the one in the loop could just as easily not be there and your code would be cout << setw(4) << arr[i][j]<< setw(5) << " | ";
I could go on but I will leave you to find the rest...
Good luck.

How to count how many times each number has been encountered?

I am trying to write a program to count each number the program has encountered. by putting M as an input for the number of the array elements and Max is for the maximum amount of number like you shouldn't exceed this number when writing an input in the M[i]. for some reason the program works just fine when I enter a small input like
Data input:
10 3
1 2 3 2 3 1 1 1 1 3
Answer:
5 2 3
But when I put a big input like 364 for array elements and 15 for example for max. the output doesn't work as expected and I can't find a reason for that!
#include "stdafx.h"
#include <iostream>
#include<fstream>
#include<string>
#include <stdio.h>
#include<conio.h>
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int checker[1000];
int element_cntr = 0;
int cntr = 0;
int n = 0;
void main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue>> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
checker[i]= M[i] ;
element_cntr++;
if (M[i] > Max)
{
cout << "the element number " << element_cntr << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (M[n] == checker[j])
{
cntr+=1;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
n++;
}
}
You have general algorithm problem and several code issues which make code hardly maintainable, non-readable and confusing. That's why you don't understand why it is not working.
Let's review it step by step.
The actual reason of incorrect output is that you only iterate through the first Max items of array when you need to iterate through the first Max integers. For example, let we have the input:
7 3
1 1 1 1 1 2 3
While the correct answer is: 5 1 1, your program will output 5 5 5, because in output loop it will iterate through the first three items and make output for them:
for (int i = 0; i < Max; i++)
for (int j = 0; j < ArrayValue; j++)
if (M[n] == checker[j]) // M[0] is 1, M[1] is 1 and M[2] is 1
It will output answers for first three items of initial array. In your example, it worked fine because the first three items were 1 2 3.
In order to make it work, you need to change your condition to
if (n == checker[j]) // oh, why do you need variable "n"? you have an "i" loop!
{
cntr += 1;
}
It will work, but both your code and algorithm are absolutely incorrect...
Not that proper solution
You have an unnecessary variable element_cntr - loop variable i will provide the same values. You are duplicating it's value.
Also, in your output loop you create a variable n while you have a loop variable i which does the same. You can safely remove variable n and replace if (M[n] == checker[j]) to if (M[i] == checker[j]).
Moreover, your checker array is a full copy if variable M. Why do you like to duplicate all the values? :)
Your code should look, at least, like this:
using namespace std;
int ArrayValue;
int Max;
int M[1000];
int cntr = 0;
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> ArrayValue >> Max;
for (int i = 0; i < ArrayValue; i++)
{
cin >> M[i];
if (M[i] > Max)
{
cout << "the element number " << i << " is bigger than " << Max << endl;
}
}
for (int i = 0; i < Max; i++)
{
cntr = 0;
for (int j = 0; j < ArrayValue; j++)
{
if (i == M[j])
{
cntr ++;
}
}
if (cntr != 0)
{
cout << cntr << " ";
}
}
return 0;
}
Proper solution
Why do you need a nested loop at all? You take O(n*m) operations to count the occurences of items. It can be easily counted with O(n) operations.
Just count them while reading:
using namespace std;
int arraySize;
int maxValue;
int counts[1000];
int main()
{
cout << "Enter the lenght of the Elements, followed by the maximum number: " << endl;
cin >> arraySize >> maxValue;
int lastReadValue;
for (int i = 0; i < arraySize; i++)
{
cin >> lastReadValue;
if (lastReadValue > maxValue)
cout << "Number " << i << " is bigger than maxValue! Skipping it..." << endl;
else
counts[lastReadValue]++; // read and increase the occurence count
}
for (int i = 0; i <= maxValue; i++)
{
if (counts[i] > 0)
cout << i << " occurences: " << counts[i] << endl; // output existent numbers
}
return 0;
}