display 25 randomnumbers from an array - c++

I have in C++ an array of 100 elements, so v[1], ... ,v[100] contains numbers. How can i display, 25 random numbers from this array? So i wanna select 25 random positions from this array and display the values.. How can i do this in C++?
Thanks!
#include <cstdlib>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#include <time.h>
#include <vector>
using namespace std;
int aleator(int n)
{
return (rand()%n)+1;
}
int main()
{
int r;
int indexes[100]={0};
// const int size=100;
//int a[size];
std::vector<int>v;
srand(time(0));
for (int i=0;i<25;i++)
{
int index = aleator(100);
if (indexes[index] != 0)
{
// try again
i--;
continue;
}
indexes[index] = 1;
cout << v[index] ;
}
cout<<" "<<endl;
system("pause");
return 0;
}
The idea is that i have this code, and i generate 100 random numbers. What i want is an array with random 25 elements from those 100 generated.. But i don't know how to do that
Regards

Short Answer
Use std::random_shuffle(v.begin(),v.end()) to shuffle the array, and then display the first 25 elements.
Long Answer
First of all, the elements would be v[0]...v[99] (C++ uses 0-based indexing), not v[1]...v[100]. To answer your question, though, it depends on whether it is acceptable to repeat elements of the array or not. If you aren't worried about repeats, then simply use the index rand()%v.size(), repeatedly until you have selected a sufficient number of indices (25 in your question). If repeats are not acceptable, then you need to shuffle the array (by swapping elements at random), and then display the first (or last, or any contiguous region of) N elements (in this case N=25). You can use std::random_shuffle to shuffle the array. That does the bulk of the work for you. Once you've done that, just show 25 elements.

If you want to print 25 numbers of an array V you can use this code do:
int V[100]={1,2,5,...} ;
srand ( time (0) ) ;
for (int i=0;i<25;i++)
{
cout << V[rand() % 100 + 1]<<" " ;
}

I modified the version of Mehdi a little in order to make it choose differnet indexes
NOTE: This makes the algorithm not deterministic - it relies on the RNG.
int indexes[100]={0};
srand ( time (0) );
for (int i=0;i<25;i++)
{
int index = rand() % 100;
if (indexes[index] != 0)
{
// try again
i--;
continue;
}
indexes[index] = 1;
cout << v[index] ; cout << endl;
}

Related

How to find Minimum Maximum sum c++

