So I'm making a selection sort program where I have to input two values: one for the numbers to use in the array, and the seed to use for the random number generator. I'm just a little confused on how to adjust the number used, since the maximum number of elements we can put in is 15. The array currently has 8. Each element should be a number between 20 and 40.
#include <iostream>
using namespace std;
int selectionSort(int[], int);
int selectionSort(int numbers[], int numbersSize) {
int i = 0;
int j = 0;
int indexSmallest = 0;
int temp = 0; // Temporary variable for swap
for (i = 0; i < numbersSize - 1; ++i) {
// Find index of smallest remaining element
indexSmallest = i;
for (j = i + 1; j < numbersSize; ++j) {
if (numbers[j] < numbers[indexSmallest]) {
indexSmallest = j;
}
}
// Swap numbers[i] and numbers[indexSmallest]
temp = numbers[i];
numbers[i] = numbers[indexSmallest];
numbers[indexSmallest] = temp;
}
return indexSmallest;
}
int main() {
int numbers[] = {10, 2, 78, 4, 45, 32, 7, 11, 0, 0, 0, 0, 0, 0, 0};
const int NUMBERS_SIZE = 15;
int i = 0;
int nums = 0;
int seed = 0;
cin >> nums;
cin >> seed;
srand(seed);
for (int i = 0; i < nums; i++) {
numbers[i] = (rand() % 20) + 20;
}
cout << "UNSORTED: ";
for (i = 0; i < nums; ++i) {
cout << numbers[i] << " ";
}
cout << endl;
selectionSort(numbers, nums);
cout << "SORTED: ";
for (i = 0; i < nums; ++i) {
cout << numbers[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
The only problem is that the random numbers being generated are the wrong numbers. For example, when I input "10 100" (10 for the numbers being used in the array and 100 for the seed), it outputs
UNSORTED: 25 36 35 24 24 34 38 22 29 29
SORTED: 22 24 24 25 29 29 34 35 36 38
when it should be outputting
UNSORTED: 28 28 34 37 36 27 33 36 36 39
SORTED: 27 28 28 33 34 36 36 36 37 39
I'm not really sure how to fix this.
There is a lot to say about this code:
The initial values put into the array numbers[] will of course be overwritten.
NUMBERS_SIZE is not used.
If you want to be able to specify the array length as input parameter, you should use a std::vector<>, or create the array dynamically, or at least check that the given number of values doesn't exceed the array size.
rand() is a random number generator, srand() sets some kind of seed for these random numbers. It is guaranteed that with the same seed you will always get the same sequence of random numbers.But, why/how do you expect to know the numbers that will be generated?
Indention.
Don't do using namespace std;
The answer to your question would be: Don't use random numbers.
You may try rand function
/* initialize random seed: */
srand (time(NULL));
/* generate random number betwee 1 and 10: */
iSecret = rand() % 10 + 1;
you need also to include 3 libraries
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
Related
I want to sort using the "Bubble Sort" algorithm of the 2d array. My array size will be about array[100000][100000]. my input number will be n=100,000.
For now we can use a small size of the array to fix the sorting issue.
I need to sort them in descending order for the first number(first number's line).
If the first number of 2 values are the same, then I have to sort them according to their second number.
Finally I have to output the result into a txt file
Let's' understand using an example. Here, my input looks like this
41 11
34 4
69 4
78 6
62 8
5 5
81 3
5 10
above our input example and we have a couple of inputs. Now I need to sort them descending orders for the first number. But if the first number of 2 values are the same, then sort them according to their second number.
Example output below,
81 3
78 6
69 4
62 8
41 4
34 4
5 10
5 5
If anyone can please help me.
I am a beginner so I am trying to input the file manually to solve this sorting problem. I can solve the sorting problem then I will try to input and out the text.
Something I have tried but not worked. I am still trying to solve it.
#include<bits/stdc++.h>
#include <algorithm>
using namespace std;
int main ()
{
int arr[100][100];
int n,j;
cin >>n;
cout << "Please enter a number: " << endl;
for(int i=0;i<n;i++)
{ for (int j=i; j<n; j++)
{
cin>>arr[i][j];
}
}
cout << "Unsorted array:" << endl;
for (int i=0; i<n; i++)
{
for (int j=i; j<n; j++)
{
cout<<arr[i][j]<<"\t";
}
}
for (int i=0; i<=n; i++)
{
for (int j=i+1; j<=n-1; j++)
{
int temp;
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
return 0;
}
Use a std::vector<std::array<int,2>>for your base container. The dynamic growth capabilities of std::vector solves your stack space issue, and the std::array use gives you tied cell comparison. I.e. you can do this:
std::array<int, 2> ar1{1,2}, ar2{1,3};
if (ar1 < ar2) ...
and it will do the right thing. The result then boils down to effectively this:
#include <iostream>
#include <array>
#include <vector>
#include <utility>
int main()
{
std::vector< std::array<int,2> > v;
std::size_t n;
if (std::cin >> n && n > 0)
{
std::array<int,2> row;
while (n-- && std::cin >> row[0] && std::cin >> row[1])
v.emplace_back(row);
// bubblesort the content
std::size_t len = v.size();
while (len-- > 0)
{
bool swapped = false;
for (std::size_t i=0; i<len; ++i)
{
// std::array support multi-cell comparison.
if (v[i] < v[i+1])
{
// use library swap to swap entire row.
std::swap(v[i], v[i+1]);
swapped = true;
}
}
// early exit if no swaps happened on the last pass
if (!swapped)
break;
}
// report final output.
for (auto const& row : v)
std::cout << row[0] << ' ' << row[1] << '\n';
}
}
Input
8
41 11
34 4
69 4
78 6
62 8
5 5
81 3
5 10
Output
81 3
78 6
69 4
62 8
41 11
34 4
5 10
5 5
I wrote a program where program sorts people by the each person time, and if time is the same, program sorts by the name alphabetically. Everything works fine, just I am getting extra first line full of random symbols. I of course can write if function and say not to show that first line, but is it good thing to do?
#include <algorithm>
#include <iostream>
#include <stdlib.h>
#include <string>
using namespace std;
struct people {
string full_name;
int h;
int min;
int sec;
};
bool comp(const people &p1, const people &p2) {
return (p1.min < p2.min || p1.min == p2.min && p1.sec < p2.sec ||
p1.min == p2.min && p1.sec == p2.sec && p1.full_name < p2.full_name);
}
int main() {
int time;
string fullnamechange[30];
people peo[30];
cin >> time;
for (int i = 0; i < time; i++) {
getline(cin, peo[i].full_name); // taking everything into a string
fullnamechange[i] = peo[i].full_name;
fullnamechange[i].erase(fullnamechange[i].begin(),
fullnamechange[i].end() - 8);
peo[i].h = atoi(fullnamechange[i].c_str());
fullnamechange[i].erase(fullnamechange[i].begin(),
fullnamechange[i].end() -
5); // changing time in string to int
peo[i].min = atoi(fullnamechange[i].c_str());
fullnamechange[i].erase(fullnamechange[i].begin(),
fullnamechange[i].end() - 2);
peo[i].sec = atoi(fullnamechange[i].c_str());
}
for (int i = 0; i < time; i++) { // erasing time from string
peo[i].full_name.erase(peo[i].full_name.begin() + 20,
peo[i].full_name.end());
}
sort(peo, peo + time, comp);
cout << endl;
for (int i = 0; i < time; i++) {
cout << peo[i].full_name << " " << peo[i].min << " " << peo[i].sec << endl;
}
return 0;
}
/*
input for example:
6
Petras A. Petraitis 0 20 00
Jurgis Jurgutis 0 12 59
Romas Jonas 0 15 12
Zigmas Nosis 0 23 9
Rimas Senasis 0 15 12
output I get:
em3╣Mg n Ç 0 0 //random numbers I get
Jurgis Jurgutis 12 59
Rimas Senasis 15 12
Romas Jonas 15 12
Petras A. Petraitis 20 0
Zigmas Nosis 23 9 */
I'm trying to create an array of pointers to a 2D (5 X 12) array in C++.
The ptr array has 5 elements. Each element should hold the address of the 1st element of the respective row of the 2D array. So 1st element should point to 1st element of 1st row, 2nd element should point to 1st element of 2nd row, and so on.
The 5th element of my array of pointers seems to point to a garbage value.
Code and output shown below. Can anyone please let me know why?
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
int main( )
{
int rainMatrix[5][12] = {{0}}; //declare and initialize rain matrix
int *matrix_ptr[5] = {NULL};//declare and initialize array of pointers
int **matrix_ptr_ptr = matrix_ptr;
for (int i = 0; i < 5; ++i)
matrix_ptr[i] = &rainMatrix[i][0];
rainGen(matrix_ptr_ptr, 5, 12); //generate a random matrix
//display the matrix
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 12; ++j) {
cout << setw(2) << rainMatrix[i][j] << " ";
}
cout << endl;
}
for (int i = 0; i < 5; ++i)
cout << setw(2) << *matrix_ptr[i] << " " << rainMatrix[i][0] << endl;
return 0;
}
void rainGen (int **pptr, int row, int col)
{
unsigned int seed = 43;
unsigned int rv;
srand(seed);
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
rv = rand() % 100;
**pptr = rv;
*pptr += 1;
}
pptr++;
}
}
OUTPUT
11 1
88 11
28 88
25 28
1477892712 25
You're manipulating the wrong pointer in the innermost loop. Consider the pointer arithmetic carefully:
pptr essentially points to matrix_ptr[0];
on the first iteration, the double indirection means **pptr will set what you want, but then
*pptr += 1 will modify the contents of matrix_ptr[0], which means it no longer points to the beginning of the matrix.
Subsequent passes through the loop compound the situation drastically.
Modifying pptr won't help because it actually points to the wrong thing: it points to matrix_ptr, so incrementing it merely once moves its address from that of matrix_ptr[0], which points to rainMatrix[0][0], to that of matrix_ptr[1], which points to rainMatrix[1][0]. That is the wrong address for the next entry of the matrix, which is rainMatrix[0][1]. In essence, you've moved to the next row, instead of to the next column.
Try this for the innermost loop instead:
for (int i = 0; i < row; ++i)
{
auto qptr = *pptr;
for (int j = 0; j < col; ++j)
{
rv = rand() % 100;
*qptr = rv;
qptr += 1;
}
pptr++;
}
}
In this case, qptr is given the address of the first entry in the matrix. *qptr = rv sets the value. qptr += 1 increments the position of qptr while leaving *pptr alone - and, by extension, it leaves matrix_ptr[0] alone.
John Perry correctly identified the problem, but you have several option to deal with it. You are incorrectly incrementing *pptr += 1 Beyond using auto, you can simply index the pointer with the offset of j, e.g.
*(*pptr + j) = rv;
or
(*pptr)[j] = rv;
Either will work. Putting it together in your rainGen function, you could do:
void rainGen (int **pptr, int row, int col)
{
unsigned int seed = 43;
unsigned int rv;
srand(seed);
for (int i = 0; i < row; ++i) {
for (int j = 0; j < col; ++j) {
rv = rand() % 100;
// *(*pptr + j) = rv; /* or */
(*pptr)[j] = rv;
}
pptr++;
}
}
(note: seed and srand(seed) should be moved to main() if there is the potential that rainGen could be called more than once -- srand should only be called once)
Example Use/Output
Both will produce the desired output:
$ ./bin/raingen
72 71 65 94 0 13 49 17 36 49 67 51
87 68 45 15 91 72 16 80 77 35 9 81
11 88 73 59 24 22 37 48 45 54 94 45
19 44 62 56 45 81 59 32 49 4 99 92
28 16 24 5 3 34 38 14 22 12 26 98
72 72
87 87
11 11
19 19
28 28
You are modifying the pointers in the pointer-array matrix_ptr within your rainGen function, so that all of them point past the end and further accesses go to "random" memory locations, which is undefined behavior. Tools like valgrind can find such errors.
I need to generate a random amount of numbers between 10 to 15. Also, I need to make those random numbers between 20 to 50. I have the second part done I think, I just don't know what to put into my if statement condition. Anyone know? Here's my code thus far:
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
srand((unsigned)time(0));
int random_integer; // Stores random number between 20 and 50
int random_set; // Stores random amount of numbers
for(){ //
random_integer = 20 + rand()%25; // Random number between 20 and 50
cout <<"Generating " << random_set << "random numbers" << random_set " (is a random number between 10 to 15).";
cout << random_integer <<", ";
}
return 0;
}
Whilst the other answers have covered how to do this using rand(), the better (and proper) way to generate random numbers in C++ (assuming you have a C++11 or above compiler, which you should have) is via the <random> header.
Here is how to generate random ints in a given range:
#include <random>
#include <iostream>
int main(void) {
std::random_device rd; // seed for PRNG
std::mt19937 mt_eng(rd()); // mersenne-twister engine initialised with seed
const int range_min = 10; // min of random interval
const int range_max = 15; // max of random interval
// uniform distribution for generating random integers in given range
std::uniform_int_distribution<> dist(range_min, range_max);
const int n = 10; // number of random int's to generate
// call dist(mt_eng) to generate a random int
for (int i = 0; i < n; ++i)
std::cout << dist(mt_eng) << ' ';
}
And, of course, you can randomise the value of n trivially via similar code to the above as well.
First of all, this generates numbers from 20 to 45 (exclusive):
random_integer = 20 + rand () % 25;
To fix it, use rand () % 30.
I need to generate a random amount of numbers between 10 to 15
Then generate a random number between 10 and 15 and iterate (with a loop) from 0 to that number:
int n = 10 + rand () % 5;
int *numbers = new int[n]; //array that stores the random numbers
for (int i = 0; i < n; i++)
numbers[i] = 20 + rand () % 30; //random number between 20 and 50
The key is your modulo-ing number and your starting number.
// rand() % 5 + 10 has a range of 10 to 10+5 (15)
// rand() % 30 + 20 has a range of 20 to 20+30 (50)
int numberCount = rand() % 5 + 10;
for(int i = 0; i < numberCount; ++i)
{
int randomNumber = rand() % 30 + 20;
cout << randomNumber << endl;
}
If you want inclusive, use 6 and 31 instead of 5 and 30.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
So first, we start with an array of 50. The range of the values within the array can be 1-100, not repeating. Then we display the highest value of that random array. Then we display the lowest value in the array. Then comes the sorting, which would be easy using the standard library functions in the <algorithm> header, but since it's not allowed, we need to find another way around it. Then sort from high to low.
So, to display this easily... First we start with an array[50] with random numbers between 1-100
72 29 11 41 31 27 21 46 43 40 17 45 30 32 25 15 19 88 22 24 51 34 99 23 26 37 1 4 2 9 33 44 12 39 38 3 47 48 5 42 49 18 54 55 87 16 28 20 50 9
Now we display the highest number
99
Then the lowest
1
The we sort them
1 2 3 4 5 9 9 11 12 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 54 55 72 87 88 99
Then reverse sort them
99 88 87 72 55 54 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 34 33 32 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 12 11 9 9 5 4 3 2 1
So.. how would I go about doing this without algorithms?
The usual way to do this is by using loops.
For example, to traverse an array, printing every element, we could use a loop like:
for (int i=0; i<50; i++) {
std::cout << array[i] << std::endl;
}
All of the problems you mention, except sorting, can be done using a simple loop like the one above. You'll have to do your own bookkeeping in order to solve the problems, but it shouldn't be too difficult.
As for sorting, that's a more challenging problem. You might start with the wikipedia article to see how that is handled. You probably want to try implementing selection sort.
You can use bitset sort since the range of values of the array is limited to 1-100, and there is no repetition you can have a bitset array of 100 ints where each index specifies can be a 0 (that number isn't in the array) or a 1 (the number is in the array). For example the array [1, 5, 3] can be represented by the bitset array [1, 0, 1, 0, 1].
pseudo code:
MAX_SIZE = 100
bitset = new int[MAX_SIZE]
smallest = biggest = -1
for each value in array {
smallest = value if value < smallest
biggest = value if value > biggest
bitset[value-1] = 1
}
sorted = (i for i in 0..bitset.length - 1 if bitset[i] == 1)
reverse_sorted = (sorted[i] for i in sorted.length-1..0)
Not very professional but works
int array[50], used[50], sortedArray[50], buildSort = 1, genNum, max = 0, min = 101;
bool x;
srand(time(0));
//Array Generator
for(int i = 0; i < 50; i++){
do{
genNum = (1+rand()%100);
x = false;
for(int j =0; j < 50; j++){
if(genNum == used[j]){
x = true;
}
}
}while(x == true);
used[i] = genNum;
array[i] = genNum;
}
cout << "Numbers: ";
for(int d = 0; d < 50; d++){
cout << array[d] << " ";
}
cout << endl << endl;
//Max and Min finder
for(int m = 0; m < 50; m++){
if(array[m] > max){
max = array[m];
}
if(array[m] < min){
min = array[m];
}
}
cout << "Max is: " << max << endl;
cout << "Min is: " << min << endl << endl;
//Sorting
sortedArray[0] = min;
for(int v = min+1; v <= max; v++){
for(int r = 0; r < 50; r++){
if(array[r] == v){
sortedArray[buildSort] = array[r];
buildSort++;
}
}
}
cout << "Sorted: ";
for(int k = 0; k < 50; k++){
cout << sortedArray[k] << " ";
}
cout << endl << endl;
cout << "Reverse sorting: ";
for(int l = 49; l >=0; l--){
cout << sortedArray[l] << " ";
}
Well, I have not checked this code and I'm sure it has some errors in it, but hopefully this will at least give you some ideas and a good base to go off of:
/******************
*
* Your array should have 51 spots.
* The last element should be 0.
*
******************/
uint8_t findMax(uint8_t *arrayToSearch){
// Your array should end in a sentinel value of 0
uint8_t highest = 0;
for(; *arrayToSearch; arrayToSearch++){
highest = (*arrayToSearch > highest) ? *arrayToSearch : highest;
}
return highest;
}
uint8_t findMin(uint8_t *arrayToSearch){
// Your array should end in a sentinel value of 0
uint8_t lowest = 101;
for(; *arrayToSearch; arrayToSearch++){
lowest = (*arrayToSearch < lowest) ? *arrayToSearch : lowest;
}
return lowest;
}
void sortAscending(uint8_t *arrayToSearch){
// sort from low to high
// get count of array (According to your question, it should be 50, but we'll verify)
unsigned short count = 0;
uint8_t *countingPoint;
countingPoint = arrayToSeach; // make countingPoint point to the first element
while(*countingPoint){
count++;
countingPoint++;
}
// now we'll create a second array
uint8_t sortedArray[count];
// now let's begin sorting.
unsigned long int totalIterations = 0;
while(totalIterations < count){
uint8_t currentSmallest = 101; // value which will not ever exist.
signed long int smallestIndex = -1;
unsigned short offset = 0;
uint8_t *startOfArray;
startOfArray = arrayToSearch;
for(; *startOfArray; *startOfArray++, offset++){
if(currentSmallest > *startOfArray){
smallestIndex = offset;
currentSmallest = *startOfArray;
}
} /* end for */
sortedArray[totalIterations] = currentSmallest;
*(smallestIndex + arrayToSearch) = 101; /* set the value above 100 so it will be
skipped in the next for loop */
totalIterations++;
} /* end while */
/* now we'll the sorted values to the array to search */
int i;
for(i=0; i < count; i++){
*(i+arrayToSearch) = sortedArray[i];
}
// and we're done.
}
/*
* We can actually write sortDescending the same way and just modify
* the last loop to put them in reverse order
*/
void sortDescending(uint8_t *arrayToSearch){
// sort from low to high and then order as high to low
// get count of array (According to your question, it should be 50, but we'll verify)
unsigned short count = 0;
uint8_t *countingPoint;
countingPoint = arrayToSeach; // make countingPoint point to the first element
while(*countingPoint){
count++;
countingPoint++;
}
// now we'll create a second array
uint8_t sortedArray[count];
// now let's begin sorting.
unsigned long int totalIterations = 0;
while(totalIterations < count){
uint8_t currentSmallest = 101; // value which will not ever exist.
signed long int smallestIndex = -1;
unsigned short offset = 0;
uint8_t *startOfArray;
startOfArray = arrayToSearch;
for(; *startOfArray; *startOfArray++, offset++){
if(currentSmallest > *startOfArray){
smallestIndex = offset;
currentSmallest = *startOfArray;
}
} /* end for */
sortedArray[totalIterations] = currentSmallest;
*(smallestIndex + arrayToSearch) = 101; /* set the value above 100 so it will be
skipped in the next for loop */
totalIterations++;
} /* end while */
/* now we'll copy the values to the arrayToSearch in reverse order */
int i;
for(i=(count-1); i >= 0; i--){
*(i+arrayToSearch) = sortedArray[i];
}
// and we're done.
}
/* calling these */
int main(){
uint8_t yourArray[51];
// ... your code to populate this array
yourArray[50] = 0; // set the last spot to 0.
uint8_t highest = findMax(yourArray);
uint8_t lowest = findMin(yourArray);
// now make yourArray sorted by lowest to highest
sortAscending(yourArray);
// ... Whatever you need to do with it in ascending order.
// now make it sorted by highest to lowest
sortDescending(yourArray);
// ... Whatever you need to do with it in descending order.
return 0;
}
I'm a C-programmer so this is a rather C-style answer.
Some additional information that might be helpful can be found at:
http://www.sanfoundry.com/c-program-sort-array-ascending-order/
http://www.programmingsimplified.com/c/source-code/c-program-bubble-sort
http://en.wikipedia.org/wiki/Sorting_algorithm
The Wikipedia page (last link) might seem a little overwhelming, but there is a lot of great content on it.
I hope this will be of some help to you. Again, I'm not sure if the code I included will work properly. It's merely meant to convey the general idea.