Right rotation operation - c++

int main()
{
int shiftSteps, newposition;
int numbers[10], numberscopy[10];
cin >> shiftSteps;
for (int i = 0; i < 10; i++)
cin >> numbers[i];
for (int i = 0; i < 10; i++)
numberscopy[i] = numbers[i];
//----------------------------------------
for (int i = 0; i < 10; i++)
{
newposition = (i + shiftSteps) % 10;
numbers[newposition] = numberscopy[i];
}
for (int i = 0; i < 10; i++)
cout << numbers[i] << " ";
}
I wrote this code to rotate 10 numbers to Right with auxiliary array "numberscopy", but i want to rewrite the code without auxiliary array and i don't know how.

You can rotate the array in-place, i.e. without using an auxiliary array with std::rotate which is a standard algorithm.
std::rotate(numbers, numbers + shiftSteps, numbers + 10);

Without auxiliary array, you can make use of reversal algorithm to rotate array by "shiftSteps".
It involves following three steps,
reversing array from 0 to sizeOfArray-1
reversing array from 0 to shiftSteps-1
reversing array from shiftSteps to sizeOfArray-1
Here's final code,
void reverseArray(int numbers[], int begin, int end)
{
while (begin < end)
{
swap(numbers[begin], numbers[end]);
begin++;
end--;
}
}
void rightRotate(int numbers[], int shiftSteps, int sizeOfArray)
{
reverseArray(numbers, 0, sizeOfArray-1);
reverseArray(numbers, 0, shiftSteps-1);
reverseArray(numbers, shiftSteps, sizeOfArray-1);
}
int main()
{
int shiftSteps;
int numbers[10];
cin >> shiftSteps;
for (int i = 0; i < 10; i++)
cin >> numbers[i];
rightRotate(numbers, shiftSteps, 10);
for (int i = 0; i < 10; i++)
cout << numbers[i] << " ";
}
Source for more info.

Related

Why does this selection sort code shows different output when running again as compared to first time