I've written some code in c++ that is meant to find the minimum and maximum values that can be calculated by summing 4 of the 5 integers presented in an array. My thinking was that I could add up all elements of the array and loop through subtracting each of the elements to figure out which subtraction would lead to the smallest and largest totals. I know this isn't the smartest way to do it, but I'm just curious why this brute force method isn't working when I code it. Any feedback would be very much appreciated.
#include <iostream>
#include <vector>
#include <limits.h>
using namespace std;
void minimaxsum(vector<int> arr){
int i,j,temp;
int n=sizeof(arr);
int sum=0;
int low=INT_MAX;
int high=0;
for (j=0;j<n;j++){
for (i=0;i<n;i++){
sum+=arr[i];
}
temp=sum-arr[j];
if(temp<low){
low=temp;
}
else if(temp>high){
high=temp;
}
}
cout<<low;
cout<<high<<endl;
}
int main (){
vector<int> arr;
arr.push_back(1.0);
arr.push_back(2.0);
arr.push_back(3.0);
arr.push_back(1.0);
arr.push_back(2.0);
minimaxsum(arr);
return 0;
}
There are 2 problems.
Your code is unfortunately buggy and cannot deliver the correct result.
The solution approach, the design is wrong
I will show you what is wrong and how it could be refactored.
But first and most important: Before you start coding, you need to think. At least 1 day. After that, take a piece of paper and sketch your solution idea. Refactor this idea several times, which will take a complete additional day.
Then, start to write your code. This will take 3 minutes and if you do it with high quality, then it takes 10 minutes.
Let us look first at you code. I will add comments in the source code to indicate some of the problems. Please see:
#include <iostream>
#include <vector>
#include <limits.h> // Do not use .h include files from C-language. Use limits
using namespace std; // Never open the complete std-namepsace. Use fully qualified names
void minimaxsum(vector<int> arr) { // Pass per reference and not per value to avoid copies
int i, j, temp; // Always define variables when you need them, not before. Always initialize
int n = sizeof(arr); // This will not work. You mean "arr.size();"
int sum = 0;
int low = INT_MAX; // Use numeric_limits from C++
int high = 0; // Initialize with MIN value. Otherwise it will fail for negative integers
for (j = 0; j < n; j++) { // It is not understandable, why you use a nested loop, using the same parameters
for (i = 0; i < n; i++) { // Outside sum should be calculated only once
sum += arr[i]; // You will sum up always. Sum is never reset
}
temp = sum - arr[j];
if (temp < low) {
low = temp;
}
else if (temp > high) {
high = temp;
}
}
cout << low; // You miss a '\n' at the end
cout << high << endl; // endl is not necessary for cout. '\n' is sufficent
}
int main() {
vector<int> arr; // use an initializer list
arr.push_back(1.0); // Do not push back doubles into an integer vector
arr.push_back(2.0);
arr.push_back(3.0);
arr.push_back(1.0);
arr.push_back(2.0);
minimaxsum(arr);
return 0;
}
Basically your idea to subtract only one value from the overall sum is correct. But there is not need to calculate the overall sum all the time.
Refactoring your code to a working, but still not an optimal C++ solution could look like:
#include <iostream>
#include <vector>
#include <limits>
// Function to show the min and max sum from 4 out of 5 values
void minimaxsum(std::vector<int>& arr) {
// Initialize the resulting values in a way, the the first comparison will always be true
int low = std::numeric_limits<int>::max();
int high = std::numeric_limits<int>::min();;
// Calculate the sum of all 5 values
int sumOf5 = 0;
for (const int i : arr)
sumOf5 += i;
// Now subtract one value from the sum of 5
for (const int i : arr) {
if (sumOf5 - i < low) // Check for new min
low = sumOf5 - i;
if (sumOf5 - i > high) // Check for new max
high = sumOf5 - i;
}
std::cout << "Min: " << low << "\tMax: " << high << '\n';
}
int main() {
std::vector<int> arr{ 1,2,3,1,2 }; // The test Data
minimaxsum(arr); // Show min and max result
}

Printing an array in reverse

Task
You'll be given an array of N integers and you have to print the integers in the reverse order.
Constraints
1<=N<=1000
1<=A_i<=10000, where A_i is the ith integer in the array.
Input
4
1 2 3 4
Output
4 3 2 1
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int N, y; //declaring N as the length of array
cin >> N; //intakes the length as an input
if (N>=1 && N<=1000){ //checks whether the length satisfies the rules
int a[N]; // makes an array containing N elements
for (int x =1; x<N; x++){ //starts transcription on the array
cin>>y; //temporarily assigns the input on a variable
if (y>=1&&y<=10000){ //checks if the input meets rules
a[x]=y; //copies the variable on the array
}
}
for (int z = N; z>1; z--){ //runs a loop to print in reverse
cout<<a[z]<<endl;
}
}
return 0;
}
Problem
Obtained output is
-1249504352
3
2
Indicating an error in transcription.
Question
Can somebody please tell me where I am making a mistake? Secondly, is it possible to directly check whether an input is meeting requirement rather than temporarily declaring a variable for it?
Here is a solution in idiomatic c++11, using std::vector, which is a dynamically resizable container useful for applications like this.
#include <vector>
#include <iostream>
#include <algorithm>
int main() {
int size;
std::cin >> size; // take in the length as an input
// check that the input satisfies the requirements,
// use the return code to indicate a problem
if (size < 1 || size > 1000) return 1;
std::vector<int> numbers; // initialise a vector to hold the 'array'
numbers.reserve(size); // reserve space for all the inputs
for (int i = 0; i < size; i++) {
int num;
std::cin >> num; // take in the next number as an input
if (num < 1 || num > 10000) return 1;
numbers.push_back(num);
}
std::reverse(numbers.begin(), numbers.end()); // reverse the vector
// print each number in the vector
for (auto &num : numbers) {
std::cout << num << "\n";
}
return 0;
}
A few things to note:
using namespace std is considered bad practice most of the time. Use (e.g.) std::cin instead for things which come from the std namespace.
numbers.reserve(size) is not necessary for correctness, but will make the program faster by reserving space in advance.
for ( auto &num : numbers ) uses a range-based for loop, available in c++11 and later versions.
You could make your for loop indices go from high to low:
for (int i = N-1; i > 0; --i)
{
std::cout << a[i] << "\n"; // Replace '\n' with space for horizontal printing.
}
std::cout << "\n";
This would apply with std::vector as well.
With std::vector, you can use a reverse iterator. There are other techniques available (as in other answers).

