I have some code that rotates a number array to the left but instead, I need it to rotate it to the right. There is other code online that rotates array to the right but that code lets you only rotate numbers in the middle of the array.
I have tried decrementing the loops differently & and changing where its initialized but doesn't seem to rotate the correct way.
Expected output: if array is this {1, 2, 3, 4, 5, 6, 7}. Then it should look like: {7, 1, 2, 3, 4, 5, 6}
Current output: {2, 3, 4, 5, 6, 7, 1}
#include <iostream>
using namespace std;
/*Function to left Rotate arr[] of size n by 1*/
void leftRotatebyOne(int arr[], int n);
/*Function to left rotate arr[] of size n by d*/
void leftRotate(int arr[], int d, int n)
{
int i;
for (i = 0; i < d; i++)
leftRotatebyOne(arr, n);
}
void leftRotatebyOne(int arr[], int n)
{
int i, temp;
temp = arr[0];
for (i = 0; i < n-1; i++)
arr[i] = arr[i+1];
arr[i] = temp;
}
/* utility function to print an array */
void printArray(int arr[], int size)
{
int i;
for(i = 0; i < size; i++)
cout << arr[i] << " ";
}
/* Driver program to test above functions */
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7};
printArray(arr, 7);
leftRotate(arr, 1, 7);
cout << "___" << endl;
printArray(arr, 7);
getchar();
return 0;
}
leftRotateByOne is the key function here. The others can stay the same. Have a look at what it is doing, preferably with a pen and paper to keep track of the operations:
Keeps a copy of the first element.
Moves all elements to the "left" (that is, to the element with index
one less), being careful not to overwrite anything you need later.
Puts the first element in the last place.
So you need to do the opposite:
Keep a copy of the last element.
Moves all elements to the "right" (that is, to the element with index
one more), being careful not to overwrite anything you need later.
Puts the last element in the first place.
For example:
void rightRotatebyOne(int arr[], int n)
{
int i, last;
last = arr[n-1];
for (i = n-1; i > 0; i--)
arr[i] = arr[i-1];
arr[0] = last;
}
Related
I am looking at my homework for c++ and having some trouble understanding a part of the code. The code is creating a 2d array and wants to know how many times the elements from 1-9 are repeated.
#include <iostream>
using namespace std;
const int r = 3;
const int c = 4;
void frequency (int a[r][c]);
int main() {
int elems [r][c] = {{1, 1, 3, 4}, {2, 3, 4, 5}, {6, 9, 9, 9}};
frequency(elems);
return 0;
}
void frequency(int a[r][c]){
int arr[10] = {};
for(int i = 0; i < r; i++){
for(int j = 0; j < c; j++){
arr[a[i][j]]++;
}
}
for(int i = 1; i < 10; i++){
cout << i << " is repeated " << arr[i] << " times." << endl;
}
}
I don't understand how the line arr[a[i][j]]++; works -- how does it act as a counter for elements that are repeated?
I don't understand how the line arr[a[i][j]]++; works -- how does it act as a counter for elements that are repeated?
int arr[10] = {}; is creating an int-array with 10 elements (indexed 0-9) all initialized to 0.
arr[a[i][j]]++; is (post-)incrementing an element of arr.
The element at which index? The one at index a[i][j].
You loop through every row in a (i.e. in elems) using i and through every column within that row using j; in essence looping through every element in the order they are spelled in the source code. You are using the numbers in array a to index into the array arr: The first two elements of elems are 1, thus you increment arr[1]. The third number in elems is 3, thus you increment arr[3], ...
I am trying to call the functions so that it prints out if the array is a palindrome or not. Please tell me what I am doing wrong; it seems I am not passing the arguments correctly. If I made a mistake with the post, please let me know; I am fairly new to the website.
This is how the output is supposed to look:
This is what my output looks like:
This is my code:
#include <stdio.h>
void createReverseArray();
void printArray();
void compareArray();
int main()
{
int MyArray1[] = {1, 2, 3, 2, 1};
int MyArray2[] = {1, 2, 3, 4, 1};
int MyArray3[] = {1, 2, 3, 3, 2, 1};
int MyArray4[] = {1, 2, 3, 4, 2, 1};
int n = 5, i, j, n, temp;
createReverseArray(MyArray1[5]);
createReverseArray(MyArray2[5]);
createReverseArray(MyArray3[5]);
createReverseArray(MyArray4[5]);
compareArray(MyArray1[5]);
compareArray(MyArray2[5]);
compareArray(MyArray3[5]);
compareArray(MyArray4[5]);
printArray(MyArray1[5]);
printArray(MyArray2[5]);
printArray(MyArray3[5]);
printArray(MyArray4[5]);
}
int createReverseArray(int &a[], int n)
{
i = 0;
j = n - 1;
while(i<j) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
return reverse = a[];
}
int compareArray(int &a[], int reverse)
{
if(a[] == reverse) {
printf("The array is a palindrome")
}
else {
return 0;
}
}
void printArray(&a[])
{
printf("Array elements are:%d", a[]);
compareArray(a[]);
}
I am not sure due to the amount of uncertainties I have with the provided code, but if your objective is simply to detect whether the array is a palindrome, it is exceedingly simple and can be done in a single function:
bool isPalindrome(int[] list, int size)
{
for(int k = 0; k < size / 2 - 1; k++)
if(list[k] != list[size - k - 1])
return false;
return true;
}
This will iterate half your array, comparing it to the second half and exiting the instant one value is not equal to its mirror.
As for the mistakes in your code, I might be able to point out some of the more obvious ones, for future reference:
Calling functions with incorrect number of arguments.
Example: createReverseArray(MyArray1[5]).
Calling passing integers in place of arrays as arguments. Example:
MyArray[5] is the integer in the sixth position of MyArray.
Ignoring scope and using variables without declaring them. Example: i and j from main being used in createReverseArray. THIS DOES NOT WORK.
Comparing an integer to an array pointer. Example: if(a[] == reverse). No matter what you were trying to achieve, this will never give you a useful result.
Declaring different functions in your forward declaration and in your implementation. Example: void createReverseArray(); and int createReverseArray(int &a[], int n). You should declare them wit the same arguments and return values or the compiler will not understand they're the same thing.
I am using sublime text 2 and I am trying to program bubble sort, and every time I run the code below it gives me an error on bubbleSort(num[5], terms); the error is
ERROR: no matching function for call to 'bubbleSort'.
Can anyone tell me why this is happening.
The code is:
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int term) {
for(int i = 0; i < term; ++i) {
for(int index = 0; index < term-i-1; ++index) {
if(arr[index] < arr[index + 1]) {
int swap;
swap = arr[index];
arr[index] = arr[index + 1];
arr[index + 1] = swap;
}
}
}
for(int counter = 0; counter < term; counter++) {
cout << arr[counter] << endl;
}
}
int main() {
cout << "Hi in this program I will do bubble sort" << endl;
cout << "The numbers are 2, 9, 5, 10, 6"<< endl;
int num[5] = {2, 9, 5, 10, 6};
int terms = sizeof (num) / sizeof (num[0]);
bubbleSort(num[5], terms);
//answer = [2, 5, 6, 9, 2, 10]
}
Although a good question should be accompanied by a complete example of the compiler error, this answer should be fine.
void bubbleSort(int arr[], int term) {
// ...
}
It's a function which accepts an array of integers as first parameter and an integer as second one.
When you try to invoke it with:
int num[5] = {2, 9, 5, 10, 6};
// ...
bubbleSort(num[5], terms);
You're passing num[5] which is not an array of integer, but it should be an element of the array num, then an integer itself.
In short you're calling the function passing
bubbleSort(INT, INT);
and not, as requested by the function
bubbleSort(ARRAY_INT, INT);
That' why the compiler doesn't find a function which names bubbleSort and accept two integers.
Additional note
It's a little be out of context, but I want to suggest you to improve your C++ base skills, because the expression:
num[5]
It's perfectly wrong in your code, because it tries to access to the 6-th element in the array (which is composed by only 5 elements), that'll produce an out-of-bound behaviour.
Thanks for helping me now I know that I am supposed to use
bubbleSort(num, terms);
I want to locate a specific item from an array and then shift the array to remove that item. I have a list of integers {1, 2, 3, 4, 5, 6, 7, 8, 9} and want to remove the integer 2.
Currently I am getting an error: storage size of ‘new_ints’ isn’t known on the line:
int new_ints[];
Not sure what this means or how can I fix this?
Here is my code:
int main() {
int tmp = 2;
int valid_ints[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int new_ints[];
new_ints = stripList(tmp, valid_ints);
for (int i = 0; i < sizeof(new_ints); i++)
cout << new_ints[i] << endl;
return 0;
}
int *stripList (int tmp, int valid_ints[]){
for (int i = 0; i < sizeof(valid_ints); i++){
for (int j = tmp; j < sizeof(valid_ints); j++){
valid_ints[j] = valid_ints[j+1];
}
}
return valid_ints;
}
Like what Ben said, it is highly recommended to use an vector if you would like to resize your array to fit in new elements.
http://www.cplusplus.com/reference/vector/vector/vector/
Here's my example: (note alternatively you can use vector::erase to erase undesired elements)
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<int> valid_ints;
vector<int> new_ints;
int tmp = 2;
//read in elements
for(int i = 1; i <= 9; i++)
{
valid_ints.push_back(i);
}
//valid_ints will hold {1,2,3,4,5,6,7,8,9}
for(int i = 0; i < valid_ints.size(); i++)
{
//We will add an element to new_ints from valid_ints everytime the valid_ints[i] is NOT tmp. (or 2.)
if(valid_ints[i] != tmp)
{
new_ints.push_back(valid_ints[i]);
}
}
//Print out the new ints
for(int i = 0; i < new_ints.size(); i++)
{
cout << new_ints[i] << ' ';
}
return 0;
}
The resulting vector will be filled in this order:
{1}
{1,3} (skip 2!)
{1,3,4}
{1,3,4,5}
so on... until
{1,3,4,5,6,7,8,9}
So, the output would be:
1 3 4 5 6 7 8 9
In c++ size of an array must be known at compile time. Ie int new_ints[] is illegal. You will need to have a defined size ie new_ints[10]. (See here for more details) Or better yet, utilize the fantastic advantages of c++ and use a std::vector.
I'm trying to convert some old C functions to C++. My original programme stores a matrix in a single array, and I just pass a pointer to the first element to a function so that I am working on the correct row, e.g.
double f1(int *a){
return a[0] + a[1];
}
int main(void){
int x[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for(i = 0; i < 5; i++){
printf("%d\n", f1(&x[2 * i]));
}
I would like to be able to do something similar using the STL without copying. So my programme would look something like this
double f1(vector<int>& a){
return a[0] + a[1];
}
int main(void){
int x[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
vector<int> y(x, x + 10);
for(i = 0; i < 5; i++){
cout << f1(y) << endl; // This is clearly wrong
}
How would I do this? I could change my function to receive a reference to a vector::iterator I guess, but is there another way?
You could simply pass an iterator to the function. Random access iterators are very similar to pointers (in fact, pointers qualify as random access iterators.) For example,
#include <vector>
double f1(std::vector<int>::const_iterator a)
{
return a[0] + a[1];
}
#include <iostream>
int main()
{
vector<int> y{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
auto it = y.cbegin();
for(int i = 0; i < y.size()/2; ++i)
std::cout << f1(it + 2*i) <<std::endl;
}
Write array view. An array view is a pair of pointers with begin end size empty, operator[], front and back methods, and constructors from C arrays, std::array<T,N>&, std::vector<T,A>&, std::vector<non_const_T,A>const&, std::array<non_const_T,N>const&, std::initializer_list<non_const_T>, etc.
Oh, and T*,size_t and T*,T* ctors, which are great for slicing (use forwarding ctors: T*,size_t->T*,T*, and everything else to those 2).
It does not own its data, so all of its methods are const except operator=. (non-const methods would be methods that change the view range -- changing the elements is a const operation on a view).
Then
double f1(array_view<const int> a){
return a[0] + a[1];
}
You don't need to make so many changes:
double f1(int *a)
{
return a[0] + a[1];
}
int main(void)
{
vector<int> y = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
for (int i = 0; i < 5; i++) {
cout << f1(&y[2 * i]) << endl;
}
}