Firstly when I have code this program it was running perfectly but running it again, it is not showing expected output can someone tell what's wrong with it
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
int arr[n];
int loc,min;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
for (int i = 0; i < n - 1;i++){
min = arr[i];
for (int j = i + 1; j < n; j++)
{
if(min>arr[j]){
min = arr[j];
loc = j;
}
swap(arr[loc],arr[i]);
}
}
for (int i = 0; i < n; i++){
cout << arr[i] << " ";
}
cout << endl;
}
Forgoing the fact that variable-length arrays are not part of standard C++ (and thus code tutorials that use them should be burned), the code has two main problems.
On an already sorted sequence, the inner-most if body will never be entered, and therefore loc will never receive a determinate value.
The swap is in the wrong place..
Explanation
Within your code...
using namespace std;
int main(){
int n;
cin >> n;
int arr[n];
int loc,min; // loc is INDETERMINATE HERE
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
for (int i = 0; i < n - 1;i++){
min = arr[i];
for (int j = i + 1; j < n; j++)
{
if(min>arr[j]){
min = arr[j];
loc = j; // loc ONLY EVER SET HERE
}
swap(arr[loc],arr[i]); // loc IS USED HERE EVEN IF NEVER SET
}
}
for (int i = 0; i < n; i++){
cout << arr[i] << " ";
}
cout << endl;
}
The purpose of the inner loop is to find the location (loc) of the most extreme value (smallest, largest, whatever you're using for your order criteria) within the remaining sequence. No swapping should be taking place in the inner loop, and the initial extreme value location (again, loc) should be the current index of the outer loop (in this case i)
Therefore...
We don't need min. It is pointless.
We must initialize loc to be i before entering the inner loop.
We swap after the inner loop, and then only if loc is no longer i.
The result looks like this.
int main()
{
int n;
cin >> n;
int arr[n];
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
for (int i = 0; i < n - 1; i++)
{
int loc = i;
for (int j = i + 1; j < n; j++)
{
if (arr[loc] > arr[j])
loc = j; // update location to new most-extreme value
}
// only need to swap if the location is no longer same as i
if (loc != i)
swap(arr[loc], arr[i]);
}
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
The line swap(arr[loc],arr[i]); should be outside the inner for loop, so move it one line down.
Also, you will want to initialize loc to i at the start of the outer for loop.
#include<bits/stdc++.h>
using namespace std;
int main(){
int n;
cin >> n;
int arr[n];
int loc,min;
for (int i = 0; i < n; i++)
{
cin >> arr[i];
}
for (int i = 0; i < n - 1;i++){
min = arr[i];
loc=i;
for (int j = i + 1; j < n; j++)
{
if(min>arr[j]){
min = arr[j];
loc = j;
}
swap(arr[i],arr[loc]);
}
}
for (int i = 0; i < n; i++){
cout << arr[i] << " ";
}
cout << endl;
}

Frequency of arrays in C++

I'm trying to write a code which works like this:
it first gets an int from the user which presents the number of array indexes the user would like to own (n), then the code creates an array with n number of indexes. It then has to print the frequency of every entered number.
Running my below code results in a segmentation fault. Any solution will in advance be appreciated.
My code:
int main()
{
int n, index;
cin>>n;
int ar[n];
int freq[100]={0};
for (int i = 0; i < n; i++)
{
cin>>ar[i];
}
for (int i = 0; i < 100; i++)
{
index=ar[i];
freq[index]++;
}
for (int i = 0; i < 100; i++)
{
cout<<freq[i]<<' ';
}
return 0;
}
NOTE: 1<=n<=100
I would do something like this:
int main ()
{
int n, input;
while (n > 100 || n < 1)
cin >> n;
// indexes 0 - 99
int freq[100] = { 0 };
for (int i = 0; i < n; i++)
{
cout << "number: ";
cin >> input;
if (input > 0 && input <= 100)
freq[input - 1]++;
}
for (int i = 0; i < n; i++)
if (freq[i] != 0)
cout << i + 1 << "-->" << freq[i] << &endl;
return 0;
}
try it here

c++ Selection sort isn't working in specific cases

I've created a program that uses selection sort to sort integers in an array. In specific cases, such as if I input that I want an array of length 3 and then have "2 1 3" as my input, it outputs it in the same order. It's working for other inputs, but every now and then for some reason it wont sort a list of integers correctly.
My code is as follows:
'''
#include <iostream>
using namespace std;
void sort(int[], int);
void swap(int&, int&);
void swap(int &a, int &b){
int temp;
temp = a;
a = b;
b = temp;
}
void sort(int nums[], int n){
int j, min, i;
for (i = 0; i < n - 1; i++){
min = i;
for(j = i + 1; j < n; j++){
if(nums[j] < nums[min]){
min = j;
}
swap(nums[min], nums[i]);
}
}
}
int main(){
int n, i;
cout << "Enter how many numbers you want to sort" << endl;
cin >> n;
int nums[n];
cout << "Enter the integers seperated by a space: ";
for(i = 0; i < n; i++){
cin >> nums[i];
}
cout << "Array Before Sort: ";
for (i = 0; i < n; i++){
cout << nums[i] << ", ";
}
sort(nums, n);
cout << "\nArray after sort: ";
for(i = 0; i < n; i++){
cout << nums[i] << ", ";
}
return 0;
}
'''
Place your swap(nums[min], nums[i]); statement outside of inner loop, like this
void sort(int nums[], int n){
int j, min, i;
for (i = 0; i < n - 1; i++){
min = i;
for(j = i + 1; j < n; j++){
if(nums[j] < nums[min]){
min = j;
}
}
swap(nums[min], nums[i]);
}
}

How do I put any value X after all the minimums in an array?

If I enter an array , at first the code finds the minimums then I want to put zeroes after all the minimums . For example
given an array = 1,1,3,1,1
As we see 1s are the minimum so the result should be = 1,0,1,0,3,1,0,1,0
CODE
#include <pch.h>
#include <iostream>
int main()
{
int min = 10000;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] > min)
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min) { // Not very clear about this
for (int k = n; k > i; k--) // part of the code, my teacher
array[k] = array[k - 1]; //explained it to me , but i
array[i + 1] = 0; // didn't understand (from the
i++; // `for loop k` to be precise)
n++;
}
std::cout << array[i] << ", 0";
}
return 0;
}
But my answer doen't put zeroes exactly after minimums
There are few issues in your code, first of all your min is wrong. I have fixed your code with comments on fixes I have made. Please take a look :
#include "stdafx.h"
#include <iostream>
int main()
{
int min = 10000;
bool found = 0;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] < min) //< instead of >
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min)
{
for (int k = n; k > i; k--)
{
array[k] = array[k - 1];
}
array[i + 1] = 0;
i++; //increment i here because you don't want to consider 0 that you have just added above.
n++; //since total number of elements in the array has increased by one (because of 0 that we added), we need to increment n
}
}
//print the array separately
for (int i = 0; i < n; i++)
{
std::cout << array[i];
if (i != n - 1)
{
std::cout << ",";
}
}
return 0;
}
The first issue was in the calculation of min: < instead of >.
Another problem if that you are modifyng the paramers iand ninside the loop. This is rather dangerous and implies to be very cautious.
Another issue was that it should be i++; n++; instead of i--,n--;
Here is the code:
// #include <pch.h>
#include <iostream>
int main()
{
int min = 1000000;
int n;
std::cout << "Enter the number of elements (n): "; //no of elements in the
std::cin >> n; //array
int *array = new int[2 * n];
std::cout << "Enter the elements" << std::endl;
for (int i = 0; i < n; i++) {
std::cin >> array[i];
if (array[i] < min)
min = array[i];
}
for (int i = 0; i < n; i++) {
if (array[i] == min) { // Not very clear about this
for (int k = n; k > i; k--) // part of the code, my teacher
array[k] = array[k - 1]; //explained it to me , but i
array[i + 1] = 0; // didn't understand (from the)
i++;
n++;
}
}
for (int i = 0; i < n; i++) {
std::cout << array[i] << " ";
}
std::cout << "\n";
return 0;
}

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));
;-)