I want a function or loop to run through the array and print each element out until it has printed 10 elements. In which case, a new line is started and the printing continues. eg. 1 2 3 4 5
6 7 8 9 10
This is for a program that works an array like a 50's housewife performing many calculations and alterations to said array.
This is my current attack on the logic behind my issue.
int main()
{
test = new int[100];
for (int i = 0; i < 100; i++){
//Set array to rand
test[i] = rand() % 44 + 55;
}
printf("original List\n");
for (int i = 0; i < 100; i++){
// print original order
printf("%d\n", test[i]);
}
sortArr;
// function call sort array ascend
printf("\Sorted List\n");
for (int i = 0;i < 100;i++) {
// print sorted order
printf("%d , ", test[i]);
int temp;
//temp counter for width of printout
for (temp = 0;temp < 10;temp++) cout<< "\n" << endl;
sum += test[i];
}
Expected is a block of output consisting of 100 array elements in a grid with a width of 10 elements per line.
Actual result is a mess of new line loops and further headache to me.
Pretty common issue just use a modulus based on the index i:
for (int i = 0;i < 100;i++) {
printf("%d , ", test[i]);
if ((i + 1) % 10 == 0) {
printf("\n");
}
}
If you want nicely formatted output however you'll need:
#include <iomanip>
and
std::cout << std::setw(/*max_len*/) << test[i];
The simplest solution would be to print the delimiter (i%10 == 0) ? "\n" : ", ". You correctly recognized that taking the remainder on every iteration of the loop is inefficient, and wanted to write one that would print ten elements followed by a newline.
The trick there is to write an inner loop that increments a second counter, j, do all your output within the inner loop, and then update i at the bottom of the outer loop. A simplified example:
#include <array>
#include <iostream>
#include <stdlib.h>
#include <time.h>
using std::cout;
int main()
{
constexpr size_t ARRAY_LEN = 100;
std::array<int, ARRAY_LEN> test;
{
// Quick and dirty initialization of the random seed to the lowest 30
// or so bits of the system clock, which probably does not really have
// nanosecond precision. It’ll do for this purpose.
timespec current_time;
timespec_get( ¤t_time, TIME_UTC );
srand(current_time.tv_nsec);
}
for (int i = 0; i < test.size(); i++){
//Set array to rand
test[i] = rand() % 44 + 55;
}
for ( int i = 0, j = 0;
i < test.size();
i += j ) {
for ( j = 0; j < 10 && i + j < test.size(); ++j ) {
cout << test[i + j] << ' ';
}
cout << '\n';
}
return EXIT_SUCCESS;
}
Note that the version you wrote does not initialize the standard library’s random seed, so you get the same (poorly-distributed) random numbers. You could write a version that uses the much superior STL random-number generators and perhaps <chrono>, instead of the C versions, but that’s a bit outside the scope of your question.
Related
c++
When printing to console, if function execution is sequential it would seem logical the ordered array would be printed after calling insertionSort, however order list does not print until next loop. Any help would be appreciated.
#include <stdio.h>
#include <iostream>
#include <array>
using namespace std;
void insertionSort(int* array, int size) {
for (int i = 1; i < size; i++) {
int key = i - 1;
while (i > 0 && array[key] > array[i] ) {
int tmp = array[i];
array[i] = array[key];
array[key] = tmp;
i -= 1;
key -= 1;
}
}
}
const int ARRAY_MAXSIZE = 5;
int main(void) {
int *array = (int*)calloc(ARRAY_MAXSIZE, sizeof(int));
int input;
cout << "Enter 5 digits\n";
for (int size=0; size < ARRAY_MAXSIZE; size++) {
cout << size << " index ";
cin >> input;
array[size] = input;
insertionSort(array, size);
for (int j=0; j <= size; j++) {
cout << array[j];
}
cout << '\n';
}
}
Console Entry
This is a classic off-by-one error. Your insertionSort expects you to pass the number of elements to sort via the parameter size. But your main loop is always holding a value that is one less than the size immediately after adding an element.
I want to say that bugs like this are easily discovered by stepping through your program's execution with a debugger. If you don't know how to use a debugger, start learning now. It is one of the most important tools used by developers.
Anyway, the quick fix is to change your function call to:
insertionSort(array, size + 1);
However, as Paul McKenzie pointed out in comments, it's a bit crazy to do this every time you add a new element because your function sorts an entire unsorted array. Your array is always nearly sorted except for the last element. You only need to call that function once after your input loop is done:
// Read unsorted data
for (int size = 0; size < ARRAY_MAXSIZE; size++) {
cout << size << " index ";
cin >> input;
array[size] = input;
}
// Sort everything
insertionSort(array, ARRAY_MAXSIZE);
// Output
for (int j = 0; j < ARRAY_MAXSIZE; j++) {
cout << array[j];
}
cout << '\n';
But if you want every insertion to result in a sorted array, you can "slide" each new value into place after inserting it. It's similar to a single iteration of your insertion-sort:
// Sort the last element into the correct position
for (int i = size; i >= 1 && array[i] > array[i - 1]; i--)
{
std::swap(array[i], array[i - 1]);
}
Even better, you don't need to swap all those values. You simply read the value, then shuffle the array contents over to make room, then stick it in the right spot:
// Read next value
cin >> input;
// Shuffle elements to make room for new value
int newPos = size;
while (newPos > 0 && array[newPos - 1] > input) {
array[newPos] - array[newPos - 1];
newPos--;
}
// Add the new value
array[newPos] = input;
The purpose of my code is to add the elements of a vector together into one integer. This is for Problem #1 on Project Euler:
https://projecteuler.net/problem=1
Here is my code:
int main()
{
int max_count = 1000; //The upper bound
//Loop for filling vector
for (int i = 1; i <= max_count; ++i){
int counter[max_count];
if (counter[i] % 3 == 0|| counter[i] % 5 == 0){
vector <int> start_point = {};
start_point.push_back (counter[i]);
for (auto& n : start_point){
int sum_of_elems = 0;
sum_of_elems += n;
cout << sum_of_elems;
}
}
}
return 0;
}
Currently, my code is outputting the following and I cannot figure out why.
32766143547943202305202750000-4646761603276630-76434810000-76434582500-464677056327662448-4646770403276632766-46467703232766327666032766230586999-970904238-95777621723084852023084852032766-970904244-46467688032766230624075-970911300230826120-1916976912327663276623063434032766230634681-957776214230826120140084992032766-970911280327660003276603276630-4646761603276623058081332766-464676440327663276632766230831712230745153065793306031200003276623074515300-191647711200023084852023074515365793360036000002308224802307451533657937207200-46467616032766000023083171232766230595552230831712032766327660-46467619232766230577342230822480230829920000-46467616032766230822480230829960-46467264032766230540223001920409600-46467247232766327661920409600-46467220832766000000000011072962560230556921230818160-4646738403276619204096000000230510592-1572142422000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001920169263100000170147416279176918919693827240000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
You're reinitializing your sum variable on each loop, so you end up just printing the individual values. You're also mixing looping and summing, which is complicating your code; either skip the vector entirely (just have a summing loop), or fill it completely, then sum it.
I can't give much more useful advice because you've got a lot of associated problems here. You declare counter without initializing it, then read from uninitialized memory to populate start_point.
Point is, most of your variables need to be declared outside the loops (so they're not repeatedly reinitialized from scratch on each loop), your output should be after the loops, and counter needs real data so you're not invoking undefined behavior.
Removing vectors and other unnecessary variables, the code can be simplified to:
#include <iostream>
int main()
{
int max_count = 1000; //The upper bound
int sumOfMultiples = 0;
for (int i = 1; i < max_count; ++i)
if (i % 3 == 0 || i % 5 == 0)
sumOfMultiples = sumOfMultiples + i;
std::cout << "Sum of Multiples of 3 and 5 below 1000 is: " << sumOfMultiples << "\n";
return 0;
}
Output is:
Sum of Multiples of 3 and 5 below 1000 is: 233168
One day, Twilight Sparkle is interested in how to sort a sequence of
integers a1, a2, ..., an in non-decreasing order. Being a young
unicorn, the only operation she can perform is a unit shift. That is,
she can move the last element of the sequence to its beginning:
a1, a2, ..., an → an, a1, a2, ..., an - 1. Help Twilight Sparkle to
calculate: what is the minimum number of operations that she needs to
sort the sequence?
Input
The first line contains an integer n (2 ≤ n ≤ 105). The second
line contains n integer numbers a1, a2, ..., an (1 ≤ ai ≤ 105).
Output
If it's impossible to sort the sequence output -1. Otherwise
output the minimum number of operations Twilight Sparkle needs to sort
it.
Examples
input
2
2 1
output
1
input
3
1 3 2
output
-1
input
2
1 2
output
0
Above is the problem and now I am confused because the solution down there used a variable called "s" and played around it for some reason but I don't know why was that variable used, if someone can tell me I'll be thankful.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n, s, v(0);
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++) cin >> a[i];
for (int i = 0; i < n - 1; i++) if (a[i] > a[i + 1]) s = i, v++;
if (a[n - 1] > a[0]) s = n - 1, v++;
if (v == 0) cout << 0 << endl;
else if (v > 1) cout << -1 << endl;
else cout << n - 1 - s << endl;
return 0;
}
Now here is my own solution, it works and everything except on a 10^5(and around that) size array but the question time limit is only 1000 ms, and mine exceeds that limit due to the nested loops making it go over O(10^8) which is 1000 ms on their systems.
#include <bits/stdc++.h>
#define fl(i,n) for(int i = 0; i < n; i++)
#define ll long long
#define nl endl
#define pb push_back
#define mp make_pair
#define PII pair<int,int>
#define EPS 1e-9
#define INF 1e9
using namespace std;
bool check(int a[], int n){
for(int i = 0; i < n-1; i++){
if(a[i] <= a[i+1]) continue;
return false;
}
return true;
}
int main()
{
int n;
cin >> n;
int a[n]; //is out of standard i know but it's accepted in the contest's compiler so we just use it
for(int i = 0; i < n; i++){
cin >> a[i];
}
if(check(a,n)){
cout << 0;
return 0;
}
int ret = 0;
for(int i = 0; i < n-1; i++){
ret++;
for(int j = n-1; j > 0; j--)
a[j] ^= a[j-1] ^= a[j] ^= a[j-1]; //is xor swap
if(check(a,n)){
cout << ret;
return 0;
}
}
cout << -1;
return 0;
}
PS: I TRACED the solution's code and even if I get the correct answers I simply don't know what it refers to.
The other person's implementation relies on an algorithmic insight. The only way a sequence can be sorted by moving back to front is if the sequence is made of two already-sorted sections. Then, the goal is to check how many unsorted discontinuities exist, and where they are. That's what s appears to be used for: the index of the (last) discontinuity of the sequence. v is the count of discontinuities.
If there are 0, it's already sorted. If more than 1, it's unsortable. If it's exactly one, then you can easily figure out how many shifts you need to perform to pull the discontinuity back to the front, using it's location (s) in the original sequence.
The only extra line of code is the special case of checking for the discontinuity around end of the sequence.
My recommendation: Generate a larger set of test sequences, and print v and s for each one.
I'm doing an assignment that involves calculating pi with threads. I've done this using mutex and it works fine, but I would like to get this version working as well. Here is my code.
#include <iostream>
#include <stdlib.h>
#include <iomanip>
#include <vector>
#include <pthread.h>
using namespace std;
typedef struct{
int iterations; //How many iterations this thread is going to do
int offset; //The offset multiplier for the calculations (Makes sure each thread calculates a different part of the formula)
}threadParameterList;
vector<double> partialSumList;
void* pi_calc(void* param){
threadParameterList* _param = static_cast<threadParameterList*>(param);
double k = 1.0;
for(int i = _param->iterations * _param->offset + 1; i < _param->iterations * (_param->offset + 1); ++i){
partialSumList[_param->offset] += (double)k*(4.0/((2.0*i)*(2.0*i+1.0)*(2.0*i+2.0)));
k *= -1.0;
}
pthread_exit(0);
}
int main(int argc, char* argv[]){
//Error checking
if(argc != 3){
cout << "error: two parameters required [iterations][threadcount]" << endl;
return -1;
}
if(atoi(argv[1]) <= 0 || atoi(argv[2]) <= 0){
cout << "error: invalid parameter supplied - parameters must be > 0." << endl;
return -1;
}
partialSumList.resize(atoi(argv[2]));
vector<pthread_t> threadList (atoi(argv[2]));
vector<threadParameterList> parameterList (atoi(argv[2]));
int iterations = atoi(argv[1]),
threadCount = atoi(argv[2]);
//Calculate workload for each thread
if(iterations % threadCount == 0){ //Threads divide evenly
for(int i = 0; i < threadCount; ++i){
parameterList[i].iterations = iterations/threadCount;
parameterList[i].offset = i;
pthread_create(&threadList[i], NULL, pi_calc, ¶meterList[i]);
}
void* status;
for(int i = 0; i < threadCount; ++i){
pthread_join(threadList[i], &status);
}
}
else{ //Threads do not divide evenly
for(int i = 0; i < threadCount - 1; ++i){
parameterList[i].iterations = iterations/threadCount;
parameterList[i].offset = i;
pthread_create(&threadList[i], NULL, pi_calc, ¶meterList[i]);
}
//Add the remainder to the last thread
parameterList[threadCount].iterations = (iterations % threadCount) + (iterations / threadCount);
parameterList[threadCount].offset = threadCount - 1;
pthread_create(&threadList[threadCount], NULL, pi_calc, ¶meterList[threadCount]);
void* status;
for(int i = 0; i < threadCount-1; ++i){
pthread_join(threadList[i], &status);
cout << status << endl;
}
}
//calculate pi
double pi = 3.0;
for(int i = 0; i < partialSumList.size(); ++i){
pi += partialSumList[i];
}
cout << "Value of pi: " << setw(15) << setprecision(15) << pi << endl;
return 0;
}
The code works fine in most cases. There are certain combinations of parameters that cause me to get a double free or corruption error on return 0. For example, if I use the parameters 100 and 10 the program creates 10 threads and does 10 iterations of the formula on each thread, works fine. If I use the parameters 10 and 4 the program creates 4 threads that do 2 iterations on 3 threads and 4 on the 4th thread, works fine. However, if I use 5 and 3, the program will correctly calculate the value and even print it out, but I get the error immediately after. This also happens for 17 and 3, and 10 and 3. I tried 15 and 7, but then I get a munmap_chunk(): invalid pointer error when the threads are trying to be joined - although i think that's something for another question.
If I had to guess, it has something to do with pthread_exit deallocating memory and then the same memory trying to be deallocated again on return, since I'm passing the parameter struct as a pointer. I tried a few different things like creating a local copy and defining parameterList as a vector of pointers, but it didn't solve anything. I've also tried eraseing and clearing the vector before return but that didn't help either.
I see this issue:
You are writing beyond the vector's bounds:
vector<threadParameterList> parameterList (atoi(argv[2]));
//...
int threadCount = atoi(argv[2]);
//...
parameterList[threadCount].iterations = (iterations % threadCount) + (iterations / threadCount);
parameterList[threadCount].offset = threadCount - 1;
Accessing parameterList[threadCount] is out of bounds.
I don't see in the code where threadCount is adjusted, so it remains the same value throughout that snippet.
Tip: If the goal is to access the last item in a container, use vector::back(). It works all the time for non-empty vectors.
parameterList.back().iterations = (iterations % threadCount) + (iterations / threadCount);
parameterList.back().offset = threadCount - 1;
One thing I can see is you might be going past the end of the vector here:
for(int i = 0; i < partialSumList.capacity(); ++i)
capacity() returns how many elements the vector can hold. This can be more than the size() of the vector. You can change you call to capacity() to size() to make sure you don't go past the end of the vector
for(int i = 0; i < partialSumList.size(); ++i)
The second thing I spot is that when iterations % threadCount != 0 you have:
parameterList[threadCount].iterations = (iterations % threadCount) + (iterations / threadCount);
parameterList[threadCount].offset = threadCount - 1;
pthread_create(&threadList[threadCount], NULL, pi_calc, ¶meterList[threadCount]);
Which is writing past the end of the vector. Then when you join all of the threads you don't join the last thread as you do:
for(int i = 0; i < threadCount-1; ++i){
^^^ uh oh. we missed the last thread
pthread_join(threadList[i], &status);
cout << status << endl;
}
I am trying to create a nested for loop that fills in values in an array from 1 to 20.
IE) array = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}
int array[20];
for(int i = 0; i<21; i++)
{
for(int j =1; j<21; j++)
{
array[i] = j;
cout<< array[i];
}
}
Supposedly, The array index should count up with "i", and should be equated to "j" which is also counting up. The array element is printed to the console as it is filled.
I expected 1 -20 to be printed out once, but when I run the code, 1-20 prints out multiple times. Can someone tell me the problem? Thanks!
Your outer for loop runs 21 times, your inner for loop runs 20 times each of the outer for loop iterations, so you have a total of 21 * 20 = 420 print statements.
You can simply do
for(int i = 0 ; i < array.length ; i++)
{
array[i] = i + 1;
cout << array[i] << endl;
}
If you look at your array when you're done, it will also be just a series of 20s. The first loop is saying "do this 20 times" and then the second loop is saying "set and print the value of that array element 20 times." What you need to do is include a check for whether you're assigning the correct j value to the correct array[i] value, and only set the value in that case. Something like:
if (j == i + 1) array[i] = j;
Why do you need a nested loop?
for(int i = 0; i<20; i++)
{
array[i] = i + 1;
cout<< array[i];
}
yes, you have two loops when you only need one:
for(int i = 0; i<21; i++)
{
array[i] = i + 1;
cout<< array[i];
}
In order to fill the array and to print the result you just need two simple for loops
for(int i = 0; i<20; i++)
{
array[i] = j;
}
for(int j =0; j<20; j++)
{
cout<< array[i];
}
The nested loop that you created above will do exactly what you described.
For each loop of the outer for loop it will execute the full 20 loops of the inner loop.
so in total you will execute it 21 * 20 times.
Also be careful with your index. You want to start with int i = 0 to i < 20 which loops exactly 20 times.
I don't know why you are attempting to print a single element in you array, but it isn't necessary to use nested loops here; in fact, a loop isn't required at all:
// vector version
std::vector<int> vec(20);
std::iota(vec.begin(), vec.end(), 1);
// array version
int arr[20];
std::iota(std::begin(arr), std::end(arr), 1);
If you want to print out the whole array after you've initialized it:
std::copy(vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, "\n"));
I see a lot of people answered about this question, so I will not repeat them, I'll just mention that you are writing outside the array size.
if you have int array[20], you should loop
for(int i = 0; i<20; i++)
the last index is 19
The outer loop 21 times repeats the inner loop
for(int i = 0; i<21; i++)
{
for(int j =1; j<21; j++)
{
array[i] = j;
cout<< array[i];
}
}
The inner loop does the same operation that is assigns elements of the array sequantial numbers. Moreover your code has a bug because due to the outer loop youare trying to access element array[20] that does not exist, because if the array was defined as
int arrat[20];
then the valid indicies are 0 - 19.
That do not bother about writing correctly required loop or loops you could use standard algorithm std::iota
For example
#include <iostream>
#include <numeric>
#include <iterator>
#include <algorithm>
int main()
{
const size_t N = 20;
int array[N];
std::iota( std::begin( array ), std::end( array ), 1 );
std::copy( std::begin( array ), std::end( array ), std::ostream_iterator<int>( std::cout, " " ) );
}
Or instead of the algorithms you could use the range based for statement. For example
#include <iostream>
int main()
{
const size_t N = 20;
int array[N];
int i = 1;
for ( int &x : array )
{
x = i++;
std::cout << x << ' ';
}
}
If you really want to use nested solution, (for example game board coordinates) then this is my solution.
// nesting arrays for example game board coordinates
#include <iostream>
int main(){
int x = 20;
int y = 40;
int array[x][y];
// initialize array of variable-sized.
for(int i = 0; i < x; ++i){
for(int j = 0; j < y; ++j){
array[i][j] = 0; // or something like i + j + (i * (y-1)) if you wish
// and send it to cout
std::cout << array[i][j] << " ";
}
std::cout << std::endl;
}
//notice, that when sent to cout like this, x and y flips on screen, but
//logics of coordinates is ok
// and then do something usefull with it
return EXIT_SUCCESS;
}
int size = 20;
for (int i = 0; i < size; i++)
{ int array[i];
array[i] = i + 1;
cout << array[i]<< " ";
}
You could populate your array with 1 for loop, and gauge the size of your array like stated above.