C++ Vector understanding - vector

I am currently using codewars.com to practice my coding skills. I finished one of the problems and wanted to check what other people's solutions were and I found one I couldn't understand. It's much better than my solution and I would like to understand it more. such what does "*std" do exactly. what is the +=i doing to the min_elements and what is happening to the min elements?
long queueTime(std::vector<int> customers,int n){
std::vector<long> queues(n, 0);
for (int i : customers)
*std::min_element(queues.begin(), queues.end()) += i;
return *std::max_element(queues.cbegin(), queues.cend());
}
This was my solution:
#include <iostream>
#include <vector>
#include <array>
using namespace std;
long queueTime(std::vector<int> customers,int n){
int i = 0; //start of Queue
int count = 0; //keeps track of how many items has been
processed
int biggest = 0; //Last/largest ending item size, add to count at end
int list [n]; //Declared number of registers by size n
for(int k = 0;k<n;k++) //sets each existing register to have 0
items
{
list[k] = 0;
}
//Start of processing customers, ends when last customer is at register.
for (auto i = customers.begin(); i!=customers.end();)
{
//checks if there are free registers.
for(int index = 0; index<n && i!=customers.end();index++)
{
if(list[index]==0)
{
list[index] = *i;
i++;
}
}
//Subtract 1 from every register
int temp=0;
for (int k =0;k<n;k++)
{
if(list[k]!= 0)
{
temp = list[k];
temp = temp-1;
list[k] = temp;
}
}
//increase count of items processed
count++;
}
//calculates the largest number of items a customer has amungst the last few
customers.
for(int j=0;j<n;j++)
{
if(list[j]>biggest)
{
biggest = list[j];
}
}
//end first part
cout<<"\nCount: "<<count<<" Biggest: "<<biggest<<endl;
cout<<"End Function:"
<<"\n************************\n***************************
*******************\n"<<endl;
//answer if number of items processed + last biggest number of items.
return count+biggest;
}

The code is mapping a set of integers to n buckets and minimizing the sum of the elements assigned to a given bucket.
For each customer int i , the smallest element of the queue is incremented by i. Then the largest resulting queue value is returned.
std::vector is a qualified name lookup of an identifier within the std namespace.
min_element returns an iterator. The dereference operator (*) produces an lvalue that is incremented by a compound assignment operator (+=).

Related

Correct Assignment for Pointers

