• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

All you need to do is just find the new line ('\n' on Linux/Unix or '\r' followed by '\n' on windows) and replace it with something else. Since the character(s) you want to replace will be at the end of the string, it is safe to replace it/them with null bytes, since (if I understand what you're doing correctly) there is nothing in the string after them that you have to worry about.

I keep trying this but it doesn't seem to be working. I'm fucking so lost.

I'm doing this:
Code:
array[a] = malloc(strlen(token)+1);
strncpy(array[a], token, sizeof(array[a]));
a++;

So theoretically my token should be "Mammal\n"
which I copy to the array.
But then doing array[a][sizeof(array[a])] = '\0' changes nothing. And yes I'm inserting this BEFORE the a++.

edit:

Code:
token[strlen(token)] = '\0';

should work. But it isnt.

edit 2: Ah I bet it is strlen(token)-1....
 

Pokemaniac

Member
I keep trying this but it doesn't seem to be working. I'm fucking so lost.

I'm doing this:
Code:
array[a] = malloc(strlen(token)+1);
strncpy(array[a], token, sizeof(array[a]));
a++;

So theoretically my token should be "Mammal\n"
which I copy to the array.
But then doing array[a][sizeof(array[a])] = '\0' changes nothing. And yes I'm inserting this BEFORE the a++.

edit:

Code:
token[strlen(token)] = '\0';

should work. But it isnt.

edit 2: Ah I bet it is strlen(token)-1....

You seem to be on the right track, but I just wanted to mention that sizeof doesn't work on arrays in C. The language completely lacks a way to programatically determine the size of an array. You just have to keep track of the size manually.
 
You seem to be on the right track, but I just wanted to mention that sizeof doesn't work on arrays in C. The language completely lacks a way to programatically determine the size of an array. You just have to keep track of the size manually.

Thanks.

I finally, FINALLY got it working. Holy shit I feel so good right now.

edit: fuck I've been working on this for like 3 hours.
 

NotBacon

Member
Thanks.

I finally, FINALLY got it working. Holy shit I feel so good right now.

edit: fuck I've been working on this for like 3 hours.

Best feeling. That's where the learning happens too. After hours of tedious work on something very specific. And then you show someone because you're proud and they say "...cool?".

"You showed some text on your screen? Watch I can play video on my screen."
 

Ambitious

Member
There's this local club I visit pretty frequently. They have their event schedule on their website, but I would rather have it in my calendar instead. I would like to either a) be able to import all scheduled events manually by running a script or b) create a calendar service which I can subscribe to. Could someone please give me some hints on how to implement this? I'm gonna work with Python, I guess.

Parsing the website shouldn't be a problem. Unfortunately, the starting time for the events isn't included in the event list; it's part of the event description. So that's gonna be a bit messy, but whatever. Is the BeautifulSoup library still to be recommended?

Regarding option A: This should be pretty trivial. I just have to create an .ics file from the scraped data, which I'm sure there exist countless libraries for, and open it. Right? Might have to figure out a way to avoid duplicated items when re-running the scraper and how to deal with updated dates/times.
Obviously, I would have to manually execute the script every time they add new events to the schedule.

Regarding option B: This is of course what I would prefer, for the sake of automation and convenience. So instead of creating an .ics file, I would have to publish the scraped event data to a server. What kind of technologies do I need for this? Is it CalDAV? Any suggestions for libraries?
I have a macOS server* at home, so I could run the calendar service on there and create an automated job to scrape the website periodically.


* It's standard macOS though, not the server version.

Scraping the website was easy, as expected. Parsing the event start time got a bit messy, though, as it's only mentioned in the plaintext event description. There's no dedicated field for the time. And the used formats are not consistent either (e.g. 7:00, 7.00, 7am).
I have the same issue with certain events that take place all weekend. The date range is only mentioned in plaintext.

But anyway: As for the calendar subscription, apparently all you need is a simple HTTP server, serving an .ics file. Now I just need to create the .ics file from my parsed data and publish the file somewhere. Dropbox would be the easiest, most convenient solution for the latter, as I wouldn't have to set up anything (i.e. server, port forwarding etc.). But I'd rather not use them anymore.
 

Allonym

There should be more tampons in gaming
No problem.

Actually I need further help, if you'd be so kind. So I created the code;

public class LuckySevens {
public static void main(String[]args){
int min, max;
System.out.println("Enter an integer for lower range value");
min=IO.readInt();

System.out.println("Enter an integer for upper range value");
max=IO.readInt();

for(int outer=100; outer <=200; outer++){
for(int inner=100; inner<=outer; inner++)
System.out.print("7");
IO.reportBadInput();
if(min>max);

}}}
--------------------------------------------------------------------------------------------------------------------------------
This prints out a right triangle made of rows and columns of sevens with each successive row having one more seven than the previous. That's not what I wanted. I want the program to output every number from 100 to 200 that contains a seven and following that at the end of the code it has to feature a return statement but when I do put a return statement after "if(min>max)", the 10th line features an error message that says dead code and "outer++" is underlined.

If anyone would be able to help me rectify this, I would be eternally grateful. This is java btw
 

vypek

Member
Actually I need further help, if you'd be so kind. So I created the code;

public class LuckySevens {
public static void main(String[]args){
int min, max;
System.out.println("Enter an integer for lower range value");
min=IO.readInt();

System.out.println("Enter an integer for upper range value");
max=IO.readInt();

for(int outer=100; outer <=200; outer++){
for(int inner=100; inner<=outer; inner++)
System.out.print("7");
IO.reportBadInput();
if(min>max);

}}}
--------------------------------------------------------------------------------------------------------------------------------
This prints out a right triangle made of rows and columns of sevens with each successive row having one more seven than the previous. That's not what I wanted. I want the program to output every number from 100 to 200 that contains a seven and following that at the end of the code it has to feature a return statement but when I do put a return statement after "if(min>max)", the 10th line features an error message that says dead code and "outer++" is underlined.

If anyone would be able to help me rectify this, I would be eternally grateful. This is java btw


As an aside, could you use the code tags for better formatting in the future? Its not like its necessary here but it does make it more readable.

Taking a quick look:
Dead code means its a logical impossibility. You'll never reach that code so there is something off in the logic that outer++ can't be used.

Outputting every number that has a seven in a range is a pretty simple build off of the project you mentioned before. Did you finish that one where it counts how many 7's appear? All you have to do is check if you see a 7 in the inner loop and if you do, output the number.

The min and max check can be done outside of the loop at the very end since you only need to check it right before you terminate the program. Just do the boolean check and output right before the final brace.

Hope that helps. Will edit or post more later

EDIT:
I can actually do more now since I am in an online meeting.

Only your outer loop should be counting from 100 to 200. Your nested loop shouldn't be doing that. Inner loop wants to look at the number that outer is on and then look at each number for the length of that number and check for a 7.

Example:
outer is at 100
inner reads in 100, and determines its length is 3
inner reads index 0, 1 and then 2 while looking for a 7
if 7 is found, output the full number, else continue on and let outer go to next index
 
Actually I need further help, if you'd be so kind. So I created the code;

public class LuckySevens {
public static void main(String[]args){
int min, max;
System.out.println("Enter an integer for lower range value");
min=IO.readInt();

System.out.println("Enter an integer for upper range value");
max=IO.readInt();

for(int outer=100; outer <=200; outer++){
for(int inner=100; inner<=outer; inner++)
System.out.print("7");
IO.reportBadInput();
if(min>max);

}}}
--------------------------------------------------------------------------------------------------------------------------------
This prints out a right triangle made of rows and columns of sevens with each successive row having one more seven than the previous. That's not what I wanted. I want the program to output every number from 100 to 200 that contains a seven and following that at the end of the code it has to feature a return statement but when I do put a return statement after "if(min>max)", the 10th line features an error message that says dead code and "outer++" is underlined.

If anyone would be able to help me rectify this, I would be eternally grateful. This is java btw

Well for starters the logic seems wrong.
 

Allonym

There should be more tampons in gaming
As an aside, could you use the code tags for better formatting in the future? Its not like its necessary here but it does make it more readable.

Taking a quick look:
Dead code means its a logical impossibility. You'll never reach that code so there is something off in the logic that outer++ can't be used.

Outputting every number that has a seven in a range is a pretty simple build off of the project you mentioned before. Did you finish that one where it counts how many 7's appear? All you have to do is check if you see a 7 in the inner loop and if you do, output the number.

The min and max check can be done outside of the loop at the very end since you only need to check it right before you terminate the program. Just do the boolean check and output right before the final brace.

Hope that helps. Will edit or post more later

I've only been doing this stuff for a month so I'm kinda lost, I assume tags are these guys "<,>"?

This is still the project you helped me out with originally. I thought that I created a nested loop that did do that but evidently I didn't. I thought my code would do this; I thought it'd prompt the user to enter a lower range value and an upper range value. From there, I thought the nested loop I made would run from the lower range, check to see if there were any 7's and then move to the next number, check that one etc. I thought it would do this until it reached the upper limit and then from there display (say I started from 100 and went to 200)

107
117
127
137
147
157
167
170
177
187
197

The result would be 11 because 7 appears 11 times. I don't understand what you mean when you ask if I saw a seven in the inner loop. Am I supposed to write the values that feature a seven in the inner loop? This is all confusing.
 

vypek

Member
I've only been doing this stuff for a month so I'm kinda lost, I assume tags are these guys "<,>"?

This is still the project you helped me out with originally. I thought that I created a nested loop that did do that but evidently I didn't. I thought my code would do this; I thought it'd prompt the user to enter a lower range value and an upper range value. From there, I thought the nested loop I made would run from the lower range, check to see if there were any 7's and then move to the next number, check that one etc. I thought it would do this until it reached the upper limit and then from there display (say I started from 100 and went to 200)

107
117
127
137
147
157
167
170
177
187
197

The result would be 11 because 7 appears 11 times. I don't understand what you mean when you ask if I saw a seven in the inner loop. Am I supposed to write the values that feature a seven in the inner loop? This is all confusing.

When you make a post, the code tags are the button that looks like this: #

If the min > max check is for validation then you'll want something like this to start with:
Code:
read min
read max
if (min > max){
   output to user that the numbers are bad
}
else{
  for (outer = min; outer <= max; outer++){
      for (inner = 0; inner <= outer.length(); inner++){
          //CHECK IF YOU SEE A 7; IF 7, println(outer) 
      }
   }
}

I didn't test that code but I think it should be very close to what you need to do

By the way, you forgot 171 - 176 and 178-179 should be included since they have 7 in them
 

Allonym

There should be more tampons in gaming
Well for starters the logic seems wrong.

I don't intend to be rude but do you have anything more substantial to add? I don't have a ton experience programming, this is an introductory class and things that may be readily apparent to you, may not be so for me. I'm just operating within the given parameters of the assignment. I know that we have to use nested loops and a return statement and prompt the user for inputs using IO but that's all we're really given to go on.
 
I don't intend to be rude but do you have anything more substantial to add? I don't have a ton experience programming, this is an introductory class and things that may be readily apparent to you, may not be so for me. I'm just operating within the given parameters of the assignment. I know that we have to use nested loops and a return statement and prompt the user for inputs using IO but that's all we're really given to go on.

It's gonna sound weird but you need to sound out the problem again and go step by step. The previous code you had was printing a pyramid of 7s because you were telling it to print 7s instead of checking. The psuedocode posted above helps
 

Two Words

Member
Hey guys, I just got a Python internship that starts next month. The pay is $27 an hour, so I want to make a good impression and advance in their internship program. I know a bit of Python, but I feel that I have not really mastered programming the "Pythonic" way. Does anybody have any good places to learn Python in a manner that will really force me to utilize the unique attributes of Python?
 

Makai

Member
Hey guys, I just got a Python internship that starts next month. The pay is $27 an hour, so I want to make a good impression and advance in their internship program. I know a bit of Python, but I feel that I have not really mastered programming the "Pythonic" way. Does anybody have any good places to learn Python in a manner that will really force me to utilize the unique attributes of Python?
https://www.python.org/dev/peps/pep-0008/
 

theecakee

Member
I'm a junior CS major right now starting to apply and look for internships.

I have small stuff I've done, but not many big things on my resume. I am going to a Hackathon in like 2-3 weeks so I think after I'm done and have it on my resume that I'm definitely going to start applying hardcore. I do have one other big side project I'd like to work on, but it's just time is a huge issue.

What's the best way to prepare for the code interviews? I was thinking about making a quizlet set for major terms in Algorithms, Java things, and OOP stuff, so basically probably everything in Crack the Code Interview book. Then just flip through them whenever I'm free or something. Then everyday spend like an hour doing some Hacker Rank problem.

Should I focus more time on side projects? Should I do something different?
 

upandaway

Member
I'm a junior CS major right now starting to apply and look for internships.

I have small stuff I've done, but not many big things on my resume. I am going to a Hackathon in like 2-3 weeks so I think after I'm done and have it on my resume that I'm definitely going to start applying hardcore. I do have one other big side project I'd like to work on, but it's just time is a huge issue.

What's the best way to prepare for the code interviews? I was thinking about making a quizlet set for major terms in Algorithms, Java things, and OOP stuff, so basically probably everything in Crack the Code Interview book. Then just flip through them whenever I'm free or something. Then everyday spend like an hour doing some Hacker Rank problem.

Should I focus more time on side projects? Should I do something different?
I don't have a lot of experience with it (only when I looked for a couple of months half a year ago) but the best way to practice was mock interviews, or actual interviews. If you have a friend, a nice format is asking each other questions in turns from Cracking the Coding Interview to answer on the whiteboard or live on a laptop (google made me write answers on a laptop in a set amount of time, it threw me for a loop because I never practiced it). Preferably also get someone more experienced to do a real mock interview if you can.

Answering questions on your own is a whole other different beast from doing it in an interview
 

komplanen

Member
Do you guys think a portfolio of self-made projects is a good idea? Any tips? I'm trying to get my first programming job and I'm really open to what the field is, as long as it's not web programming.

What example projects do you guys think would be broad interest enough when I don't exactly have a targeted field?
 

Koren

Member
Hey guys, I just got a Python internship that starts next month. The pay is $27 an hour, so I want to make a good impression and advance in their internship program. I know a bit of Python, but I feel that I have not really mastered programming the "Pythonic" way. Does anybody have any good places to learn Python in a manner that will really force me to utilize the unique attributes of Python?
I have no good suggestion of ressources, but I'd say an important point if you want to write pythonic code is the use of iterables/iterators/generators/etc.

I mean, if you have to compute the product of the elements in a list, avoid
Code:
accum = 1

for i in range(len(L)) :
    accum *= L[i]
and prefer
Code:
accum = 1

for elem in L :
    accum *= elem

It may be a detail, but it's probably one of the most obvious things that shows you haven't used Python much. Even more so when Python has a strong emphasis on lists (which are actually resizable arrays that can handle different types) and iterables in general.

If you need both the elements and the index, use
Code:
for i, elem in enumerate(L) :

If you need to iterate over several lists at the same time, use
Code:
for elem1, elem2 in zip(L1, L2) :

etc.

When you're fine with the base of the language, look into generator functions (and itertools, too). Take some time to look into dicts.

Usually, "Pythonic" means "easily understandable", since it was partly designed for readability. Think about the types that will work best, and how you can write the code to make it readable, and you'll probably get "pythonic" constructs most of the time.

After that, it's mostly a matter of time to learn all the tricks you can use. Reading code can be helpful. StackOverflow has been useful to me to discover some interesting constructs.


Try not to reinvent the wheel, there's so many modules available that a lot of things you don't have to write yourself. I won't suggest you reading the whole "standard set" of modules, but at least look into what's available, it's probably deemed unpythonic of not using one of the standard modules ;)


Also, not strictly "Pythonic", but Python is awful to warn you about possible bugs (since you don't have a compilation, and it use dynamic typing without any nice way to check the type of an argument, because it's actually unpythonic to do so). So Python is a language that HEAVILY relies on testing.

You should probably get used to design a LOT of unit tests for all your functions if you intent to create large code.


I'm really not that fond of some parts of that PEP (but I think we discussed it already), and the main thing I remember is readability is over consistency or PEP-8...
However, know when to be inconsistent -- sometimes style guide recommendations just aren't applicable. When in doubt, use your best judgment. [...] When applying the guideline would make the code less readable, even for someone who is used to reading code that follows this PEP.

Also, I wonder how much "pythonic" refers to the basic formatting/spacing/indentations...

Do you guys think a portfolio of self-made projects is a good idea? Any tips?
I'm not really sure how useful it is, but I'm convinced it's a nice thing to have. If you can contribute to an open-source project, it's probably nice too.
 

Bollocks

Member
lol so I just schooled our java guys at work today.
thought I would write some Java code for a change, had a null pointer exception and decided to ask the java guys.

They didn't know that when you have a class with a base constructor and extend this class but don't implement a new base constructor, the parent base constructor will be invoked when you instantiate the subclass. Even if you define a new parameterized constructor on the subclass. It will always get called, unless you overwrite the base constructor in the subclass.

They: "Yeah that's not how Java works, why should it do that, of course you get a null pointer exception, you have to implement a base constructor in your new class, those members are uninitialized, you have to initialize them".
Me: "Yeah that's what I do in the base class, what's even the point of subclassing if I have to copy and paste code?"
They: "Yes that's why you have to call super()"
Me: "Why do I have to manually call super() if I don't overwrite the base constructor in the subclass"?
"So you're telling me I have to call super() in every constructor subclass because otherwise the base members will be left uninitialized?"
"Why can I even compile without super() then, doesn't make sense"
They: "It's Java"
Me: "Look, I didn't provide a base constructor in the subclass, it will therefore invoke the one from the base class instead - automatically, unless I define one in the subclass, then I have to manually call super()"

I then pointed out a quote on the official docs, "No that's wrong", "It's from the official docs", "Can't be, if you call it manually maybe."
Eventually we ran a basic example and everything got initialized, thanks to the power of inheritance, doh.

Funny thing was that I'm a frontend developer, so I deal with JavaScript, this disqualified me immediately, "lol maybe it works that way in JS", "yeah it's hard to describe a javascript guy OOP".
Guess what I have a background in software engineering long before I even started with webdev, I just don't like Java.
I loved their faces when the "JS" guy took them to school.
latest

I consider this basic knowledge, I don't know how you can not know this, idk how I should feel about this.
 

Two Words

Member
I have no good suggestion of ressources, but I'd say an important point if you want to write pythonic code is the use of iterables/iterators/generators/etc.

I mean, if you have to compute the product of the elements in a list, avoid
Code:
accum = 1

for i in range(len(L)) :
    accum *= L[i]
and prefer
Code:
accum = 1

for elem in L :
    accum *= elem

It may be a detail, but it's probably one of the most obvious things that shows you haven't used Python much. Even more so when Python has a strong emphasis on lists (which are actually resizable arrays that can handle different types) and iterables in general.

If you need both the elements and the index, use
Code:
for i, elem in enumerate(L) :

If you need to iterate over several lists at the same time, use
Code:
for elem1, elem2 in zip(L1, L2) :

etc.

When you're fine with the base of the language, look into generator functions (and itertools, too). Take some time to look into dicts.

Usually, "Pythonic" means "easily understandable", since it was partly designed for readability. Think about the types that will work best, and how you can write the code to make it readable, and you'll probably get "pythonic" constructs most of the time.

After that, it's mostly a matter of time to learn all the tricks you can use. Reading code can be helpful. StackOverflow has been useful to me to discover some interesting constructs.


Try not to reinvent the wheel, there's so many modules available that a lot of things you don't have to write yourself. I won't suggest you reading the whole "standard set" of modules, but at least look into what's available, it's probably deemed unpythonic of not using one of the standard modules ;)


Also, not strictly "Pythonic", but Python is awful to warn you about possible bugs (since you don't have a compilation, and it use dynamic typing without any nice way to check the type of an argument, because it's actually unpythonic to do so). So Python is a language that HEAVILY relies on testing.

You should probably get used to design a LOT of unit tests for all your functions if you intent to create large code.



I'm really not that fond of some parts of that PEP (but I think we discussed it already), and the main thing I remember is readability is over consistency or PEP-8...


Also, I wonder how much "pythonic" refers to the basic formatting/spacing/indentations...


I'm not really sure how useful it is, but I'm convinced it's a nice thing to have. If you can contribute to an open-source project, it's probably nice too.
Thanks for all of the advice. It is really helpful.
 
Can anyone show me how to call a python method from c++ then show the returned string? I tried googling around but I'm still getting errors. I just need some example code.
 

Koren

Member
Can anyone show me how to call a python method from c++ then show the returned string?
There's plently of ways to do this...


For example, it can be done using popen if you have a POSIX C/C++ (the result of the script is open as a file, so you can read it as you would read a file)

______________________

Example :

Quick and quite stupid test.py:
Code:
import sys

def toto(x) :
    return 2*x

print(toto(sum(int(v) for v in sys.argv[1:])))

(prints twice the sum of its arguments, interpreted as integers)

Quick a also stupid C file that call the script and print the result:
Code:
#include <stdio.h>

int main(int argc, char* argv[]) {
	FILE* f = popen("python test.py 2 3 4", "r");

	int v;
	
	fscanf(f, "%d\n", &v);
	pclose(f);
    
	printf("Output: %d\n", v);
	
	return 0;
}
______________________

The C code will produce "Output: 18"


Granted, that's not C++, but it work the same in C++, with streams if you prefer.


The nice thing with popen is that you can *write* to the file descriptor, and the python script will think it comes from standard input, so you can actually communicate with the script both ways.


Or you can use system(), the C++ Python library, etc.
 

kadotsu

Banned
I need a bigger (3-5 programmers) and documented IT project example to train as a SCRUM master/project lead. Are there any good sites with examples?
 

Makai

Member
I need a bigger (3-5 programmers) and documented IT project example to train as a SCRUM master/project lead. Are there any good sites with examples?
There's a bunch on the Scrum website, but they don't seem very useful. More important than process is the code itself - early engineering decisions can be very expensive to change.

http://fabiensanglard.net/doom3/

Not that a project will be successful if it tries to emulate Doom 3's development in the early 2000s.
 

kadotsu

Banned
There's a bunch on the Scrum website, but they don't seem very useful. More important than process is the code itself - early engineering decisions can be very expensive to change.

http://fabiensanglard.net/doom3/

Not that a project will be successful if it tries to emulate Doom 3's development in the early 2000s.

This isn't about the programming. My training isn't about coding it's about planning, time management, risk assessment etc. I need a FSD.
 

Makai

Member
This isn't about the programming. My training isn't about coding it's about planning, time management, risk assessment etc. I need a FSD.
It is possible to perfectly plan for things but it requires a level of rigor that is impractical for a normal company:

At the on-board shuttle group, about one-third of the process of writing software happens before anyone writes a line of code. NASA and the Lockheed Martin group agree in the most minute detail about everything the new code is supposed to do -- and they commit that understanding to paper, with the kind of specificity and precision usually found in blueprints. Nothing in the specs is changed without agreement and understanding from both sides. And no coder changes a single line of code without specs carefully outlining the change. Take the upgrade of the software to permit the shuttle to navigate with Global Positioning Satellites, a change that involves just 1.5% of the program, or 6,366 lines of code. The specs for that one change run 2,500 pages, a volume thicker than a phone book. The specs for the current program fill 30 volumes and run 40,000 pages.&#65279;

FSDs are always woefully wrong at normal companies and prior engineering decisions constrain what can be done. I bet seeing how and why successful projects structure their code is more useful than seeing how they create tickets. This is probably the closest you'll get to what you want: https://www.scrumalliance.org/success-stories
 

kadotsu

Banned
FSDs are always woefully wrong at normal companies and prior engineering decisions constrain what can be done. I bet seeing how and why successful projects structure their code is more useful than seeing how they create tickets. This is probably the closest you'll get to what you want: https://www.scrumalliance.org/success-stories

I agree with everything you said. It's Master course for IT project management. But here's the kicker: They want us to be pretend PLs but failed to provide a single example project. They said we should have brought that with us... because masters student always have copious amounts of almost finished projects that would require a PL.
 

Koren

Member
It is possible to perfectly plan for things but it requires a level of rigor that is impractical for a normal company
The fact that NASA still do giant errors like not specifying the physical units of the result/input (or rather, specifying it but not checking that software is correct for this kind of specifications) is... mind blowing.
 
I just took an online code test of 8 questions and one of them stumped me, figured I would post it here:

int a = ??
int b = 0
int c = ??

for (b = 0; a < 12; b++){
a = (a + a) * c;
}

What are the initial values of a and c assuming final values a = 32 and b = 4 ?
 

JesseZao

Member
I just took an online code test of 8 questions and one of them stumped me, figured I would post it here:

int a = ??
int b = 0
int c = ??

for (b = 0; a < 12; b++){
a = (a + a) * c;
}

What are the initial values of a and c assuming final values a = 32 and b = 4 ?

You don't always have to stay positive. Take your time.
 

vypek

Member
Thought I might ask here, has anyone been asked coding questions when using Uber? I still have no idea how they knew I was into development. I didn't bother answering the questions since I was distracted and talking with my driver. It just took my by surprise that Uber was asking data structure and algorithm problems to their riders.
 

Koren

Member
Hi guys, would someone kindly explain in lamens terms for someone with limited programming knowledge what a static array is? Thanks.
There can be different meaning depending on the context. Would you mind give us a bit more details?

Without more, I'd say that "static array" refer to an array whose dimensions are perfectly known from the source code, and won't change during execution. Because of this, you know exactly how much memory you need to store it, which allows some optimizations.
 

Koren

Member
I realized I had to use negatives but couldn't get there in time. Need to keep my nerves in check cause algebra was never my strong suit. Thanks!
In those situations, unrolling the loop is helpful. It works either when the number of loops is small, or the loop itself is simple. Both are true here (4 iterations, and it's a geometric sequence)...


At each loop, you just do a <- 2c * a

Thus, after 3 loops, a contains 8 c^3 a. After 4 loops, a contains 16 c^4 a


So 8 c^3 a < 12 and 16 c^4 a = 32


The second equation means c^4 a = 2

There's obviously only two integer solutions, but one doesn't verify 8 c^3 a < 12... Thinking that integers can be negative is the harderst part.
 

wwm0nkey

Member
hmmmm okay so I am working on a card system for a game and I got a few elements working but removing the cards/keeping them still seems broken right now

Here is what it kind of looks like right now (not at my work computer)

Code:
for(int i =0; i < 5; i++){
if(card[i].isUsed == true){
card.remove(card[i]);
card[i].isUsed = false;
    }
}
//Code that adds blank cards in if the count ever goes below 5

So it should only be removing the card at index i if it was being used right? I keep getting the issue of it removing other cards at random but I am also wondering if that's because I am grabbing the objects automatically at the start and it just doesn't grab them in the same order all the time?
 

Somnid

Member
hmmmm okay so I am working on a card system for a game and I got a few elements working but removing the cards/keeping them still seems broken right now

Here is what it kind of looks like right now (not at my work computer)

Code:
for(int i =0; i < 5; i++){
if(card[i].isUsed == true){
card.remove(card[i]);
card[i].isUsed = false;
    }
}
//Code that adds blank cards in if the count ever goes below 5

So it should only be removing the card at index i if it was being used right? I keep getting the issue of it removing other cards at random but I am also wondering if that's because I am grabbing the objects automatically at the start and it just doesn't grab them in the same order all the time?

What does card.remove do? Note that you do not want to modify an array being iterated over or bad things happen. Make a new array that does not include the removed cards instead.
 

wwm0nkey

Member
What does card.remove do? Note that you do not want to modify an array being iterated over or bad things happen. Make a new array that does not include the removed cards instead.

Opps sorry should have said that it was a List and not an Array! So remove should be removing the element at i, though now that I think about it I could just do remove(i) lol
 

Somnid

Member
Opps sorry should have said that it was a List and not an Array! So remove should be removing the element at i, though now that I think about it I could just do remove(i) lol

Doesn't matter if it's a list. Do not modify it under iteration. Think about what happens, if your removed index 3 then index 4 is now index 3 and when you advance to the next index you're on what you'd expect to be index 5.

Make a new list without the deleted elements. People in this thread will talk about the glories of immutability and this is what they are referring to, make new objects rather than modify. It saves your from subtle bugs like this where you accidentally change the object out from under a piece of code that reads it.
 

Koren

Member
Doesn't matter if it's a list. Do not modify it under iteration.
This 100x, unless you use *properly* an actual iterator over the list or are *really* careful.

Also, I don't understand the card.isUsed = False. If you've removed the card, at best, it's the following card, at worse, it's not even a card that exists anymore... and the hardcoded 5 in the loop will backfire quickly.


Make a new list without the deleted elements. People in this thread will talk about the glories of immutability and this is what they are referring to, make new objects rather than modify.
Depending on what you're after, there's plently of reasons of NOT creating a new list, though. For example, to avoid a O(n) cost (or even worse... especially when that may means that you'll have to deal with copy constructors and the like for basically nothing), or to preserve references to the list.

I'd say there's far better way to handle this... For example, assuming it's a STL list, something like:
Code:
bool isUsed(const ???& elem) { return elem.isUsed; }

card.remove_if(isUsed);


Edit: is it a flashcard learning app in the making? ^_^
 

wwm0nkey

Member
Doesn't matter if it's a list. Do not modify it under iteration. Think about what happens, if your removed index 3 then index 4 is now index 3 and when you advance to the next index you're on what you'd expect to be index 5.

Make a new list without the deleted elements. People in this thread will talk about the glories of immutability and this is what they are referring to, make new objects rather than modify. It saves your from subtle bugs like this where you accidentally change the object out from under a piece of code that reads it.
Man I have no idea why that wasn't the most obvious thing to me before lol

I think I have my solution now
 
Top Bottom