I have to display the records based on the integer value in an array. For instance, if I have an array i.e.
2, 3, 5, 3, 6, 8, 10, 1, 9, 7
I would need to display 3 and 5 based on the integer 2. Then it should display 6,8 and 10 based on integer 3 and then 9 based on 1. So my display array would be:
3,5
6,8,10
9
So far, I haven't been able to form any algorithm/code.. How to proceed on this one?
tested it with your given array...
void display_records(std::vector<int> vi) {
int tmp = 0;
int index = 0;
for(int i=0;i<vi.size(); i++){
for(int j=1;j<=vi[i];j++){
index = i + j;
tmp = vi[index];
if((i+j) < vi.size()) { //to prevent it going out of range
std::cout << tmp << " " ;
}
}
i = i + vi[i];
std::cout << std::endl;
}
}
Try something like this: (i am not sure if i understood your question) (not tested)
void displayRecords(int* vect, int size, int val)
{
for(int i=0; i<size; i++)
{
if(vect[i]==val)
{
int tmp = val;
int j = i + 1;
while(tmp && j != size)
{
std::cout<<vect[j]<<" ";
j++;
tmp--;
}
break;
}
}
}
Related
I have tried this code that I found online and it worked, but I want it to print out which number makes magic square. In this case it is 83, so instead of cout<<"Magic Square", how do I change it to show 83 instead?
Thank you in advance.
# define my_sizeof(type) ((char *)(&type+1)-(char*)(&type))
using namespace std;
// Returns true if mat[][] is magic
// square, else returns false.
bool isMagicSquare(int mat[][3])
{
int n = my_sizeof(mat)/my_sizeof(mat[0]);
// calculate the sum of
// the prime diagonal
int i=0,j=0;
// sumd1 and sumd2 are the sum of the two diagonals
int sumd1 = 0, sumd2=0;
for (i = 0; i < n; i++)
{
// (i, i) is the diagonal from top-left -> bottom-right
// (i, n - i - 1) is the diagonal from top-right -> bottom-left
sumd1 += mat[i][i];
sumd2 += mat[i][n-1-i];
}
// if the two diagonal sums are unequal then it is not a magic square
if(sumd1!=sumd2)
return false;
// For sums of Rows
for (i = 0; i < n; i++) {
int rowSum = 0, colSum = 0;
for (j = 0; j < n; j++)
{
rowSum += mat[i][j];
colSum += mat[j][i];
}
if (rowSum != colSum || colSum != sumd1)
return false;
}
return true;
}
// driver program to
// test above function
int main()
{
int mat[3][3] = {{ 1, 5, 6 },
{ 8, 2, 7 },
{ 3, 4, 9 }};
if (isMagicSquare(mat))
cout << "Magic Square";
else
cout << "Not a magic Square";
return 0;
}
As per suggested, I have tried to change it to:
int main()
{
int mat[3][3] = {{ 1, 5, 6 },
{ 8, 2, 7 },
{ 3, 4, 9 }};
if (isMagicSquare(mat))
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
cout<< mat[i][j] << ' ';
}
cout<< endl;
}
}
else
cout << "Not a magic Square";
return 0;
}
But it showed the whole array instead of the correct index in the array. I am sorry, I am somewhat new at the whole thing.
The result is showing up as:
1 5 6
8 2 7
3 4 9
Did I changed it in the wrong place? Or is there any further reading that I should read. Any helps would be appreciate.
The result that I am expecting is
83
as it is the number in the index that is the magic number.
If the given square is a magic square, that means when isMagicSquare(mat) is true, then iterate through the given square and print each of the values.
To do that, you'll have to learn how to print a 2D array.
In your case, you can do like below:
if (isMagicSquare(mat))
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 3; j++)
{
cout<< mat[i][j] << ' ';
}
cout<< endl;
}
}
Please check the below resources to learn more about 2D array:
How to print 2D Arrays in C++
Two Dimensional Array in C++
Multidimensional Arrays in C / C++
I have a row of ten numbers for example:
5 5 6 7 5 9 4 2 2 7
Now I want a program that finds all duplicates and gives them out in the console like 3 times 5, 2 times 2, 2 times 7.
While I did code an algorithm that finds duplicates in a row of numbers I can't give them out in the console as described. My program will output:
3 times 5
2 times 5
2 times 7
2 times 2
How can I solve this problem?
#include <iostream>
using namespace std;
int main()
{
int arr[10];
int i,j;
int z = 1;
for(i = 0; i < 10; i++) {
cin >> arr[i];
}
for(i = 0; i < 10; i++){
for(j = i+1; j < 10; j++){
if(arr[i] == arr[j]){
z++;
}
}
if(z >= 2){
cout << z << " times " << arr[i] << endl;
z = 1;
}
}
return 0;
}
You can use the STL here (C++11):
int arr[10];
std::map<int, int> counters;
for (auto item : arr)
{
cin >> item;
++counters[item];
}
std::for_each(counters.begin(), counters.end(), [](const std::pair<int,int>& item)
{
if(item.second > 1) std::cout << item.second << " times " << item.first << std::endl;
});
You need to check that arr[i] is not already found before, like this for example:
if(z >= 2) {
int found_before = 0;
for(j = 0; j < i; ++j)
if(arr[i] == arr[j])
found_before = 1;
if(!found_before)
cout << z << " times " << arr[i] << endl;
z = 1;
}
which will print:
3 times 5
2 times 7
2 times 2
That way you don't print 5 again.
With your code it would print that it found 5 three times (for the first 5 in your array), and then when it would move to he second 5 in your array, it would forgot about the first 5 in your array, and report that it found 5 twice (itself and the 5th number of the array).
Why not use STL?
std::map<int, int> counter;
for (i = 0; i < 10; i++)
counter[arr[i]] ++;
for (i = 0; i < 10; i++) {
if (counter.count(arr[i]) > 0){
std::cout << counter[arr[i]] << " times "<< arr[i] << std::endl;
counter.erase(arr[i]);
}
}
std::map is a convenient tool for this job. You can easily count up occurrences of a specific number. After counting, you can print the count of each array element. With counter.erase, it's guaranteed that you won't print the same element for multiple times.
Why keeping your algorithm idea, I suggest to create sub method:
std::size_t count(const int* arr, std::size_t start, std::size_t end, int value)
{
std::size_t res = 0;
for (std::size_t i = start; i != end; ++i) {
if (arr[i] == value) {
++res;
}
}
return res;
}
then your fixed algorithm would be:
for (std::size_t i = 0; i != 10; ++i) {
if (count(arr, 0, i, arr[i]) != 0) {
continue; // Already visited
}
auto total = count(arr, i, 10, arr[i]);
if(total >= 2){
std::cout << z << " times " << arr[i] << std::endl;
}
}
An easy way is to make another array for it, especially if the numbers are not that big.
Lets say you have initialized your array like so: int nums[10] = { 5, 5, 6, 7, 5, 9, 4, 2, 2, 7 }
int result[max(nums)]; //Fill with zeroes, max(nums) is the highest number in the array
for(int i = 0; i < 10; i++) {
result[nums[i]]++;
}
for(int i = 0; i < max(nums); i++) {
if (result[i] > 1) cout << result[i];
}
Mind you this isn't optimized for memory. For larger number contents you might want to consider hashmaps.
If you don't need performance but rather compact code, then std::multiset with std::upper_bound is an alternative:
#include<set>
#include<iostream>
#include<algorithm>
int main(int a, char** b)
{
int array[] = {5, 5, 6, 7, 5, 9, 4, 2, 2, 7};
std::multiset<int> a(std::begin(array), std::end(array));
for(auto it = a.begin(); it != a.end(); it = std::upper_bound(a.begin(), a.end(), *it))
{
if(a.count(*it) > 1)
std::cout << *it << " times " << a.count(*it) << std::endl;
}
return 0;
}
I am trying to create a code where given an ordered array with numbers between 1 and 10, the code returns all of the values missing.
My code is as follows:
int missingArray [] = {1, 3, 4, 5, 7, 8};
for (int i = 0; i < 11; i++) {
if (missingArray[i] == i+1) {
cout << "Continue. \n";
}
if (missingArray[i] != i+1) {
cout << "The value of " << i+1 << " is missing. \n";
}
}
I want the code to return
Continue
The value of 2 is missing
Continue
Continue
Continue
The value of 6 is missing
Continue
Continue
The value of 9 is missing
The value of 10 is missing
But instead, after I get the first "missing" element, it lists everything as missing. Anyone have any suggestions?
What is REALLY going wrong is that your initial assumption - that the value (i+1) is expected at location i - becomes invalid once a missing value is detected. If you intend to detect ALL missing values, you need to decouple the array index from the value tracking. Consider the following code:
#define NMISSWING 6
int missingArray[NMISSING] = {1, 3, 4, 5, 7, 8};
int i = 0;
for (int n=1; n<=10; n++) {
if (i >= NMISSING) break; // all array entries checked
if (missingArray[i] == n) {
cout << "Continue. \n";
i += 1; // Matched i'th, move on to next
}
else {
cout << "The value of " << n << " is missing. \n";
}
}
note that I just use 'else' instead of performing essentially the same test twice. If someone is trying to teach you to to do otherwise, feel free to tell them that my opinion as a professional programmer is that that motif strikes me as academic pedantry which should be avoided
Your code leads to undefined behavior since missingArray[i] is not valid for values of i greater than 5.
You need to change your approach a little bit.
int missingArray [] = {1, 3, 4, 5, 7, 8};
int* start = missingArray;
int* end = start + sizeof(missingArray)/sizeof(*missingArray);
for (int i = 1; i < 11; i++)
{
if ( std::find(start, end, i) == end )
{
cout << i << " is missing.\n";
}
// Optionally
else
{
cout << "Found " << i << "\n";
}
}
you check missingArray[i] == i+1
1 == 1
3 == 2
4 == 3
5 == 4
...
so after first condition 1==1 others are never equal.
int missingArray[] = { 1, 3, 4, 5, 7, 8 };
int k = 0;
for (int i = 0; i < 10; i++) {
if (missingArray[k] == i + 1) {
cout << "Continue. \n";
k++;
}
else if (missingArray[k] != i + 1) {
cout << "The value of " << i + 1 << " is missing. \n";
}
}
My approach would be to select each element of the array in turn and then iterate between one greater than that value and the next element in the array.
Then to finish off iterate between the final value and the maximim value you are seeking (11 in this case).
int missingArray [] = {1, 3, 4, 5, 7, 8};
int j = 0;
for(auto i = 0U; i < sizeof(missingArray)/sizeof(int) - 1; ++i)
for(j = missingArray[i] + 1; j < missingArray[i + 1]; ++j)
std::cout << "missing: " << j << '\n';
for(++j; j < 11; ++j)
std::cout << "missing: " << j << '\n';
Output:
missing: 2
missing: 6
missing: 9
missing: 10
As Pmar said, your initial assumption was not valid. I change the code a little bit. I hope this will help you.
#include<stdio.h>
#include <iostream>
using namespace std;
int main (){
int missingArray [] = {1, 3, 4, 5, 7, 8};
int numbers_mising = 0;
for (int i = 0; i < 10; i++) {
if (missingArray[i - numbers_mising] == i+1) {
cout << "Continue. \n";
}
if (missingArray[i - numbers_mising] != i+1) {
cout << "The value of " << i+1 << " is missing. \n" << numbers_mising << "\n";
numbers_mising++;
}
}
}
In this example, also the number two is missing. You do not need to know in advance what numbers are missing with this solution. I use a variable to keep track of the numbers missing and changing the index of the array.
you can go with this logic also this is very simplest logic for you.
Expected Output:
The value of 3 is missing.
The value of 7 is missing.
int missingArray[]={1,2,4,5,6,8};
int n=sizeof(missingArray)/sizeof(missingArray[0]);
int i=0,k=1;
while (i<n)
{
if(missingArray[i]==k)
{
i++;
k++;
}
else
{
cout<<"The value of "<<k<<" is missing. \n";
k++;
}
}
int main()
{
char array[10] = {1,2,3,4,5,6,7,7,9,10};
char i;
char i_2 = 1;
char not_ok = 1;
while(i_2 < 11){
i = 0;
while(i < 10){
if(array[i] == i_2){
not_ok = 0;
}
i++;
}
if(not_ok){
printf("Missing %d\n",i_2);
}
not_ok = 1;
i_2++;
}
return 0;
}
I have written the following program intended on comparing float's in C++. Originally this was written trying to compare double's but I soon realized how bad a problem that is. In general what is supposed to happen is that the program is to compare the two numbers of the given slot array and swap them as necessary.
#include<iostream>
using namespace std;
int swap(float[] , int, int);
int main() {
float slot[10] = {8.25, 3.26, 1.20, 5.15, 7.99, 10.59, 4.36, 9.76, 6.29, 2.09};
int n=10, i;
int lower, upper, sortflag, sml, scan;
lower = 0;
upper = n-1;
sortflag = 1;
float temp;
while( (lower < upper) && (sortflag == 1)) {
sml = lower;
sortflag = 0;
scan = lower + 1;
while(scan <= upper - lower) {
if (slot[scan] > slot[scan + 1]) {
swap(slot, scan, scan + 1);
sortflag = 1;
if(slot[scan] < slot[sml]) sml = scan;
}
scan++;
}
swap(slot, lower, sml);
upper = upper - 1;
lower = lower + 1;
}
cout << "AFTER SORT: " << endl;
for (i= 0; i < n; i++) cout << slot[i] << " ";
cout << endl;
return 0;
}
void swap(float data[], int i, int j) {
float temp;
temp = data[i];
data[j] = data[i];
data[j] = temp;
}
When I ran this program with double instead of float, the program ran infinitely until I had to invoke Ctrl+C to break it. After switching to float I instead get the following output:
AFTER SORT:
8.25 8.25 3.26 5.15 7.99 10.59 10.59 10.59 10.59 10.59
0 0 1 3 4 5 5 5 5 5
--------------------------------
Process exited after 0.06651 seconds with return value 0
Press any key to continue . . .
Where is the logic going wrong?
EDIT: So after some consideration, I went ahead and rewrote the program to make it compare int array values instead.
int slot[10] = {8, 3, 1, 5, 7, 10, 4, 9, 6, 2};
And adjusted all the appropriate functions as necessary:
// Declaration of function:
void swap(int[] , int, int);
void swap(int data[], int i, int j) {
int temp;
temp = data[i];
data[i] = data[j];
data[j] = temp;
}
And the function is now coming up correct with the correct input. There is no problems with going out of bounds here.
AFTER SORT:
1 2 3 4 5 6 7 8 9 10
--------------------------------
Process exited after 0.05111 seconds with return value 0
Press any key to continue . . .
Here's the new modified program:
int main() {
int slot[10] = {8, 3, 1, 5, 7, 10, 4, 9, 6, 2};
int n=10, i;
int lower, upper, sortflag, sml, scan;
lower = 0;
upper = n-1;
sortflag = 1;
while( (lower < upper) && (sortflag == 1)) {
sml = lower;
sortflag = 0;
scan = lower + 1;
while(scan <= (upper-lower)) {
if (slot[scan] > slot[scan + 1]) {
swap(slot, scan, scan + 1);
sortflag = 1;
if(slot[scan] < slot[sml]) sml = scan;
}
scan++;
}
swap(slot, lower, sml);
upper = upper - 1;
lower = lower + 1;
}
cout << "AFTER SORT: " << endl;
for (i= 0; i < n; i++) cout << slot[i] << " ";
cout << endl;
//for (i= 0; i < n; i++) cout << index[i] << " ";
cout << endl;
return 0;
}
void swap(int data[], int i, int j) {
int temp;
temp = data[i];
data[i] = data[j];
data[j] = temp;
}
So now the question is why does the int version work without problem but neither the double nor float versions do?
Your swap function is wrong. data[j] = data[i]; is useless when followed by another write data[j] = temp;. It should be like this
int swap(float data[], int i, int j) {
float temp;
temp = data[i];
data[i] = data[j]; // reverse this line
data[j] = temp;
return 0;
}
And there's no point making the function returning int if you don't use the result. Just declare it void
So I'm trying to randomize an array of 1, 2, 3, 4, 5, 6, 7, 8, 9, 10. Then ask for the user to select a position in the array, and modify it. After that, it should display the number the user entered for all of the 10 values. Finally, it will need to get the original array that was randomized and reverse it.
So far, I have this
#include <iostream>
using namespace std;
int array [10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int rarray [10];
int main() {
cout << "Random Array = ";
for (int i = 0; i < 10; i++) {
int index = rand() % 10;
int temp = array[i];
array[i] = array[index];
array[index] = temp;
}
for (int i = 1; i <= 10; i++) {
cout << array[i] << " "; //somehow, this display needs to be entered into another array
}
system("PAUSE");
}
But as stated in the comment, I'm stuck on as how to do this.
You can accomplish this by using std::shuffle, std::copy, and std::reverse from the C++ Standard Library.
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int position;
// Get the position to modify and make sure it's within our bounds.
do
{
cout << "Select a position: ";
}
while (!(cin >> position) || position < 0 || position > 9);
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int rarray[10];
// Shuffle the array. We use std::begin and std::end to get the bounds of
// of the array instead of guessing it's size.
std::random_shuffle(std::begin(array), std::end(array));
// Copy it to the new array
std::copy(std::begin(array), std::end(array), rarray);
// Modify the new array and display it. Add your own code here to get the
// value it is modified with.
rarray[position] = 100;
for (auto value : rarray)
cout << value << " ";
cout << endl;
// Reverse the original array and display it
std::reverse(std::begin(array), std::end(array));
for (auto value : array)
cout << value << " ";
cout << endl;
system("PAUSE");
}
or if you are not allowed to use the C++ Standard Library you will need to handle everything manually. This is a tedious task but a great example of why the C++ Standard Library should be leveraged whenever possible. This is also more prone to errors, more difficult to maintain, and ugly to look at.
int main()
{
int position;
do
{
cout << "Select a position: ";
} while (!(cin >> position) || position < 0 || position > 9);
int array[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < 10; i++)
{
int index = rand() % 10;
int temp = array[i];
array[i] = array[index];
array[index] = temp;
}
// Copy the array
int rarray[10];
for (int i = 0; i < 10; i++)
{
rarray[i] = array[i];
}
// Modify the new array and display it
rarray[position] = 100;
for (int i = 0; i < 10; i++)
{
cout << rarray[i] << " ";
}
cout << endl;
// Reverse the old array and display it
for (int i = 0; i < 10 / 2; i++)
{
int tmp = array[i];
array[i] = array[9 - i];
array[9 - i] = tmp;
}
for (int i = 0; i < 10; i++)
{
cout << array[i] << " ";
}
cout << endl;
system("PAUSE");
}
Both implementations are close to your original request but you may need to expand on it a little to match your requirements exactly. They should get you moving along nicely though.