I am shifting from Python to C so bit rusty on the semantics as well as coding habit. In Python everything is treated as an object and objects are passed to functions. This is not the case in C so I want to increment an integer using pointers. What is the correct assignment to do so. I want to do it the following way but have the assignments wrong:
#include <stdio.h>
int i = 24;
int increment(*i){
*i++;
return i;
}
int main() {
increment(&i);
printf("i = %d, i);
return 0;
}
I fixed your program:
#include <stdio.h>
int i = 24;
// changed from i to j in order to avoid confusion.
// note you could declare the return type as void instead
int increment(int *j){
(*j)++;
return *j;
}
int main() {
increment(&i);
printf("i = %d", i);
return 0;
}
Your main error was the missing int in the function's argument (also a missing " in the printf).
Also I would prefer using parentheses in expressions as *j++ and specify exactly the precedence like I did in (*j)++, because I want to increment the content of the variable in the 'j' location not to increment the pointer - meaning to point it on the next memory cell - and then use its content.

Arduino 'for' error

I have made a program for my Arduino which will sort an array of fifty random numbers in ascending or descending order, I think I have got it all right, but when I run it I get an error message "expected unqualified-id before 'for' ".
int array [50];
int i = 0;
void setup() {
Serial.begin(9600); // Load Serial Port
}
void loop() {
// put your main code here, to run repeatedly:
Serial.println ("Position " + array[i]);
delay (2000);
}
for (i <= 50) { <-----*Here is where the error highlights*--->
int n = random (251); // Random number from 0 to 250
array[i] = n;
i++;
}
// Bubble sort function
void sort (int a[], int size) {
for(int i=0; i<(size-1); i++) {
for(int o=0; o<(size-(i+1)); o++) {
if(a[o] > a[o+1]) {
int t = a[o];
a[o] = a[o+1];
a[o+1] = t;
}
}
}
}
I have annotated where the error is shown. I need to get past this to test my code, I have no clue on how to fix it!
You have written it wrong. There is pseudocode of for loop:
for(datatype variableName = initialValue; condition; operation){
//your in loop code
}
//Code wich will be executed after end of for loop above
In your case it will look like this:
for(int i = 0; i < 50 ; i++){
int n = random (251); // Random number from 0 to 250
array[i] = n;
}
Another thing is, that you are trying to iterate the array. The first index is 0. It means the last index is 49 not 50. If you try to access 50th index it will crash your program.
Last thing is, that the for loop we are talking about is out of any method. It will never be executed.
The for loop requires three parts to its parameters:
A variable to count iterations
A condition that must be true to continure
A increment factor
Each part should be separated by a semicolon
So your for loop should start out like this:
for(int i = 0;i <= 50; i++){
//code here
}
Official arduino For Loop Reference

Arduino Dynamic Two-dimensional array

I'm working on an Arduino project where I need to build (and work with) a two-dimensional array at runtime. I've been poking around looking for a solution, but I've had no luck. I found an example of a dynamic one-dimentional array helper here: http://playground.arduino.cc/Code/DynamicArrayHelper, so i've been trying to adopt that code for my use. I created a library using the following code:
My Header file:
#ifndef Dynamic2DArray_h
#define Dynamic2DArray_h
#include "Arduino.h"
class Dynamic2DArray
{
public:
Dynamic2DArray( bool sorted );
//Add an integer pair to the array
bool add( int v1, int v2);
//Clear out (empty) the array
bool clear();
//Get the array item in the specified row, column
int getValue(int row, int col);
//Get the number of rows in the array
int length();
private:
int _rows;
void * _slots;
bool _sorted;
void _sort();
};
#endif
The library's code:
#include "Arduino.h"
#include "Dynamic2DArray.h"
#define ARRAY_COLUMNS 2
int _rows;
void * _slots;
bool _sorted;
Dynamic2DArray::Dynamic2DArray(bool sorted) {
//Set our local value indicating where we're supposed to
//sort or not
_sorted = sorted;
//Initialize the row count so it starts at zero
_rows = 0;
}
bool Dynamic2DArray::add( int v1, int v2) {
//Add the values to the array
//implementation adapted from http://playground.arduino.cc/Code/DynamicArrayHelper
//Allocate memory based on the size of the current array rows plus one (the new row)
int elementSize = sizeof(int) * ARRAY_COLUMNS;
//calculate how much memory the current array is using
int currentBufferSize = elementSize * _rows;
//calculate how much memory the new array will use
int newBufferSize = elementSize * (_rows + 1);
//allocate memory for the new array (which should be bigger than the old one)
void * newArray = malloc ( newBufferSize );
//Does newArray not point to something (a memory address)?
if (newArray == 0) {
//Then malloc failed, so return false
return false;
}
// copy the data from the old array, to the new array
for (int idx = 0; idx < currentBufferSize ; idx++)
{
((byte*)newArray)[idx] = ((byte *)_slots)[idx];
}
// free the original array
if (_slots != NULL)
{
free(_slots);
}
// clear the newly allocated memory space (the new row)
for (int idx = currentBufferSize; idx < newBufferSize; idx++)
{
((byte *)newArray)[idx] = 0;
}
// Store the number of rows the memory is allocated for
_rows = ++_rows;
// set the array to the newly created array
_slots = newArray;
//Free up the memory used by the new array
free(newArray);
//If the array's supposed to be sorted,
//then sort it
if (_sorted) {
_sort();
}
// success
return true;
};
int Dynamic2DArray::length() {
return _rows;
};
bool Dynamic2DArray::clear() {
//Free up the memory allocated to the _slots array
free(_slots);
//And zero out the row count
_rows = 0;
};
int Dynamic2DArray::getValue(int row, int col) {
//do we have a valid row/col?
if ((row < _rows) && (col < ARRAY_COLUMNS)) {
//Return the array value at that row/col
return _slots[row][col];
} else {
//No? Then there's nothing we can do here
return -1;
}
};
//Sorted probably doesn't matter, I can probably ignore this one
void _sort() {
}
The initial assignment of the _slots value is giving me problems, I don't know how to define it so this code builds. The _slots variable is supposed to point to the dynamic array, but I've got it wrong.
When I try to compile the code into my project's code, I get the following:
Arduino: 1.8.0 (Windows 10), Board: "Pro Trinket 3V/12MHz (USB)"
sketch\Dynamic2DArray.cpp: In member function 'int Dynamic2DArray::getValue(int, int)':
sketch\Dynamic2DArray.cpp:83:22: warning: pointer of type 'void *' used in arithmetic [-Wpointer-arith]
return _slots[row][col];
^
Dynamic2DArray.cpp:83: error: 'void*' is not a pointer-to-object type
Can someone please help me fix this code? I've posted the files to https://github.com/johnwargo/Arduino-Dynamic-2D-Array-Lib.
The code you took was for a 1D dynamic array; the modifications for a 2D array are too tricky. Give up these horrors.
I think there is no reason you use dynamic array. You can assume that size max is ROW_MAX * COL_MAX, so you can define a static array int array[ROW_MAX][COL_MAX].
on one hand if you defined a dynamic array, you could free space when you dont use it anymore and take advantage of it for other work. I dont know if this is your case.
on the other hand if you define a static array (on UNO), you have 32kB available on program space, instead of 2kB available on RAM.
Because of the difference 32kB / 2kB, there are very few chances you can get bigger array with dynamic allocation.

Game of Life Processing

import processing.core.PApplet;
public class gl extends PApplet {
static int neighborCount;
static int screenRows;
int tNC; // Temporary Neighbor Count
int newState;
int columns = 960;
int rows = 477;
int[][] cells = new int[columns][rows];
int[][] newGen = new int[columns][rows];
public static void main(String[] args) {
PApplet.main("gl");
}
public void settings() {
size(1920, 955);
}
public void setup() {
// Set background white and all of cells[][] to 0 or 1
screenRows = 0;
background(255);
for (int j = 0; j < (rows / 2); j++) {
for (int i = 0; i < (columns / 2); i++) {
cells[i][j] = (int) random(0, 2);
}
}
}
public void draw() {
// If program has finished generating this frame, reset everything and set cells[][] equal to newGen[][]
if (screenRows > (height / 2)) {
screenRows = 0;
System.out.println("End of generation reached");
background(255);
cells = newGen.clone();
for (int i = 0; i < columns; i++) {
for (int j = 0; j < rows; j++) {
newGen[i][j] = 0;
}
}
}
// Go through every element in cells[][], determine it's value, and display it
for (int x = 1; x < (width / 2) - 1; x++) {
for (int y = 1; y < (height / 2) - 1; y++) {
printCell(x, y);
}
}
screenRows++;
}
public void printCell(int x, int y) {
setCellState(x, y);
if (newGen[x][y] == 0) {
stroke(255);
fill(255);
} else if (newGen[x][y] == 1) {
stroke(0);
fill(0);
}
System.out.println(x + ", " + y);
rect(x, y, 2, 2);
}
public void setCellState(int x, int y) {
tNC = getNeighborCount(x, y);
neighborCount = 0;
System.out.println(tNC);
if (tNC < 2) { // If less than 2 neighbors, cell dead
newGen[x][y] = 0;
} else if (tNC > 3) { // If more than 3 neighbors, cell dead
newGen[x][y] = 0;
} else if ((tNC == 2 || tNC == 3) && cells[x][y] == 1) { // If 2 or 3 neighbors and cell is alive, do nothing (unnecessary statement but makes visualizing easier)
} else if (tNC == 3 && cells[x][y] == 0) { // If 3 neighbors and cell is dead, cell is alive
newGen[x][y] = 1;
} else if (tNC == 2 && cells[x][y] == 0) { // If 2 neighbors and cel is dead, do nothing (also unnecessary)
} else {
System.out.println("Error in setCellState(int, int);"); // In event of none of the conditions being met
}
tNC = 0; // Reset variable (probably unnecessary but might as well)
}
public int getNeighborCount(int x, int y) {
// Go through each cell adjacent or diagonal to the cell and add it's value (0 or 1) to neighborCount
for (int i = -1; i < 2; i++) {
for (int j = -1; j < 2; j++) {
neighborCount += cells[i + x][j + y];
}
}
// Subtract the value of the cell being evaluated from neighborCount as that is not a factor in the sum of the neighbors
neighborCount -= cells[x][y];
return neighborCount;
}
}
Pastebin
I am just going for functionality over speed, for now.
I am attempting to code Conway's Game of Life using Processing in Eclipse. The above code is dysfunctional in multiple ways:
The generation displayed appears much smaller in the window than I want to be. It only takes up a fraction of the window despite my efforts to counterbalance this by making each cell 2x2 pixels and half as many rows and columns as the window is tall and wide.
Also, the generation does not appear to update in the window after the first generation is displayed after a few seconds.
I noticed that the variable tNC is often equal to 0 when it should be equal to any number from 0 to 7.
You've got three main problems.
Problem 1: You seem to be generating the next generation as you render cells, which might be okay... but then what are you doing with the screenRows logic (the if statement in your draw() function)?
If I were you, I would split your logic up into two sections: write one function that draws your board, and another function that returns a new board based on the current one. Stop trying to calculate the next generation as you're drawing the current generation, as that's just going to give you a ton of headaches.
I also don't think your logic for switching between the arrays is correct. Which array holds the current generation, and which holds the next generation? Are you sure?
Problem 2: You seem to be switching between pixel sizes and array coordinates. For example, you're drawing each cell at its array index coordinate, but you're drawing them as 2x2 rectangles. This doesn't make a ton of sense, since you're just going to draw over top of it with the next cell anyway. Again, separate your logic: create a function that draws a cell based on the window width and height, an array position, and an array length.
Problem 3: Your print statements are killing your framerate. Print statements are notoriously slow. Your framerate is already pretty slow because of all of the calculations you're doing, but it gets even slower when you print out (960*477*2) things every single frame. This isn't really a logic error, but it makes it harder to see exactly what your program is doing.
The Solution: To fix your problems, I'd recommend refactoring your code quite a bit. If I were you, I would start over with a new program. Then:
Step 1: Separate your drawing logic from your logic for calculating the next generation. Create two functions: one for drawing, and another one that returns a new array based on the current one.
Step 2: In your drawing code, make sure you separate your array indexes and your pixel positions. Maybe write another function that takes a cell position and draws a rectangle based on the window size and the array size.
PS: Are you in the same class as this person? Are you using Daniel Shiffman's code too?

Base case condition in quick sort algorithm

For the quick sort algorithm(recursive), every time when it calls itself, it have the condition if(p < r). Please correct me if I am wrong: as far as I know, for every recursive algorithm, it has a condition as the time when it entered the routine, and this condition is used to get the base case. But I still cannot understand how to correctly set and test this condition ?
void quickSort(int* arr, int p, int r)
{
if(p < r)
{
int q = partition(arr,p,r);
quickSort(arr,p,q-1);
quickSort(arr,q+1,r);
}
}
For my entire code, please refer to the following:
/*
filename : main.c
description: quickSort algorithm
*/
#include<iostream>
using namespace std;
void exchange(int* val1, int* val2)
{
int temp = *val1;
*val1 = *val2;
*val2 = temp;
}
int partition(int* arr, int p, int r)
{
int x = arr[r];
int j = p;
int i = j-1;
while(j<=r-1)
{
if(arr[j] <= x)
{
i++;
// exchange arr[r] with arr[j]
exchange(&arr[i],&arr[j]);
}
j++;
}
exchange(&arr[i+1],&arr[r]);
return i+1;
}
void quickSort(int* arr, int p, int r)
{
if(p < r)
{
int q = partition(arr,p,r);
quickSort(arr,p,q-1);
quickSort(arr,q+1,r);
}
}
// driver program to test the quick sort algorithm
int main(int argc, const char* argv[])
{
int arr1[] = {13,19,9,5,12,8,7,4,21,2,6,11};
cout <<"The original array is: ";
for(int i=0; i<12; i++)
{
cout << arr1[i] << " ";
}
cout << "\n";
quickSort(arr1,0,11);
//print out the sorted array
cout <<"The sorted array is: ";
for(int i=0; i<12; i++)
{
cout << arr1[i] << " ";
}
cout << "\n";
cin.get();
return 0;
}
Your question is not quite clear, but I will try to answer.
Quicksort works by sorting smaller and smaller arrays. The base case is an array with less than 2 elements because no sorting would be required.
At each step it finds a partition value and makes it true that all the values to the left of the partition value are smaller and all values to the right of the partition value are larger. In other words, it puts the partition value in the correct place. Then it recursively sorts the array to the left of the partition and the array to right of the partition.
The base case of quicksort is an array with one element because a one element array requires no sorting. In your code, p is the index of the first element and r is the index of the last element. The predicate p < r is only true for an array of at least size 2. In other words, if p >= r then you have an array of size 1 (or zero, or nonsense) and there is no work to do.

Resources