Given an array of start-times and end-times, sort them based on the end-times.
Here's what my function description looks like
// sort() - sorts an array of floats returning sorted indices
// On return, indx[] is an array of indices such that data[indx[0]],
// data[indx[1]], ..., data[indx[len-1]] is data[] in ascending order.
// Parameters
// data[] - float array of data to be ordered
// indx[] - int array, same length as data[], to hold indices
// len - int specifying the length of data[] and indx[]
and here's the code
#include<iostream>
#include<string>
#include sched.h
void sort(float data[], int indx[], int len);
int main() {
int indx[NUM_EVENTS];
int scheduledEvents[NUM_EVENTS];
int numSched;
// Sort by event ending times
sort(endTime, indx, NUM_EVENTS);
// Call greedy scheduling algorithm
numSched = sched(startTime, endTime, indx, scheduledEvents, NUM_EVENTS);
// Display scheduled events
for (int i = 0; i < numSched; i++)
printEvent(startTime[scheduledEvents[i]], endTime[scheduledEvents[i]],
description[scheduledEvents[i]]);
return 0;
}
my sorting algorithm inducing a for loop to check out the outputs
looks like
void sort(float data[], int indx[], int len){
for (int i = 0; i < 10; i++){
indx[i];
}
float smallestIndex;
bool flag = 1;
while (flag == 1){
flag == 2;
for (int i = 0; i < len-1; i++){
if (data[indx[i]] > data[indx[i + 1]]){
smallestIndex = indx[i + 1];
indx[i + 1] = indx[i];`
indx[i] = smallestIndex;
flag == 1;
}
}
}
for (int i = 0; i < 10;i++){
cout << data[indx[i]] << endl;
}
doing do I got an error that looks like
> warning C4806: '==' : unsafe operation: no value of type 'bool'
promoted to type 'int' can equal the given constant
1>sched.obj : error LNK2019: unresolved external symbol "void __cdecl
printEvent(float,float,class std::basic_string,class std::allocator >)"
(?printEvent##YAXMMV?$basic_string#DU?$char_traits#D#std##V?$allocator#D#2##std###Z)
referenced in function _main
bool is a type that usually accepts true and false. Internally it is handled as an int. That is why you can assign numeric values to it. However, if you would like to do this, use int.
Also notice that your line with:
flag == 2;
has no effect. You compare flag to 2 and the result of this comparison (either true or false) is just left in the air. This is not an error but the whole expression does not do anything.
The variable flag only ever holds one of two values, so this would work, leaving your other logic (may not be the most efficient), "as is."
bool flag = true;
while (flag == true){
flag = false; // Tentative "stop"
for (int i = 0; i < len-1; i++){
if (data[indx[i]] > data[indx[i + 1]]){
smallestIndex = indx[i + 1];
indx[i + 1] = indx[i];`
indx[i] = smallestIndex;
flag = true; // Keep going.
}
}
}
A bool can only be true or false, it is binary. You can assign 1 or 0 to an int to get the same result as if you had used a bool if you don't want to use a bool.
Also you use == which is to check equivalence. A single = is for assigning a number which it looks like you want to do when,
flag == 2;
It should be declared and int (or something similar)
int flag = 0;
flag = 2
Related
For empty vector Fun1 returns 0. Function Fun2, which should be equivalent to Fun1 (only one small change, see below), crashes with error vector subscript out of range. Any ideas why is that?
Code run in Visual Studio 2017
int Fun1(vector<int> service_times) {
sort(service_times.begin(), service_times.end());
int sum = 0;
int sumi = 0;
int st = service_times.size() - 1;//condition stired in variable
for (int i = 0; i < st; i++)
{
sumi += service_times[i];
sum = sum + sumi;
}
return sum;
}
int Fun2(vector<int> service_times) {
sort(service_times.begin(), service_times.end());
int sum = 0;
int sumi = 0;
for (int i = 0; i < (service_times.size() - 1); i++)//condition
//directly written
{
sumi += service_times[i];
sum = sum + sumi;
}
return sum;
}
Since service_times is an empty vector, service_times.size() ought to return 0, no?
No. It returns size_t(0), which is an unsigned type. Therefore, service_times.size() - 1 is a unsigned - signed operation, where the signed value (1) is "promoted" to unsigned type. Therefore, 0 - 1 is actually numeric_limits<size_t>::max().
In the first function, you saved it by storing it again in an int variable: it becomes -1 again. Therefore, i < st is i < -1, which worked incidentally. However, in the second function, i < st is actually i < <some ultra big value>, which, LOL.
I am trying to read through file that contains series of words and sentences.
Then, needs to Store the unique words and maintain a count of each different word.The words should be ordered by decreasing count and, if there are multiple
words with the same count, alphabetically. (This ordering may be achieved as
the words are read in, partially as the words are read or at the end of all input processing.)In the end, I want to Output the first and last ten words in the sorted list, along with their counts.
How to fix this const char* error. I dont know what is wrong in my code or where and what exactly do I have to change:
[Error] invalid conversion from 'char' to 'const char*' [-fpermissive]
[Error] no match for 'operator<=' (operand types are 'WordType' and 'WordType')
struct WordType
{
int word;
int len, count;
};
const int MaxWords=50000;
char Words[MaxWords*10];
WordType Counters[MaxWords];
int NumWords=0;
bool Compare(WordType &A, WordType &B){
if(A.count<B.count)return true;
if(A.count>B.count)return false;
char w1[50],w2[50];
strncpy(w1,Words[A.word],A.len); //Error comes here
w1[A.len]='\0';
w2[B.len]='\0';
strncpy(w2,Words[A.word],B.len); //Error comes here
return strcmp(w1,w2) < 0 ;
}
int partition (int low, int high)
{
WordType pivot = Counters[high];
int i = (low - 1);
for (int j = low; j <= high- 1; j++)
{
if (Compare(Counters[j] <= pivot)) //Error comes here
{
i++;
swap(&Words[i], &Words[j]);
}
}
swap(&Words[i + 1], &Words[high]);
return (i + 1);
}
void quickSort(int low, int high)
{
if (low < high)
{
int pi = partition(low, high);
quickSort(low, pi - 1);
quickSort(pi + 1, high);
}
}
(Whatever your intention with the code, I just looked at the 3 bugs)
This compare function solves the 1st & 2nd compile errors:
#include <string>
bool Compare(WordType &A, WordType &B)
{
if (A.count < B.count)
return true;
if (A.count > B.count)
return false;
std::string w1{ Words[A.word] }, w2{ Words[B.word] }; // Fix
return (strcmp(w1.c_str(), w2.c_str()) < 0);
}
The compare function gets 2 parameters, so I guess you actually want to call it like:
if (Compare(Counters[j], pivot)) // Fix
-
Beside that, I prefer to use std:array & to initialize variables:
#include <array>
struct WordType
{
int word = 0;
int len = 0, count = 0;
};
constexpr int MaxWords = 50000;
std::array<char, MaxWords * 10> Words;
std::array<WordType, MaxWords> Counters;
int NumWords = 0;
// & to call in main():
Words.fill('\0');
if (Compare(Counters[j] , pivot))
strncpy(w2,(const char *)Words[A.word],B.len);
strncpy(w2,(const char *)Words[A.word],B.len);
This is how your error line should look like
I am a C++ newbie.
Context: I found this third-party snippet of code that seems to work, but based on my (very limited) knowledge of C++ I suspect it will cause problems. The snippet is as follows:
int aVariable;
int anInt = 1;
int anotherInt = 2;
int lastInt = 3;
aVariable = CHAIN(anInt, anotherInt, lastInt);
Where CHAIN is defined as follows (this is part of a library):
int CHAIN(){ Map(&CHAIN, MakeProcInstance(&_CHAIN), MAP_IPTR_VPN); }
int _CHAIN(int i, int np, int p){ return ASMAlloc(np, p, &chainproc); }
int keyalloc[16384], kpos, alloc_locked, tmp[4];
int ASMAlloc(int np, int p, alias proc)
{
int v, x;
// if(alloc_locked) return 0 & printf("WARNING: you can declare compound key statements (SEQ, CHAIN, EXEC, TEMPO, AXIS) only inside main() call, and not during an event.\xa");
v = elements(&keyalloc) - kpos - 4;
if(v < np | !np) return 0; // not enough allocation space or no parameters
Map(&v, p); Dim(&v, np); // v = params array
keyalloc[kpos] = np + 4; // size
keyalloc[kpos+1] = &proc; // function
keyalloc[kpos+2] = kpos + 2 + np; // parameters index
while(x < np)
{
keyalloc[kpos+3+x] = v[x];
x = x+1;
}
keyalloc[kpos+3+np] = kpos + 3 | JUMP;
x = ASMFind(kpos);
if(x == kpos) kpos = kpos + np + 4;
return x + 1 | PROC; // skip block size
}
int ASMFind(int x)
{
int i, j, k; while(i < x)
{
k = i + keyalloc[i]; // next
if(keyalloc[i] == keyalloc[x]) // size
if(keyalloc[i+1] == keyalloc[x+1]) // proc
{
j = x-i;
i = i+3;
while(keyalloc[i] == keyalloc[j+i]) i = i+1; // param
if((keyalloc[i] & 0xffff0000) == JUMP) return x-j;
}
i = k;
}
return x;
}
EDIT:
The weird thing is that running
CHAIN(aVariable);
effectively executes
CHAIN(anInt, anotherInt, lastInt);
Somehow. This is what led me to believe that aVariable is, in fact, a pointer.
QUESTION:
Is it correct to store a parametrized function call into an integer variable like so? Does "aVariable" work just as a pointer, or is this likely to corrupt random memory areas?
You're calling a function (through an obfuscated interface), and storing the result in an integer. It might or might not cause problems, depending on how you use the value / what you expect it to mean.
Your example contains too many undefined symbols for the reader to provide any better answer.
Also, I think this is C, not C++ code.
example code:
const char* list[] = {"Elem_E", "Elem_T", "Elem_R", "Turtle", "Rabbit"};
const char ** patterns=0;
.
.
.
bool sec_run = false;
patterns = list;
process_data(patterns, sec_run);
process_data function:
process_data(const char **& pattern, bool sec_run){
.
.
some_variable=0;
for(int i; i < num_patterns;++i){
if(!sec_run){
some_variable = *pattern[i];
}
else{
if(/* list element contains "_" */)continue;
some_variable= /*letter after "_" */
}
if(some_variable == 'E') multiplier = 0;
else if(some_variable == 'T') multiplier = 1;
else if(some_variable == 'R') multiplier = 2;
}
}
So there is the base of what I'm trying to do. I cannot change signature for process_data. To start i do not get how some_variable = *pattern[i]; returns E,T, or R, and I cannot figure out how to iteratively access the full elements in the list. ie "Elem_E" to check for underscore and parse off the E.
I have little background in C++, but have used C numerous times. I am having a difficult time finding visual representation for char **& to help with based understanding of what is going on here, if you can point in the direction of a good tutorial with visual that will also suffice.
Sorry for confusion, forgot quotes in the list.
In C++, reading a parameter passed by reference (with the &) works the same as reading a parameter passed by value (without the &). The difference happens when you assign to the parameter. If the parameter was passed by value then the assignment is only visible inside the function but if it was passed by reference the assignment will be visible outside.
int mynumber = 0;
void foo(int &x)
{
printf("%d\n", x); //prints 0;
x = 10;
}
int main()
{
foo(mynumber);
printf("%d\n", mynumber); // prints 10
}
The equivalent to this in plain C would be to make the x parameter into a pointer and add the required *s and &s:
int mynumber = 0;
void foo(int *x)
{
printf("%d\n", *x);
*x = 10;
}
int main()
{
foo(&mynumber);
printf("%d\n", mynumber); // prints 10
}
Coming back to your code, I don't really know how to solve all your problems (what does the constant Elem_E mean? Is your list NULL terminated or is there a length stored somewhere?) but what I can say is that as long as you don't want to change the patterns global variable from inside process_data, using a char **& will be the same as using a char **.
I don't know how some_variable and multiplier will be used, but I made these changes to calculate them for each string in the list. The variable sec_run is not required in this approach. If no match is found, some_variable and multiplier are set to default values of '\0' and -1.
Output:
item=Elem_E some_variable=E multiplier=0
item=Elem_T some_variable=T multiplier=1
item=Elem_R some_variable=R multiplier=2
item=Turtle some_variable= multiplier=-1
item=Rabbit some_variable= multiplier=-1
Code:
void process_data(const char **& pattern, int num_patterns)
{
const char * item;
for (int i = 0; i < num_patterns; ++i)
{
item = pattern[i];
if ( item == NULL ) continue;
char some_variable = '\0'; // set to default for no match
int multiplier = -1; // set to default for no match
int len = strlen(item);
for (int j = 0; j < len; ++j)
{
if (item[j] == '_' && j + 1 < len)
some_variable = item[j + 1]; /*letter after "_" */
}
if (some_variable == 'E') multiplier = 0;
else if (some_variable == 'T') multiplier = 1;
else if (some_variable == 'R') multiplier = 2;
cout << "item=" << item << " some_variable=" << some_variable << " multiplier=" << multiplier << endl;
}
}
void pattern_test()
{
const char* list[] = { "Elem_E", "Elem_T", "Elem_R", "Turtle", "Rabbit" };
const char ** patterns = list;
// trick to calculate array length
// length of entire array divided by length of one element
int num_length = sizeof(list) / sizeof(list[0]);
process_data(patterns, num_length);
}
I am a beginer in programming. unfortunately I have a project in c++ that I don't know its problem. the program is a little long:
#include <iostream.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <alloc.h>
#include <time.h>
#include <math.h>
#include "vdsim.h"
void gen01dat( long, int);
void cnv_encd(int g[], long,int,int);
int main()
{
long data_len=10;
int *out_array;
long input_len=5;
int g[2][3];
void gen01dat(data_len,*out_array);
int in_array=*out_array;
void cnv_encd(g,input_len,in_array,*out_array);
cout<<"the out_array 2 is :\t"<<*out_array<<endl;
void gen01dat( long data_len, int *out_array ) {
long t; /* time */
/* re-seed the random number generator */
randomize();
/* generate the random data and write it to the output array */
for (t = 0; t < data_len; t++)
*( out_array + t ) = (int)( rand() / (RAND_MAX / 2) > 0.5 );
}
void cnv_encd(int g[2][k],long input_len, int *in_array,int *out_array)
{
int m; /* K - 1 */
long t, tt; /* bit time, symbol time */
int j, k; /* loop variables */
int *unencoded_data; /* pointer to data array */
int shift_reg[K]; /* the encoder shift register */
int sr_head; /* index to the first elt in the sr */
int p, q; /* the upper and lower xor gate outputs */
m = K - 1;
/* read in the data and store it in the array */
for (t = 0; t < input_len; t++)
*(unencoded_data + t) = *(in_array + t);
/* zero-pad the end of the data */
for (t = 0; t < m; t++) {
*(unencoded_data + input_len + t) = 0;
}
/* Initialize the shift register */
for (j = 0; j < K; j++) {
shift_reg[j] = 0;
}
sr_head = 0;
/* initialize the channel symbol output index */
tt = 0;
for (t = 0; t < input_len + m; t++) {
shift_reg[sr_head] = *( unencoded_data + t );
p = 0;
q = 0;
for (j = 0; j < K; j++) {
k = (j + sr_head) % K;
p ^= shift_reg[k] & g[0][j];
q ^= shift_reg[k] & g[1][j];
}
/* write the upper and lower xor gate outputs as channel symbols */
*(out_array + tt) = p;
tt = tt + 1;
*(out_array + tt) = q;
tt = tt + 1;
sr_head -= 1; /* equivalent to shifting everything right one place */
if (sr_head < 0) /* but make sure we adjust pointer modulo K */
sr_head = m;
}
/* free the dynamically allocated array */
free(unencoded_data);
}
return 0;
}
the compiler gives this error:
error: size of 'gen01'is unknown or zero in function main()
error: size of 'cnv_encd'is unknown or zero in function main()
I don't know this what does this error mean?
thanks for your help
You can't nest functions in C++, so try moving the definitions of cnv_encd() and gen01dat() out of main().
Also, you are calling the functions wrongly:
void gen01dat(data_len,*out_array);
should be
gen01dat(data_len,out_array);
and you do not initialise out_array before you use it (this is not a compile error, but it will make your program crash).
Your call to cnv_encd() is similarly wrong. Also you declare cnv_encd() to take different parameters in different places: compare the declaration before main() to the definition you give later on.
You are trying to call gen01dat & cnv_encd functions in main. However, your calling syntax is wrong.
void gen01dat(data_len,*out_array);
should just be
gen01dat(data_len,*out_array);
The same follows for the other function call also.
Looking at your code, even after you fix those, you are going to run into other warnings or errors. But since you are learning, I will let you figure them out for yourself.
Update: I did not see the nested functions within the main. Thats wrong too. Though, I suspect the missing closing brace is a typo.
the "void" keyword is only use when declaring a function. It tells the compiler that this function doesn't return any value.
So you only use it when declaring your functions and when implementing them. When you call them you just use it's name and arguments. Just like Aditya Sehgal pointed.
And you need to change your declarations. They must have the argument variable names in it, and not just the type of the variables.