Copying elements from one array to another c++

I have looked and looked and am still lost on how to copy or get elements from an array and put them into new arrays ( divide and conquer is the goal).
I have an array that generates 100 random numbers. I need to split the random numbers into 4 smaller arrays obviously containing 25 elements and not have any duplicates. I have read about using pointers, but honestly I don't understand why even use a pointer. Why do I care about another variables address?
I don't know how to do this. Here is my code so far:
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
// Seed the random number generator
srand(time(NULL));
//create an array to store our random numbers in
int Orignumbers[100] = {};
// Arrays for the divide and conquer method
int NumbersA [25] = {};
int NumbersB [25] = {};
int NumbersC [25] = {};
int NumbersD [25] = {};
//Generate the random numbers
for(int i =0; i < 100; i++)
{
int SomeRandomNumber = rand() % 100 + 1;
// Throw random number into the array
Orignumbers[i] = SomeRandomNumber;
}
// for(int i = 0; i < ) started the for loop for the other arrays, this is where I am stuck!!
// Print out the random numbers
for(int i = 0; i < 100; i++)
{
cout << Orignumbers[i] << " , ";
}
}
"divide and conquer" is rather easy; when copying into NumbersA and so forth, you just have to access your Originnumbers with a proper offset, i.e. 0, 25, 50, and 75:
for(int i = 0; i < 25; i++) {
NumbersA[i] = Orignumbers[i];
NumbersB[i] = Orignumbers[i+25];
NumbersC[i] = Orignumbers[i+50];
NumbersD[i] = Orignumbers[i+75];
}
The thing about "no duplicates" is a little bit more tricky. Generating a random sequence of unique numbers is usually solved through "shuffling". Standard library provides functions for that:
#include <random>
#include <algorithm>
#include <iterator>
#include <vector>
int main()
{
std::random_device rd;
std::mt19937 g(rd());
int Orignumbers[100];
//Generate the random numbers without duplicates
for(int i =0; i < 100; i++) {
Orignumbers[i] = i+1;
}
std::shuffle(Orignumbers, Orignumbers+100, g);
// Arrays for the divide and conquer method
int NumbersA [25] = {};
int NumbersB [25] = {};
int NumbersC [25] = {};
int NumbersD [25] = {};
for(int i = 0; i < 25; i++) {
NumbersA[i] = Orignumbers[i];
NumbersB[i] = Orignumbers[i+25];
NumbersC[i] = Orignumbers[i+50];
NumbersD[i] = Orignumbers[i+75];
}
// Print out the random numbers
for(int i = 0; i < 100; i++)
{
cout << Orignumbers[i] << " , ";
}
}
Problem:
The program can't be guaranteed to have no duplicate value as the rand() function can generate any random sequence and that may include the decimal value of 99 for 99 times though probability is very low but chances are.
Example:
for(loop=0; loop<9; loop++)
printf("%d", Rand()%10);
If looped for 10 times, it may result some values like:
Output: 6,1,1,1,2,9,1,3,6,9
Compiled Successfully:
Hence, no certainity that values won't repeat
Possibly Solution:
There could be a solution where you can place the values in OriginalArray and compare the rand() generate values against the OriginalArray values.
For first iteration of loop, you can directly assign value to OriginalArray then from 2nd iteration of loop you've to compare rand() value against OriginalArray but insertion time consumption may be higher than O(NN) as rand() function may repeat values.
Possibly Solution:
#include <iostream>
#include <time.h>
#include <stdlib.h>
using namespace std;
int main()
{
int Orignumbers[100] ;
int NumbersA [25] ,
NumbersB [25] ,
NumbersC [25] ,
NumbersD [25] ;
srand(time(NULL));
for(int i =0; i < 100; i++){
Orignumbers[i] = rand() % 100+1;
for(int loop=0; loop<i; loop++) {
if(Orignumber[loop] == Orignumber[i] ) {
i--;
break;
}
}
}
//Placing in four different arrays thats maybe needed.
for(int i = 0; i <25; i++ ) {
NumbersA[i] = Orignumbers[i];
NumbersB[i] = Orignumbers[i+25];
NumbersC[i] = Orignumbers[i+50];
NumbersD[i] = Orignumbers[i+75];
}
for(int i = 0; i < 99; i++)
cout << Orignumbers[i] << " , ";
}
As you tagged your question with C++ then forget about old-fashion arrays, let's do it C++ style.
You want to split your array into 4 arrays and they should not have duplicate numbers, so you can't have a number 5 times in your original array, because then surely one of your 4 arrays will have a duplicate one, So here is the way I propose to do it :
#include <set>
#include <ctime>
#include <vector>
int main() {
std::multiset<int> allNums;
std::srand(unsigned(std::time(0)));
for (int i = 0; i < 100; ++i) {
int SomeRandomNumber = std::rand() % 100 + 1;
if (allNums.count(SomeRandomNumber) < 4) {
allNums.insert(SomeRandomNumber);
}
else {
--i;
}
}
std::vector<int> vOne, vTwo, vThree, vFour;
for (auto iter = allNums.begin(); iter != allNums.end(); ++iter) {
vOne.push_back(*iter);
++iter;
vTwo.push_back(*iter);
++iter;
vThree.push_back(*iter);
++iter;
vFour.push_back(*iter);
}
system("pause");
return 0;
}
EDIT : As you mentioned in the comments, you just want to find a number in an array, so how about this :
for (int i = 0; i < 100; ++i) {
if (origArray[i] == magicNumber) {
cout << "magicNumber founded in index " << i << "of origArray";
}
}
On some situations, even on C++, the use of arrays might be preferable than vectors, for example, when dealing with multidimensional arrays (2D, 3D, etc) that needs to be continuous and ordered on the memory. (e.g. later access by other applications or faster exporting to file using formats such as HDF5.)
Like Jesper pointed out, you may use Copy and I would add MemCopy to copy the content of an array or memory block into another.
Don't underestimate the importance of pointers, they may solve your problem without the need doing any copy. A bit like Stephan solution but without the need of the index variable "i", just having the pointers initialized at different places on the array. For a very large number of elements, such strategy will save some relevant processing time.

How to get largest value after leaving one array value?

i am currently having problem getting largest values from an array, here is my code:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a[10],max=0,j,secondbig=0;
for(int i=0;i<10;i++)
{
cin>>a[i];
}
max = a[0];
for(int i=0;i<10;i++)
{
if(a[i]>max){
max=a[i];
j=i;
}
}
secondbig=a[10-j-1];
for(int i=0;i<10;i++)
{
if(secondbig <a[i] && j != i)
secondbig =a[i];
}
cout<<max<<"\n"<<secondbig;
return 0;
}
What i want to do is to first get maximum value from an array and then leave one array value and then get second largest value and same for third largest value, for example :
200
100
50
300
400
500
600
700
800
900
If in the above test values 900 is the largest value then the subsequent second and third largest value should be 700 and 500, is there anyway to do that?
maybe you can sort the array
int *pbeg = begin(a);
int *pend = end(a);
sort(pbeg, pend);
this will sort all elements in the range[pbeg, pend) with operator <,
or sort all elements by using the binary predicate
Given your original code, I presume this is in the style of what you were attempting. it will retrun the three highest vaule. Notice that you only needed to create a loop to repeat the inital computation. You want the max remaining value less than the prior max value.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <limits>
using namespace std;
int main()
{
int a[10], max, prior_max = numeric_limits<int>::max();
for(int i=0;i<10;i++)
{
cin>>a[i];
}
for( int j = 0; j<3; j++){
max = numeric_limits<int>::min();
for(int i=0;i<10;i++)
{
if(a[i]>max && a[i]<prior_max){
max=a[i];
}
}
cout << max << endl;
prior_max = max;
}
return 0;
}
Assuming that you're happy to get the values in place, I'd use a vector.
std::sort(std::begin(a), std::end(a), std::greater<int>());
then print or copy the first n elements of the array (assuming n is no more than your array size, 10). They will be in reverse order, but that can be easily corrected.
As per your follow on question, If you want to list all the max values, change the j<3 to j<10. If you want the numeric sum of the max values that you have extracted from the array, you need to add one more variable:
int a[10], total, max, prior_max = numeric_limits<int>::max();
then within the outer loop, place at the end of the inner loop this statement:
total += max;
Then after the execution of the loops are complete, you can print out the total or otherwise use it. as in:
cout << 'Total: ' << total << endl;

c++ random number generation not random

I'm trying to perform a random shuffle of a vector using Visual Studio 2013 C++. The following is the code that I have
static void shuffle(vector<int>& a){
int N = a.size();
unsigned long long seed = chrono::system_clock::now().time_since_epoch().count();
default_random_engine generator(seed);
for (int i = 0; i < N; i++){
uniform_int_distribution<int> distribution(0,(N-1)-i);
int r = i + distribution(generator);
swap(a[i], a[r]);
}
}
My problem is when I call this method multiple times in succession the shuffle is not random. What could be wrong with the code?
Any help would be much appreciated.
Uhm, I'm curious... why isn't the following sufficient for your needs:
static void shuffle(vector<int>& a)
{
// There are better options for a seed here, but this is what you used
// in your example and it's not horrible, so we'll stick with it.
auto seed (std::chrono::system_clock::now().time_since_epoch().count());
// Don't bother writing code to swap the elements. Just ask the standard
// library to shuffle the vector for us.
std::shuffle(std::begin(a), std::end(a), std::default_random_engine(seed));
}
std::shuffle dosent remove duplicates, it just swaps the positions of the random numbers generated.
How can I efficiently select several unique random numbers from 1 to 50, excluding x?
You can home cook your own shuffle code otherwise:
#include <ctime>
#include <string>
#include <vector>
#include <iostream>
using namespace std;
void myShuffleWithNoRepeats( int random_once_buf[] , int size=100)
{
srand(time(0));
for (int i=0;i<size;i++)
{
// call made to rand( ) , stored in random_once_buf[ ]
random_once_buf[i]=rand() % 100;
//////////////////////////////////////////////////////////////////////////////////////
// The line below generates unique random number only once //
// //
// the variable i is the random_once_buffer[i] buffer array index count, //
// j is the check for duplicates, j goes through the random_once_buffer[i] buffer //
// from 0 to i at every iteration scanning for duplicates, reversing one step if one duplicate is found.. //
//////////////////////////////////////////////////////////////////////////////////////
for(int j=0;j<i;j++) if (random_once_buf[j] == random_once_buf[i]) i--;
}
cout<<" \n\n\n ";
}
int main(void)
{
const int size=100 ;
int random_once_buffer[100] ;
// Call made to function myShuffleWithNoRepeats( )
myShuffleWithNoRepeats( random_once_buffer , size );
// Loop to display the array random_once_buffer[ ]
for ( int i=0;i<size;i++) cout<<""<<random_once_buffer[i]<<"\t";
cout<<" \nPress any key to continue\n";
cin.ignore();
cin.get();
return 0;
}