lainchan / λ

The Beginner's General

Chan Siu Ming · 2018-06-02 22:23
Hoi chummers! I was about to post this into the simple programming questions thread but it reached it's maximum reply limit. *sadface* I want to code a little CLI voice modulator tool as a little programming project to get better in Rust programming. It should take the input of one (for now) audio sources (mic), modulate it to "le scary anonymous hacker voice" (or little girl voice, or robot voice, ...) and finally make it available on a new virtual audio source (i hope that's the correct terminology). Sadly, I don't have much domain knowledge when it comes to audio programming. Can you guys recommend me a good audio library that is cross-platform and also lightweight? It doensn't have to be a Rust crate as I'm going to use Rust's FFI. Additional resources to learn more about audio programming are also greatly appreciated.
Tyrell Wellick · 2018-06-02 23:45
https://wiki.python.org/moin/PythonInMusic
Case · 2018-06-03 06:31
>>8588 Depends. You can try Super Collider if you want a full, functional environment for synthesis. There is also C-sound. As for libraries, the low level Linux stuff is what you want if you just want to make stuff from scratch.
λx.x · 2018-06-03 20:16
This is the Beginner's General for beginners' questions. If you have a simple question and a suitable thread doesn't already exist, just post it here and someone will probably try to answer it for you. Remember to do some research before asking your question. No one wants to answer a question that a simple search can already resolve.
Demeere · 2018-06-03 23:14
>>8601 Very simple question here, but what would be a good path to follow to get good general knowledge about programming and be able to contribute to some stuff around here? Currently I'm working my way through the book "Programming from the Ground Up", found it in lainzine vol.2 and I like how it doesn't neglect to go over some basic stuff like computer architechture. That being said, high-level languages are only covered a little over halfway through the book and I'm only just at chapter 4. It's worth pointing out, too, that I'm not a complete newbie to programming. I've dabbled in some very easy languages like Lua, I've helped code some addons and scripts for sandbox games in it. Also fuarrrked around with robotics a little, with C. I understand a lot of the general conventions of most programming languages besides stuff like HTML, but I've never worked on anything of scale and I never got a full grasp of the process outside of structures like sandbox games. Which is partially why I'm going through this book. Should have it done in the next 10 days if I'm able to keep up with the chapter/day pace I decided on. I suppose I'm really just asking for some books, resources I should look at and an order to look through them. Any guidance or help would be greatly appreciated. Also, would be nice to know if the book I'm reading is a pile of soykaf or not, or if assembly languages are a waste of time.
Armitage · 2018-06-03 23:22
>>8607 https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book.html
Stallman · 2018-06-04 15:26
>>8607 Assembly isn't bad, but if you are trying to learn programming I would say it is useless. Assembly is better suited for someone that already knows a good deal of programming and wants to get a better understanding of what they are doing. Or if you are into hardware, especially with an emphasis on embedded. I would want to know what your goals are with programming. Otherwise I can only safely recommend Python. It has many uses and has many libraries which would allow you to have some fun while learning it. If you are looking for something that isn't a scripting language I would also recommend Go and Rust. Mainly because they both have amazing resources for learning their languages right on their sites. If you give more information on what you want to use programming for I can give you a more in depth answer.
Chan Siu Ming · 2018-06-04 22:15
>>8639 My goal is really just to set a foundation of understanding to learn other languages from. I'm learning Assembly just because I find it very interesting to be able to issue nearly direct commands to the CPU. I'd also like to have a better understanding of computing in general, and while this book I'm working through goes through Assembly it also contains a lot of information about the CPU, memory, etc. It provides a good picture on how everything is handled at the base level. I want to set myself a really good foundation to learn upon, so maybe I'll understand why high-level code does what it does better. I'm viewing it more as a "learn how to learn" experience, I guess. Maybe a top-down learning method would be better, but I'm finding everything at the base level pretty interesting. Also, I really would like to learn more about how high-level code is implemented. I mean, when I've learned languages in the past, I've always wondered how you would implement something like that at a larger scale. I don't want to learn a language that I have no idea how to implement. This is the reason that in the past I've mostly been stuck to programming addons in sandbox games, because everything is already there and it's really easy to throw stuff together. >>8608 Thanks, I'll give this a short look when I have some time.
Y.T · 2018-06-05 00:53
>>8656 Read Knuth's The Art of Computer Programming if you are so into programming in assembly. Learning actual assembly is almost useless though. Read SICP too. I feel like learning both these books should set you a really good foundational.
cond · 2018-06-05 01:21
>>8663 I've already got one book I'm reading through, days are too short to do anything but focus on this it seems, if I really want to learn it quickly. Thanks for the help, I'll jot down both of those on a note somewhere and take a look at them later. Also, I'm aware that assembly is pretty useless. I just like how it's easy to trace the lines between the exact processes of the CPU and memory to the instructions you write for them. Helps me get a good idea of how everything works, since I'm not aiming for only programming knowledge, but I also want to understand a good deal of compsci (or probably, more accurately just general knowledge. compsci is just too vast).
Hong, Guil Dong · 2018-06-07 04:07
>>8656 It sounds like you're interested in designing programming languages. I'd recommend SICP for that because SICP wholly is about constructing large programs from smaller, primitive parts and it dives into what it means to compile a language.
Knuth · 2018-06-07 21:21
>>8656 >I find it very interesting to be able to issue nearly direct commands to the CPU You are not unless you are writing real mode assembly :) User mode is a simulation! You should read the book "inside the machine" - you would love it. >I don't want to learn a language that I have no idea how to implement Do you mean write the language compiler or write a useful program in the language? >>8665 >Learning actual assembly is almost useless though I know where this lainon is coming from, but for many assembly is highly relevant and useful. You can use ASM for: -C++ debugging -high performance computing optmization -exploit development -OS development -Malware analysis -reverse engineering and much much more! > Read Knuth's The Art of Computer Programming if you are so into programming in assembly I would say the book is best for someone with a strong interest in algorithms. > Read SICP too. Maybe, it could also be the opposite of this lainons interests. Low level is a valid interest! >Also, I'm aware that assembly is pretty useless Don't get discouraged! Assembly made me a much smarter programmer, and allows me to do some amazing things. >It sounds like you're interested in designing programming languages I think this lainon would benefit from a bottom up approach. My advice for him is actually to start with algorithms and data structures before he jumps into large things. From there things like SICP and larger programs will make more sense. >I'd recommend SICP for that because SICP SICP is very good for what it's good for. It is a wonderful introduction in functional programming, with some program analysis. I don't think it helps people who are new to understand practical, modern programming. Most people are way more likely to encounter OOP patterns than functional paradigms. Lainon should rain SICP for sure, but maybe the best way to indulge his fascination with language design is to read the tiger book? https://www.cs.princeton.edu/~appel/modern/ It comes in ML and C variants, so he can pick a functional or native language depending on his preference. To give my two cents on learning about compilers, I think the best way, when you are ready for it, is to just read the source code to one. Straight down. Top to bottom.
Rick Deckard · 2018-06-07 22:26
So. I am using Python 3.6 and I need a hint on the app's architecture approach. Note, in my post I use "type" not as in "python type" but as a "kind". I have multiple external APIs. I have to unify and integrate those, constructing queries within my app which request same identical actions on these different APIs. - Should I store actions as strings in a DB? - Or make classes for each type? - Or make parent class with some method "bullets" defined (even though the syntax also differs from API to API), then subclasses with `__init__` for their specific verbs, which are then fed into parent class methods with `__super__` ? If this, how do I organize the app, so it knows which APIs to query each time - with a simple `if` logic defined for each case which checks some parameters or what? - Or do I make an abstract class (I have not tried this stuff yet) with all the possible actions defined, then subclass for each API type and override the methods (well, that's basically what I have described previously, but spiced up with OOP-poopery?)? How is this problem called? There must be a buzzword for this, googling which leads to soyboy articles of besterest practices.
Guthrie · 2018-06-08 06:46
>>8741 I wouldn't say interested in designing a programming language, I don't have very much experience so it'd be pretty hard. >>8769 First off, thanks for so much information. Sorry if I come off as a little braindead, I'm not well versed in programming lingo (or concepts for that matter, sadly). >You should read the book "inside the machine" - you would love it. I'll definitely give this a look, but I have a bit of a backlog of books I've been saving, so no guarantees that I end up on this one. >You can use ASM for: I did some basic stuff with editing a memory address in a game already using ASM (which i'm pretty proud of, was with my friends when i did it who pretty much exclusively program high-level and were doubtful of ASM's application). Exploit development and reverse engineering are two vectors of ASM that look really nice. I'm sure that C++ debugging can come in really handy too. I'm not looking to become an assembly master though, but I moreso view it as a good way to set a foundation for some quality knowledge all-around. I'm sure there will come a time when I'm forced to specialize in something though, and I think ASM is neat especially because it's not that common for people to be good at. Information can be a little hard to find, and there's something enchanting about learning something like that. Right now I'm just giving myself enough content to tread water and get my head filled up with some good general knowledge. >is best for someone with a strong interest in algorithms. I haven't looked much at algorithms yet. I'd love to, though. If they're covered in PFTGU i haven't gotten to them yet, but I may get to them pretty soon. The rest of the chapters in the book are conceptual, and I should be able to blow through them pretty quick from this point on. >actually to start with algorithms and data structures before he jumps into large things I'm really focusing on finishing this book so I can get to that sweet sweet "moving on from here". i'll do some research on algorithms on the side and see if i can get some concepts down before I move on to learning harder stuff about them. >I don't think it helps people who are new to understand practical, modern programming it's worth pointing out that I've done some stuff on the side with C++ (in the context of robotics) and Lua. I understand some programming conventions already, a lot of languages look pretty similar (to me) besides some differences in how certain datatypes are handled and, probably more importantly, syntax differences to get used to. ASM is the only language I've even looked at much that strays from that, which is probably why it's taking me so long. That being said, i haven't gone out of my way to fully learn a programming language, I wasn't even very proficient with Lua, which is to my understanding a very simple language to learn. >https://www.cs.princeton.edu/~appel/modern/ I looked at the preface for this, it looks pretty conclusive. I'm not sure if I'm ready to dive into something like this just yet, though. I need to try and just do a few projects with a language.
Trinity · 2018-06-08 06:58
>>8777 Glad my suggestions helped. Now that I know a little more about your experience, here are my thoughts. 1) Now that I know what kind of programming you've been doing, I think what you need is to read a larger program and start thinking about a larger project. There are *lots* of ways to structure a large project, and a lot of them are idiomatic to the language the project is implemented in. I'm going to get a lot of flak for this suggestion, but I think you should go seek out a large Java or C++ codebase and read it top down. Try and see how all the bits fit together. Then contrast that with a large Python/Ruby codebase. Then do a large Lisp codebase. Read as much of the code as you can. See how the parts fit together. Then start designing your own project that uses the design principles you learned. Meanwhile you should learn design patterns. 2) If ASM is really making you happy though, maybe you should stick with it and learn to enjoy some of the things ASM is good at. a) ASM can do useful work in very small programs. Make yourself do a little code golf exercise, and write a useful algorithm in the minimal number of characters. ASM can be astoundingly compact, and working to do this will make you better at the language. b) Write a very fast algorithm. Learn how to use Intel's SIMD registers, and vectorize an algorithm to work in parallel. Learn how to use streaming extensions, and atomics operations to make the most of data access. c) Obfuscate some code. ASM is great for writing code that is purposefully hard to read. d) Write a bootloader. e) start reading / writing shellcode for exploits. 3) If you just need a project, and have nothing on your mind try out programming competitions. Some people on here are going to be against the idea, but they can be a great way to get your juices flowing.
Cutter · 2018-06-08 18:17
I'm three months away from becoming a homeless man. Recommend me two to three good programming books to read, so that at least I can stand up on my own. I know a fair bit(basics + some algorithms) of c and python(also have some experience with django), and I've never wrote more than 150 lines of code. Most important thing is budget and time: 150 dollar(American), two and half months(max). Also any ideas on how to approach will be more than welcome.
St. IGNUcius · 2018-06-08 23:01
>>8601 > I know a fair bit(basics + some algorithms) of c and python(also have some experience with django), and I've never wrote more than 150 lines of code. Most important thing is budget and time: 150 dollar(American), two and half months(max). If you need a job fast: 1) Learn fizzbuzz in your language of choice. If you want a job, I say learn in this language: php->python->ruby->javascript Buzz is large here, you are likely to find something. 2) Also learn to do the fibonacci sequence. 3) Practice interview questions in whatever domain you want to work in. 4) Do a quick github project. In short, more doing. Less reading.
Armitage · 2018-06-09 03:16
>>8797 What would be a good github project?
Joey · 2018-06-09 05:07
>>8797 >I've never wrote more than 150 lines of code I'm sorry, what I meant was I never wrote more than 150 lines of code in a single program. >Learn fizzbuzz in your language of choice. I can write fizzbuzz in c, python and I also know fibonacci sequence, and others basic algorithms like sorts, graphs, etc. >let me make myself clear I've a graduate degree in com. science from university and I've previous experience with java(my first language). I know a fair bit of c and python- meaning, "I can write useful programs, but I've no previous experience with any project" >If you want a job, I say learn in this language: php->python->ruby->javascript But I don't like webdev stuff, maybe I should try my luck on backend dev. python, php and javascript with their respective framework, I guess. Can I really learn php and javascript in two and half months, or maybe I should focus on becoming good at one(i.e php and python).
Sabo Engle · 2018-06-09 09:27
>>8803 >I know a fair bit of c If time is an issue I would forget about C. C is a very simple language but to be useful you need to understand whole load of context such as hardware architecture and resource usage. The only reason anyone pays anyone to write C in 2018 is because they have specific needs related to performance or code size or power consumption or interacting with hardware. It's not enough to just write code that appears to solve the problem and call it a day like webcrap. So unless you're actually passionate about that stuff, it would be an unnecessarily difficult journey. >Can I really learn php and javascript in two and half months, or maybe I should focus on becoming good at one(i.e php and python). One important step is to look at job ads in locations you can commute/move to and figure out what technologies are popular. I think Python is a pretty universally solid bet though. Personally I think it's best to have one language you are really good at and then some others you know a little about rather than only knowing fizzbuzz in 50 languages.
pop · 2018-06-10 16:07
>>8788 freecodecamp if you want to be a web dev. You can get a job in 3 months if you hurry. Another option would be to read the java books from Green Tea Press. The first is programming from 0 and the second teaches data structures while building a search engine. I don't know anything else, in my opinion web dev and mobile are the fastest ways to becoming a programmer and getting a job. Good luck P.S: Learn stoicism and meditation to control stress levels and depression
Aristóteles Amadópulus · 2018-06-13 08:15
What do you think is the best configuration and build tool chain to use? In general, but also specifically for C++ development. I understand autotools are mostly considered clunky and outdated. How do CMake and Meson compare to each other?
The Oracle · 2018-06-14 07:15
>>8896 I would stay off crosspat tool chains unless you really have to. CMake is more of a "necessary evil" - it adds a level of irritation and time wasting to an already finicky build process.
Hagbard Celine · 2018-06-16 09:40
>>8912 Well, yes, the simplest you can keep things the better, of course. So your go-to when in need would be CMake?
DEBUG-CONTENTS · 2018-06-16 10:57
>>8966 Use Makefiles. CMake is unpredictable.
Anonymous · 2018-06-17 00:46
>>8639 How would you generally go about learning a new language if you have some basic foundation in another? Is it usually best to read some sort of beginner's book or just reading something like the Go site has? Or is Go just have particularly good tools?
Random · 2018-06-17 01:17
>>8991 If you want to learn Go I would suggest looking at these: https://golang.org/ The golang main site. You should start with the tour and make a few basic programs until you finish that. Then go through the packages section to get an idea of what you can do with the language. The packages section is very well detailed in how to implement all the things in the standard library. https://gobyexample.com/ Go by example is another well written site for getting a grasp for the language when starting out. You can just read it for reference, but I like to rewrite every example in a tutorial just so I can memorize then basics of the syntax. Again doing every example word for word is not necessary, but I did it in a day and it helped me get miles ahead in the language. https://ednsquare.com/publisher/view/Go-Language-CookBook-With-Examples------xOhLZaZVGG This is a relatively new site I saw on the Golang reddit. I haven't gone through it all that much but it does seem pretty interesting. https://github.com/avelino/awesome-go This is a great guide for Go resources and libraries that you can use for projects. Besides that, read Go code on github and Rosetta Code to get some ideas on what you want to do. Do exercise on exercism.io and hackerrank.com. I sometimes just read the list of exercises on those sites to get ideas for dumb projects when I'm bored. The talks on YouTube from GopherCon are pretty fun to listen to for inspiration as well. And of course when all else fails, the Stack Overflow Gods can answer any and all questions.
over · 2018-06-17 06:25
>>8994 Thanks for all the great resources. I've actually been looking for small projects I can use to learn, so this is pretty cool. How does one go about finding similar resources for other languages? Although I think I'll mostly stick to Go for now.
Molly Millions · 2018-06-18 03:27
Is it normal to take a while on SICP? I've been on 1.2 for at least 5 days now, and I'm going to have to look up most of exercises 1.22-1.28 to advance in a timely manner, I already know. Am I just dumb? Or is it normal to advance this slowly? >>8991 One resource a friend suggested to me is a site called "Learn X in Y minutes". They have brief, comprehensive overviews of syntax in a lot of languages. It's not a good way to practice, not even good for learning, but it is pretty good reference material I think.
Unnamed · 2018-06-18 04:55
>>9020 >Is it normal to take a while on SICP? I can't comment on SICP specifically, but keep in mind that it's perfectly normal for it to take time to understand things and work though all the associated exercises, especially when covering technical material. For that reason, I wouldn't worry too much about how long it takes, so long as you are continuing to make progress.
Void · 2018-06-18 17:38
>>9001 Here you go THE Awesome list of all awesome lists https://github.com/sindresorhus/awesome The big list of free books on many different languages https://github.com/EbookFoundation/free-programming-books/blob/master/free-programming-books.md And if you want a book that isn't free, use libgen
Ishikura "Tatsu" Tatsuhiko · 2018-06-19 02:25
How do I allocate a string inside an struct and print it after? When I call the struct in the function to print the struct informations it only gives me the first letter of the name: void printa_registro(Registro* r){ printf("nome: %s\n",r->nome); printf("idade :%d\n",r->idade); } Registro* aloca_registro(int idade, char nome[30]){ Registro *p; p =(Registro*) malloc(1*sizeof(Registro)); p->idade = idade; *p->nome = *nome; return p; }
Hiro Protagonist · 2018-06-19 02:26
>>9059 By the way, "nome" stands for "name" and "idade" stands for "age".
Eldon Tyrell · 2018-06-19 12:01
>>9059 change *p->nome = *nome to p->nome = nome the one with the *s only sets the first char.
Von Neumann · 2018-06-19 14:40
>>9066 It didn't work, but I managed to make it work by using strcpy(p->nome,nome) function.
Ivan Petrov · 2018-06-19 22:43
>>9067 Huh, that's surprising. You could also try p->nome = strdup(nome)
Faye Valentine · 2018-06-21 01:22
I study Computer Science, and in second year we will probably have physics course. So i thought, may i prepare for that in my spare summer time? So my question is: what kind of fields of physics is useful for CS. I thought about borrowing some books from Feynman Lectures series, pic rel, is this good idea? If it is, which ones i should choose? If not, what are some physics books you could recommend to me?
Joey · 2018-06-21 10:09
>>8601 Hey lainons. I learn C and want write little project. Can i give idea what i can write? I think i can try write simple PE reader. But i dont know where to start
Motoko Kusanagi · 2018-06-21 10:10
>>9091 you*
Hououin Kyouma · 2018-06-21 14:33
>>9087 It depends on the field you are interested in. If you are interested in hardware and how data transfer works, it would be necessary to learn abou electromagnetism and how basic coputer parts and electricity work. If you want to implememt a physics engine for game developement, wou will have to work with even more derivatives and learn how masses behave. Almost everything in physics will benefit you. Learning how electrical interference can be used to flip a bit in a computer in order to turn a "no" into a "yes" is also nice. This was used to abuse the prefetching of instructions in Intel CPUs. The more physics you know the more it will benefit you. It's not like history or politics. Those areas contain a lot of useless knowledge.
Zhora · 2018-06-21 15:53
I just finished my physics series and boy was that a lot of content. If it's anything like what I had to do you'll start with simple stuff like motion at constant accelleration and work your way all the way until quantum mechanics and relativity. http://hyperphysics.phy-astr.gsu.edu/hbase/index.html is kind of a nice site. It has a web of concepts you can explore through. I don't know how useful it is on its own, but I used it many times throughout the year.
Linda Lee · 2018-06-21 23:53
For kinematics and electromagnetism I highly recommend watching and taking notes on the video lectures by Walter Lewin kinematics course: https://www.youtube.com/playlist?list=PLyQSN7X0ro203puVhQsmCj9qhlFQ-As8e electromagnetism course: https://www.youtube.com/playlist?list=PLyQSN7X0ro2314mKyUiOILaOC2hk6Pc3j Unfortunately his MIT OCW pages for his classes were taken down, I'm sure if you google or use the waybackmachine you can find the documents associated with this classes.
Frank Garza · 2018-06-22 06:13
>>9098 I've heard good things about his videos, but I haven't watched them myself.
Zuse · 2018-06-26 11:19
What are some good resources for learning C++?
word · 2018-06-26 11:42
>>9158 Here, have this book. It's amazing, but sort of expects you to already know a little bit about pointers, etc. Book is at https://lainchan.org/λ/res/38.html#5515
Elliot Alderson · 2018-06-26 12:05
>>9159 Thanks man, appreciate it
Hacker · 2018-06-26 12:06
>>9159 I know nothing about pointers, etc. but ill give it a go
Nell · 2018-06-26 18:42
What would you recommend to someone who wants to play with dissassembly on linux machine ?
Pris · 2018-06-26 18:47
I want to make a rpg dialog system (the type that were in fallout 1,2 or baldurs gate games) and I'm thinking what file format to use for storing a dialog tree. My first thought was to use xml/json to store a dialog tree. The main problem with this is that xml/json formats describes a tree structure and as I see it a dialog tree isn't always a tree, its a directed graph. The graph may have loops that would be hard to describe in a xml/json. Strangly I find a lot of tips on the internet to use xml or json for this. I guess that I could make some bookmarks in the xml and jump to them to avoid loops but maybe I am missing something? Any sugestion what file format to use and how to handle loops in the dialog in that format (ex. Dialog A gose to dialog B or C, and both dialog B and C gose to D, additional dialog D gose back to A)?
Yuki Nagato · 2018-06-26 22:08
>>9167 gdb, maybe gdb-dashboard once you're comforatable with the commands. strings and objdump are of limited use when you have gdb.
Terzibashjian · 2018-06-27 09:43
>>9168 Neverwinter Nights had lots of dialogue. The file formats were opened by Bioware. Might be worth a look. https://nwn.wiki/display/NWN1/File+Formats https://nwn.wiki/pages/viewpage.action?pageId=327727
Debbie Charteris · 2018-06-27 13:38
Where do i start learning to program ??
⍕ · 2018-06-27 13:43
>>9184 https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book.html https://www.gnu.org/software/guile/
Dujour · 2018-06-27 13:45
>>9185 SICP is a good book but not for beginners. i guess that person is looking for a book that has projects from the start to learn concepts or something.
Undisclosed · 2018-06-27 14:20
>>9184 Do small "projects" from sites like projecteuler, codebat and practicepython.
Roger Pollack · 2018-06-28 08:28
>>9181 I will take a look. Thanks.
Ivan Petrov · 2018-06-28 16:08
>>9188 I'm getting a 'server not fund' for project euler. Anyone else know anything about this? Praying it isn't kill.
Iverson · 2018-06-28 19:33
>>9220 Works fine now.
Spooky · 2018-07-02 01:35
Hello Lainons, I've been trying to make a functinon to merge two binary search into one, and so far my attempts failed. It's a binary tree of students and it is sorted by their ages. In the function "Arv juntar" I am trying to merge 2 trees by inserting every element from one tree into the other. It doesn't work. I've also tried to make a third three and insert both into the third. Did not work too. I don't really know what to do anymore, any ideas? struct registro { int idade; //a student's age char *nome;// a student's name char *curso; // a student's course }; struct no { struct registro r; struct no *sae; // a pointer to the binary tree on the left; struct no *sad; // a pointer to the binary tree on the right; }; typedef struct no* Arv; // the definition of a Tree typedef struct registro Registro; //this is the function that merges two trees. Arv is the tree type; Arv juntar(Arv A1, Arv A2){ if(A2== NULL){ insere_ord(&A1,&(A2->r)); } juntar(A1, A2->sae); juntar(A1, A2->sad); return A1; } //this is the function to insert in order. The order is determined by the integer "idade" which mens //the age of the student int insere_ord(Arv *A, Registro *r){ if(*A == NULL){ struct no *node; node =(Arv) malloc(sizeof(struct no)); node->r = *r; node->sae = NULL; node->sad = NULL; *A = node; return 1; } if(r->idade > (*A)->r.idade){ return insere_ord(&((*A)->sad), r); } else { return insere_ord(&((*A)->sae), r); } return 1; }
Arisu Mizuki · 2018-07-02 11:45
>>9276 Why are you accessing A2's fields if it's NULL?
car · 2018-07-03 23:58
Lainons, I need help with this code public class Lista{ private int[] a; private int i; public void Lista() { this.a = new int[10]; this.i = 0; } public void add(int s) { this.a[this.i] = s; i=+1; } public static void main(String[] args) { Lista l = new Lista(); l.add(1); } } This is the error: Exception in thread "main" java.lang.NullPointerException at lista.Lista.add(Lista.java:17) at lista.Lista.main(Lista.java:23) Why it doesn't work?
Splicer · 2018-07-04 00:00
>>9285 Sorry, correct line numbers are 13 and 19
Church · 2018-07-04 10:11
>>9285 - Constructors do not use a return type or 'void', so you are not declaring a constructor. https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.8 - There is no real need to use 'this.' for instance variables that are not shadowed by local variables. - i=+1 --> i+=1 - At some point a capacity check would be a good idea.
Anamika · 2018-07-04 15:53
>>8656 There's this book called "The elements of computing systems" by Noah Nisan and Shimon Schocken. You go top-down from Boolean logic to machine language, computer arcihtecture, compilers, all the way to creating an OS.It's a guide for a hands-on project. You can end up building a computer. You should read it. It's in the ebook thread.
bloodaxe · 2018-07-06 17:25
So I was trying to learn web development through Python from Youtube with the Pycharm IDE. But when I reached the CSS part, I was stuck because you need to have a subscription for that. I tried Visual Studio then but it got expired or something even though it was the community edition. Then I tried a biggeners minimalist IDE called Thony, it had all the packages like HTML5, CSS and Flask but when I tried to run the main Python script which creates a homepage, it gave me an OSError. I am on Windows 10. So can anyone here suggest a biggeners minimalist IDE like Thony, Sublime Text etc which supports web development and Python ? I need the one that works.
Randomneo · 2018-07-06 18:13
>>9319 Visual Code looks good for windows users. But I recommend go to linux. Its easier to config for web development and there 2 best editors in the world is Vim and Emacs. You can configure them and they will work like powerfull IDE. But for all of that you need a lot of time to learn, and of course that will be paid.
HELIOS · 2018-07-06 18:34
>>9320 I recommend GNU instead of Linux. GNU is actually an os. It wouldn't be wise to only use a kernel.
Ender · 2018-07-06 22:18
>>9319 Using a Linux distribution will make it easier, as >>9320 pointed out. We can't help you with the OSError unless we know what's wrong. While >>9321 is technically correct, if you try to understand/follow his advice right now you will only get more confused. Just disregard his bullsoykaf.
queue · 2018-07-07 16:33
>>9319 Hey friendo, just to clear up some terminology, editors and IDEs are not the same thing. An editor is just a thing that lets you edit text, IDE means integrated development environment. So PyCharm has all these gizmos and widgets that make your development life easy, it does more than just let you edit text. For learning, I would recommend using an editor though. Sublime text is very commonly used throughout the industry, I recommend either it or Atom. There's options like vim, but I'm assuming if you're on Windows that vim would be too hard to learn. In any case, I recommend installing Ubuntu, as Windows development is 😬. It'll probably be pretty difficult to get things going, but being able to use linux/unix machines is a very valuable skill in an of itself.
bloodaxe · 2018-07-07 18:36
>>9320 That would be a better option if I already had some technical knowledge, but I am a complete noob when it comes to anything computer or math. So overloading myself with a professional IDE would be too overbearing. I mean, I couldn't even figure out CodeBlocks >>9321 >>9324 Thank you for that but I am searching for a windows solution since I don't have another laptop to install Linux (If I would had it, I would install Solus, that's how noob I am) and my parents will not buy me another one just for programming.
pop · 2018-07-07 19:56
>>9342 Atom.io And look up how to install cool packages for atom. It's the thing I'd recommend every beginner/noobie.
bloodaxe · 2018-07-08 16:55
>>9343 I tried installing it but it doesn't work. But from the pictures I saw, I loved it
Boris Grishenko · 2018-07-08 21:37
>>9378 "it doesn't work" is not enough information for us to be able to help you. Also, you don't need to fill out the name or email field to post on imageboards.
bloodaxe · 2018-07-10 13:41
>>9384 it's my tag . Sorry, when I click on Atom's installer after extracting the zip, nothing happens.
Roy Batty · 2018-07-20 22:14
Should programmer write functions that are used only once? There is this example in clean code book //Check if the employee is elegible for full benefits if ((employee.flags & HOURLY_FLAG) && (employee.age > 65)) The book say we should replace that with: if (employee.isElegibleForFullBenefits()) Because the last one is more expressive and thus removes the necessity for the comment, but what if that function is only used in that case and never again?
Joe Bloggs · 2018-07-21 09:15
>>9512 What do you think the problem with that is?
Project 2501 · 2018-07-21 15:15
>>9533 I don't know, when I was taught function I was told that we use them because there are portions of code which are repeated multiples times.
Six · 2018-07-21 23:39
>>9542 That was a motivating example, not a rule. There are a number of other reasons to use functions: expressive names, separation of concerns, testability, etc.
The Oracle · 2018-07-21 23:51
I know a lot about computer architecture and do some ASM coding. I thought I'd make a language with constructs that embody and abstract each low level element of modern computing architectures. Then I realized it would just be C with different syntax. I think I see now why C sticks around so long. Please tell me I'm hella wrong, I wasn't ready for this feel.
Acid Burn · 2018-07-22 01:28
>>9512 In this case it might be a good idea. In that particular example, if another feature be added which could need to meet the same parameter (here, "full benefits"), then you already have a function for checking that, the parameters of which you'll know where to change in the future.
Lunch · 2018-07-22 09:42
>>9542 >I don't know, when I was taught function I was told that we use them because there are portions of code which are repeated multiples times. Programming is not about following arbitrary rules to the letter. The book already explained to you why one-use functions are useful so what's the problem?
Hiro Protagonist · 2018-07-25 04:23
>>9512 Code is written to be read. If code wasn't written to be read then we would write in something primitive. The primary focus of your code should be readability and correctness. Neither one of those things are against each other. Readability aids in correctness because readable code is easy to debug, understand, extend, etc. This is something that I wish more lecturers would beat their students with: code is written to be read. No student believes these offhand comments about "expressiveness" and good comments. But I guarantee you that, if you get a job written software in any form, that the majority of your time will be spent reading code. Yes, the start of a project never sees too much code reading -- in fact it sees mostly code writing. But this is a rarity. 99% of the time you're brought in on an existing project. You need to get up to speed so you can start to be productive. You're tasked with an easy-ish task of the current TODO-list. What do you do? You read the code.
Colmerauer · 2018-07-25 17:45
I'm trying to do codeacademy for python to get a beginning start on learning to program, but ive noticed there was a significant difficulty jump about 65% of the way through when it has you do 15 different exercises. I'm having some trouble where I'll almost get the answer but can't figure out that single last step I'm missing, which only turns out to be painfully apparent to me once I see it. Is there really any point in continuing learning if I'm so untalented I can barely even handle codeacademy?
Molly Millions · 2018-07-25 17:47
>>9591 Don't worry lainon you're just learning, it's not about talent it's just about practice and drilling it into your head
Terzibashjian · 2018-07-25 18:47
>>9591 Codecademy is a very soykaf way to learn programming, lain. Don't feel bad if you're not doing well. I highly recommend you pick up a book to learn programming from instead. I'm going to recommend two books that I've personally read and are freely available online. I recommend them because they teach programming fundamentals that can be applied to any language and they both contain lots of exercises so that you're not just mindlessly consuming information. You'll be tested and you can look at the answers to see how you're doing, or maybe you'll surprise yourself and find a better solution. They happen to use Lisp but I'm not a zealot about the language, the books just happen to use it. The first book has an easier environment to set up with with DrRacket though with the advent of Portacle: https://portacle.github.io a common lisp environment isn't hard to get into either. How To Design Programs: http://www.ccs.neu.edu/home/matthias/HtDP2e/ and Common Lisp: A Gentle Introduction to Symbolic Computation: https://www.cs.cmu.edu/~dst/LispBook
array · 2018-07-25 19:17
>>9593 I'll definitely look into that first book, as I've heard of it before. Thanks for the recommendation, lain. >>9592 I know I shouldn't concern myself with talent but it's just a concept I have been obsessed with since I was a kid and is a source of substantial fear for me.
FILLER · 2018-07-25 19:28
>>9593 I briefly looked over HtDP. Maybe I don't understand their pedagogical approach, but I would recommend that book to no one. Have you used it? >>9594 There's a free intro to CS mooc on EDX from MIT that uses Python. It's highly regarded and is what that Codeacademy garbage should be.
Vasya Pupkin · 2018-07-25 20:22
>>9591 > where I'll almost get the answer but can't figure out that single last step I'm missing, which only turns out to be painfully apparent to me once I see it. Don't worry, missing painfully apparent things is just a regular part of a programmer's job. You'll get used to it.
setq · 2018-07-25 20:31
Learned Java in university and have a decent understanding of programming in general but comp.sci is very far from my field of study, are there any resources for mid-level projects to practice with? And are there any other languages (I've heard Lisp thrown around alot, I already know Python as well) that lainons would recommend for self-teaching? My primary field of interest is /sec/ so any language optimized for networking would be ideal
Nell · 2018-07-25 23:55
>>9595 It says that the course is not currently available. Any other suggestions?
string · 2018-07-26 00:32
>>9599 A lot of people like Harvard's CS50x. I have no experience with it though. >>9600 A book is not a course with a grader bot for code and a forum for help.
Trinity · 2018-07-27 13:59
>the most influential programming language on earth >most linux utils written on C >no high-order functions that can take functions as arguments or yiled functions as values How do you guys even use this crap?
Iverson · 2018-07-27 15:03
>>9621 you posted this on /g/ already glitterboy
Liet Kynes · 2018-07-27 16:27
>>9512 I was going to buy Clean Code but this post makes me super glad I didn't.
Chan Siu Ming · 2018-07-27 20:25
>>9621 You can 100% do both of those things in C. Look up qsort on manpage 3 for an example.
Naomi Nascimento · 2018-07-27 22:23
> Have a lot of JS code. > Made logging facility with various logging levels. > redefine logging function to no-op. > Google closure compiler isn't smart enough to optimize them out on its own. > Don't really want all those strings in production code. > Miss C's #ifdef > Start writing a parser for a JS preprocessor to add C style conditional compilation directives... > think, "Wait, someone has done this already, I'm sure there's a "right way" to do it. > see this: #ifndef in javascript https://stackoverflow.com/questions/7376131/ifndef-in-javascript > As I presume you know, Javascript doesn't have preprocessor directives like C/C++, but you can use regular if statements that are evaluated at run-time like this: if (typeof myFunc === "undefined") { var myFunc = function(a,b) { // body of your function here } } Yeah, done that already... > keep reading... > GPP preprocessor > http://en.nothingisreal.com/wiki/GPP #define debugMode #ifdef debugMode var myFunc = function(a,b) { // body of your function here } #else var myFunc = function(a,b) { // body of your alternate function here } #endif Sweet! but... i keep reading: > I see that that the answer provided by jfriend is a bit old when node.js is not around. Pls. check the latest preprocessor.js (available through npm install). > You can use the static conditions like below (from documentation) // #ifdef FULL console.log("Including extension"); // #include "path/to/extension.js" // #else console.log("Not including extension"); // #endif Huh, that's cool. So, I'll just node.js in the dev pipeline, no prob. ... keep reading. > "Deprecation notice: Preprocessor.js has been deprecated in favor of MetaScript, a much more JavaScripty way for build time meta programming using JavaScript itself as the meta language. Okay... nevermind. Keep reading. > If you are trying to get better inlining or eliminate dead code you can use google's closure compiler along with the /** @const */ helper /** @const */ var G=true if(G){var d=document} function dummy(){if(!G){var d=document}return d.getElementsByTagName("body")[0]} function hello(name) { alert(dummy() + name + dummy()); } hello('New user'); Holy soykaf that's ugly, and doesn't fix the fact that I need a macro, something like LOG(), that I can make a No-OP via something like #define LOG( msg ) {} so I don't have to scatter soykaf like the above all through my code. Nevermind. Looks like I'm making a preprocessor for JS. Would just use C's preprocessor but it pukes on some of my complex regexp. tldr, How many hitmen would it take to fix Javascript?
Hagbard Celine · 2018-07-29 01:27
How many hours a day should i try to dedicate to learning as a pure beginner?
sizeof · 2018-07-29 06:15
>>9636 depends on your age. When I was 6 computers were rare. Only got to use one in the Computer Lab, and only to play learning games for about an hour a week. Being a tinkerer I figured out you could boot the AppleII without a disk and type at the terminal. Some games were written in Apple BASIC, so if you put the disk in later (or upside down) and typed "list" it would dump all the program contents. I would just do that and press random keys since the thousands of lines would scroll by till class was over. The teacher couldn't stop me from doing it so she gave me a BASIC book. Spent as much time as I could programming. I got a used IBM 286 soon after. Spent half the night programming and exploring almost every night. All the free time I had, I was coding. Learned C, Assembly, and Pascal before I was in middle school, my first sold program was a grade keeping software (a precursor to modern spreadsheets). If you've got the time, pour all of it in. You won't have the time when you're older and you'll regret it. Today I have a growing "project ToDo list" that will take several lifetimes to complete. I've moved up the timetable for migration to a cybernetic body in hopes I can finish most of the cool things I wanted to do. The more you learn the more you will likely want to be able to do, and the less time you have to do it. Learn fast and now. There's no reason not to. I had to earn $400 for a C compiler by doing chores around the neighborhood. I had to pay out the nose for BBS time to upload my programs. My parents tried to ground me from my hardware. Today everyone has a smartphone and/or PC, and full access to documentation, free compilers, etc. IMO: if someone makes it through teenage years without knowing how to code just by exposure to the Internet, they probably don't want to develop software. Think about it: There are people like me out there. They've started their kids on programming at age 4, and my kids are adults now... They are your competition. Better not waste any time playing catch up. Start here, you won't regret it. http://nand2tetris.org/
The Plague · 2018-08-02 00:10
I got locked out of my mysql root user and have been trying to get back in all day. I encountered this same problem as this guy https://stackoverflow.com/questions/11657829/error-2002-hy000-cant-connect-to-local-mysql-server-through-socket-var-run Looking at the top replied comment about the /etc/mysql/my.cnf file, I have the file, but I'm not sure what to do with it. It's here. orpheus@Roedelius:/etc/mysql$ ls conf.d debian-start my.cnf.fallback mysql.conf.d debian.cnf my.cnf mysql.cnf It's not clear to me what the top answer says I should do with the my.cnf file to solve the error 2002 /var/run/mysqld/mysqld.sock problem I've been getting. I'd appreciate if anyone could help me with this.
McCarthy · 2018-08-02 00:27
>>9724 I opened the my.cnf file in nano and this is whats in it that is missing in the error 2002 !includedir /etc/mysql/conf.d/ !includedir /etc/mysql/mysql.conf.d/ I don't know what to do from here. Please help me.
↑ · 2018-08-04 10:24
hello Lainons, last few months I've been here on this board to see what's the best way and where to start learning computer programming, and a lot of people say learn Lisp, Scheme, etc. Now, I know how to do recursion and how to do it on nested arguments. I know how to build basic functions on Lisp and Racket(Scheme) using Lambda Expressions. "The Little Schemer' really helped me to understand recursion... so Lainons, what next? Am I on the good road? Should I not rush to another and another but rather understand every detail on every topic? My plan is after finishing reading "The Little Schemer", I will procede to HtDP (which I stopped reading because I don't understand lambda until I read TLS), and after some HtDP, will procede to SICP. thank you Lainons I appreciate you all guys
Tyrell Wellick · 2018-08-04 20:53
>>9898 Congratulations lain! I'm happy for you and I kinda wish I'd done it that way. Just keep at it, perhaps soon enough you'll be reading SICP or any of several superb books which use lisp. Ganbatte!
Judge Fang · 2018-08-05 03:51
I'm currently working on a curses interface for a small organization app I'm making in Ruby, but I'm not sure I'm doing this right. I'm in the early stages of learning curses, so I'm trying to experiment with making small programs. What I want to do is -Display the input prompt -Have user type in a character -If character is "~", exit. However, I have a small bug in the script: When I start it up, the screen is blank, and the input prompt only appears after I press a character. Any tips? INPUT_STR = "Type a few lines of text, or press '~' to quit!\n" require 'curses' def init_curses() Curses::init_screen win = Curses::Window.new( Curses.lines, Curses.cols, #Set window to be as large as terminal window 0, 0) #Start window on top-left corner win.clear win.setpos(30, 0) win.addstr(INPUT_STR) win.refresh return win end $window = init_curses input_ch = nil # After initializing, change the position and put some text $window.setpos(10, 0) sleep(2) # After changing the location, try drawing the same text again while (input_ch != "~") $window.addstr(INPUT_STR) $window.refresh input_ch = Curses::getch $window.addstr(input_ch) $window.refresh $window.clear end $window.clear #Prevent output after exiting $window.close Curses::close_screen
The Fin · 2018-08-05 04:42
>>9907 I don't use ruby or curses, but my guess would be you need an extra window.refresh. The issue may be specific to your platform/terminal. The way I would proceed is by poking it with a stick and referring to the Curses::Window documentation.
HELIOS · 2018-08-05 07:50
I want to learn Java programming at least the basic stuff ( OOP, Polymorphism, control flow ect..)Is it possible to do so in a months time for someone who has done a bit of programming but not too much; if so how would I go about doing it? What types of pdfs do I need, exercise sites ect..
Pris · 2018-08-05 09:19
>>9912 Have a look here: https://moocfi.github.io/courses/2013/programming-part-1/ I went through both parts in about a month but I had prior programming experience. The course is exercise driven so it's particularly good if you learn by doing.
Judge Fang · 2018-08-05 14:24
>>9908 Okay... I rewrote the script and narrowed down the problem code: $window.addstr(INPUT_STR) $window.refresh input_ch = $window.getch Basically, I think the error lies in the fact that there's two types of "getch" methods and two "refresh" methods; one for the window and one for the entire "Curses" environment. I was using the "Curses" version of getch, but using the "window" window of refresh, so it wasn't showing up. I'll ask on SO to see if this is the correct reasoning, but for now, my program works! So thank you!
Chan Siu Ming · 2018-08-05 16:18
I need help with a function: if(bolaColisiona(siguientePosicion)) { direccion = cambiarDireccion(direccion); printf("ASDASDASDASDASDASDASDASD"); } bolaColisiona(int*) is meant to detect collisions of a ball, the parameter is a pointer to an int array of size 2 that hold the coordinates. It returns true or false int bolaColisiona(int* siguientePosicion) { return (siguientePosicion[0] == 0 || siguientePosicion[0] == 14 || siguientePosicion[1] == 0 || siguientePosicion[1] == 49) } The problem is that the if is never true The limits of the grid are 0, 14, 0 and 49 for the upper, lower, right and left limits respectively. I use this code to print the grid void imprimirTablero(int *posicion) { system("cls"); int i, e, flag; for(i = 0; i < 15; i++) { for(e = 0; e < 50; e++) { if(i == 0 || i == 14 || e == 49 || e == 0) { printf("#"); continue; } else { if(i == posicion[0] && e == posicion[1]) { printf("O"); } else { printf(" "); } continue; } } printf("\n"); } Sleep(250); }
Judge Fang · 2018-08-05 18:47
>>9916 I don't really know what's going wrong with the program, but if I were to debug it, the first thing I would do is forget about printing the table while debugging. The logic to display the game should be separate from the logic that controls the ball. Additionally, It won't allow you to print helpful error messages. To ensure that the ball is indeed colliding, I would rewrite the function in this way. By decomposing it and adding the relevant print statements, it should be a lot easier to see what's going on in the code: #define BOLA_X_MINIMO 0 #define BOLA_X_MAXIMO 14 #define BOLA_Y_MINIMO 0 #define BOLA_Y_MAXIMO 49 int bolaColisiona_X(int x) { return x == BOLA_X_MINIMO || x == BOLA_X_MAXIMO; } int bolaColisiona_Y(int y) { return y == BOLA_Y_MINIMO || y == BOLA_Y_MAXIMO; } int bolaColisiona(int* sigientePosicion) { int choca_x = bolaColisiona_X(*sigientePosicion); int choca_y = bolaColisiona_Y(*(sigientePosicion + 1)); printf("Posicion: (%d,%d)\n", *sigientePosicion, *(sigientePosicion+1) ); printf("Choca (X)? %s \n" (choca_x)? ("SI") : "NO"); printf("Choca (Y)? %s \n" (choca_y)? ("SI") : "NO"); return choca_x || choca_y; } I added the constants to make the program a bit more flexible (if you change the max to be 17 instead of 14, then you'll have to change it in at least three places) If you let the code run, you'll be able to see exactly which function returns Y/N whenever the ball is at a given (X/Y). Let me know if this helps!
Marly Krushkhova · 2018-08-05 19:27
>>9919 Thanks, I fixed the bugs.
Six · 2018-08-05 19:52
How do you actually start a project? I've read some introductory books but I've never actually done a project and feel lost on how to start it all. For example, I'm thinking of writing a simple IRC client for my first project but I'm not sure where to start.
Judge Fang · 2018-08-05 20:21
>>9921 Awesome! What was wrong with it?
Lady Jessica · 2018-08-05 23:46
>>9924 I don't remember really, there was many little bugs This is the final code: #include <stdio.h> #include <stdlib.h> #include <windows.h> #define false 0 #define true 1 #define DERECHA_ARRIBA 0 #define DERECHA_ABAJO 1 #define IZQUIERDA_ARRIBA 2 #define IZQUIERDA_ABAJO 3 #define LIMITE_SUPERIOR 0 #define LIMITE_INFERIOR 14 #define LIMITE_IZQUIERDA 0 #define LIMITE_DERECHA 49 void obtenerSiguientePosicion(int *posicionBola, int direccion, int *siguientePosicion); int bolaColisiona(int *siguientePosicion); int cambiarDireccion(int direccion, int *siguientePosicion); void imprimirTablero(int *posicionBola); int main() { int posicionBola[2] = {7,25}; int siguientePosicion[2] = {0}; int direccion = rand() % 3; while(true) { obtenerSiguientePosicion(posicionBola, direccion, siguientePosicion); if(bolaColisiona(siguientePosicion)) { direccion = cambiarDireccion(direccion, siguientePosicion); continue; } obtenerSiguientePosicion(posicionBola, direccion, posicionBola); imprimirTablero(posicionBola); } return 0; } void obtenerSiguientePosicion(int *posicionBola, int direccion, int *siguientePosicion) { switch(direccion) { case DERECHA_ARRIBA: siguientePosicion[0] = posicionBola[0] - 1; siguientePosicion[1] = posicionBola[1] + 1; break; case DERECHA_ABAJO: siguientePosicion[0] = posicionBola[0] + 1; siguientePosicion[1] = posicionBola[1] + 1; break; case IZQUIERDA_ARRIBA: siguientePosicion[0] = posicionBola[0] - 1; siguientePosicion[1] = posicionBola[1] - 1; break; case IZQUIERDA_ABAJO: siguientePosicion[0] = posicionBola[0] + 1; siguientePosicion[1] = posicionBola[1] - 1; break; } } int bolaColisiona(int* siguientePosicion) { return (siguientePosicion[0] == LIMITE_IZQUIERDA || siguientePosicion[0] == LIMITE_INFERIOR || siguientePosicion[1] == LIMITE_IZQUIERDA || siguientePosicion[1] == LIMITE_DERECHA); } int cambiarDireccion(int direccion, int *siguientePosicion) { switch(direccion) { case DERECHA_ABAJO: if(siguientePosicion[0] == LIMITE_INFERIOR) return DERECHA_ARRIBA; return IZQUIERDA_ABAJO; case DERECHA_ARRIBA: if(siguientePosicion[0] == LIMITE_SUPERIOR) return DERECHA_ABAJO; return IZQUIERDA_ARRIBA; case IZQUIERDA_ABAJO: if(siguientePosicion[0] == LIMITE_INFERIOR) return IZQUIERDA_ARRIBA; return DERECHA_ABAJO; case IZQUIERDA_ARRIBA: if(siguientePosicion[0] == LIMITE_IZQUIERDA) return IZQUIERDA_ABAJO; return DERECHA_ARRIBA; } } void imprimirTablero(int *posicion) { system("cls"); int i, e, flag; for(i = 0; i <= LIMITE_INFERIOR; i++) { for(e = 0; e <= LIMITE_DERECHA; e++) { if(i == LIMITE_SUPERIOR || i == LIMITE_INFERIOR || e == LIMITE_DERECHA || e == LIMITE_IZQUIERDA) { printf("#"); continue; } else { if(i == posicion[0] && e == posicion[1]) { printf("O"); } else { printf(" "); } continue; } } printf("\n"); } Sleep(150); } Would you review it? I can translate it to English if you want
Liet Kynes · 2018-08-06 00:07
>>9924 Ah I remember now, the most important bug was that the change in direction of the ball is different when it collides with the laterals and horizontals limits of the grid. For example, if the ball is moving to right and up and collides with the upper limit, the direction changes to right and down, but if the same ball collides with the right limit the change in direction is left and up. I only had coded the first case. >>9922 What books have you read? See pic related, IMO that is what you have to learn, to draw a general map of the architecture of the IRC and then expanding each part into its own map. I once read that good programmers plan the entire software before they start writing code. I am also interested in writing an IRC, if you want we can discuss something. I have still to learn C sockets though
Judge Fang · 2018-08-07 15:37
>>9928 Sure! I can review it! I trust that it works, so I won't go too much into functionality. I'll just do some things *I* would have done a bit differently. - while(true) is a fairly dangerous thing to have sometimes because you'll never be able to exit (unless you CTRL-C/D). I would have somewhere that allows you to press a button that exits. But again, not really too much of an issue. -You copy a lot of the code where you get the next direction. Additionally, a lot of your code could be simplified with the ternary operator (condition) ? (value if true) : (value if false). I'll do a couple of statements, but I'll leave the rest to you. I would also change from using #defines to enums (makes it easier to run in a debugger: https://www.quora.com/Which-is-better-using-enum-or-define-to-define-constant-value-Why). void cambiar_XY(int* siguientePosicion, int cambioX, int cambioY) { *siguientePosicion += cambioX; *(siguientePosicion+1) += cambioY; } #define INCREMENTO 1 #define DECREMENTO -1 void obtenerSiguientePosicion(int* posicionBola, int direccion, int* siguientePosicion) { // Asignacion de una posicion vieja a una nueva *siguientePosicion = *posicionBola; *(siguientePosicion+1) = *(posicionBola+1); //VVV Lookup the "Ternary Relational Operator" if you're unsure about this VVV int dx = (DERECHA_ARRIBA || DERECHA_ABAJO) ? INCREMENTO : DECREMENTO; int dy = (DERECHA_ARRIBA || IZQUIERDA_ARRIBA) ? INCREMENTO : DECREMENTO; cambiar_XY(siguientePosicion, dx, dy); } int cambiarDireccion(int direccion, int* siguientePosicion) { switch(direccion) { case DERECHA_ABAJO: return (*siguientePosicion == LIMITE_INFERIOR) ? DERECHA_ARRIBA : IZQUIERDA_ABAJO; /* rest of code */ } } ... // Last one. This one's on the house ;) else { int imprimir_O = i == posicion[0] && e == posicion[1]; // Yes! You can even use the ternary operator in printf!!! // https://stackoverflow.com/questions/27457762/conditional-inside-printf-statement printf("%s", (imprimir_O) ? "O", " "); continue; } Finally, I'm just spitballing here, but I don't see a case where you hit a corner (both LIMITE_INFERIOR and LIMITE_IZQUIERDA)... You might want to account for that in the rare case that it happens. Hopefully this helped! Overall, you have great decomposition, and learning in depth for the programming constructs C will help you immensely! Happy programming!
Judge Fang · 2018-08-07 15:38
>>9950 Sorry for crap formatting. I keep forgetting to use spaces instead of tabs when I post code online. Ah well
Donna Hawthorne · 2018-08-08 17:22
>>9950 I don't understand how this works int dx = (DERECHA_ARRIBA || DERECHA_ABAJO) ? INCREMENTO : DECREMENTO; int dy = (DERECHA_ARRIBA || IZQUIERDA_ARRIBA) ? INCREMENTO : DECREMENTO; I know how the ternary operator works. The thing is that I defined DERECHA_ABAJO as 1, so the first conditional will always be true. The second conditional will always be true too because IZQUIERDA_ARRIBA is 2 I realised that in the main function I calculate the next position twice. The first one is to check if the ball collides and the second is to replace the current position with the next one (if it doesn't collide). I replaced the second call of obtenerSiguientePosicion() with a new function called reemplazarPosicionActualConSiguiente (replaceCurrentPositionWithNext). void reemplazarPosicionActualConSiguiente(int *posicionActual, int *siguientePosicion) { posicionActual[0] = siguientePosicion[0]; posicionActual[1] = siguientePosicion[1]; } Is it bad to use global variables? The program only has 3 variables and every function uses almost all of them. Wouldn't it be better to make them global instead of passing them around as parameters? Plus it would save a little ram
Yu-ichi · 2018-08-08 21:44
>>9962 >Plus it would save a little ram It wouldn't, and in order to try and reason this way you need to have far more experience with a particular architecture and auditing the generated code. I don't think globals are appropriate here, but I would say that while globals are error prone, many of the ways of avoiding or encapsulating globals you may come up with are error prone in similar ways.
Morpheus · 2018-08-10 02:16
void insert(LinkedList* l, const float f, const int i) { int j; Node *temp, *n; temp = l->head; n = (Node*)malloc(sizeof(Node)); n->val = f; n->next = 0; if (i == 0) { n->next = temp; l->head = n; return; } for (j = 0; j < i - 1; j++) temp = temp->next; n->next = temp->next; temp->next = n; } I'm trying to create a linked list in C. Is it possible to remove the edge case where i is 0?
Judge Fang · 2018-08-10 14:46
>>9962 Ah fuarrrk forgot to actually add a check. That's what you get when you mix pseudocode with actual code, I guess. Anyways, it should be: int dx = (posicion == DERECHA_ARRIBA || posicion == DERECHA_ABAJO) ? INCREMENTO : DECREMENTO; >Is it bad to use global variables? As this anon said: >>9969 , there's nothing inherently wrong with global variables, but they do end up making your program harder to maintain (what would happen if you accidentally changed the variable in a function? How much time would you spend trying to find where you changed it incorrectly? I ask because having one or two globals isn't the end of the world, but it very quickly gets difficult to manage. ) >>10006 I'm looking through your code, and I *think* I understand what's going on. To answer your question, no. I don't think there would be because you need some way of changing what the "head" of your list is. If you're inserting something at the beginning of your list, you need to "push" something out of the first slot. Also. Watch out for the for loop you wrote. Because you didn't include brackets, it'll compile, but it'll only run the first line (temp = temp->next). void insert(LinkedList* l, const float f, const int insert_pos) { Node *temp, *node_to_insert; temp = l->head; // create new linked list createNode(node_to_insert, f, 0); // if inserting at the start of the list, then // change the location of the head if (insert_pos == 0) { node_to_insert->next = temp; l->head = n; return; } // Go to the i'th position int index; for (index = 0; index < insert_pos - 1; index++) { if(temp->next != NULL) { temp = temp->next; node_to_insert->next = temp->next; temp->next = node_to_insert; } else break; } }
Trinity · 2018-08-10 19:50
>>10010 You are performing link mutations at every step through the loop.
Judge Fange · 2018-08-10 21:52
>>10012 God damn it. Knew I shouldn't be programming early in the morning. In my defense, I was confused by what should be inside the for loop, so I just assumed what they wanted to do (albeit incorrectly) To defend my honor, a less incorrect version is below for(int ind = 0; ind < insert_pos - 1; ind++) temp = temp->next; node_to_insert->next = temp->next; temp->next = node_to_insert;
Cowboy · 2018-08-14 16:17
can someone share programming perls book?
Hacker · 2018-08-14 20:03
>>10085 http://libgen.io/search.php?req=programming+pearls
Unsigned · 2018-08-15 02:34
Hello, new and totally confused web scraper here. Little backstory, recently started searching for jobs as a freelancer, and this is my first one. I got tasked to scrap some data from a sport statistics/betting site and suddenly found an error I don't understand. Basically, the html data I get from the site when running the script (Python, requests and BeautifulSoup) is quite different to the stuff that loads in the browser. Now, doing a little research, it appears to be that there are two main reasos that might be happening: User agent and javascript. For the first one, I did set the user agent to Chrome's because if I didn't set one I would get 403 so, yeah. Adressing the second one, it seems to be that JS is not even an issue. Reading the source, the only relevant part of JS is one that just changes the display from none to block. All the data is already there. Also, disabled JS in Chromium, Firefox and Qutebrowser and the data seems just fine, I just can't access to it without changing the style manually. So, my question would be: does somebody know what the fuarrrk is going on? I'm not really knowledgeable in webstuff, so I don't know if there's something obvious I'm not seeing.
藤原純一 · 2018-08-15 03:02
>>10089 Oh, the webpage is https://betalyst.com/tips-zone/. Hope I'm not breaking any rules by posting it. If I am, please just remove the post.
Judge Fang · 2018-08-15 09:57
>>10089 >>10090 $ wget --user-agent="Mozilla/5.0 Firefox/55.0" -O tz.htm 'https://www.betalyst.com/tips-zone/' $ grep -F -e '<table class="todayList' tz.htm | wc 3 726 20418
if · 2018-08-15 14:48
>>10092 Alright what the heck, that worked... Thank you. Does somebody know why the output of my script may differ?
Lukasiewicz · 2018-08-15 15:26
>>10092 Alright, sorry to keep bothering. But that worked like, once. Now it gets a binary file for some reason, godjammit. $ wget --user-agent="Mozilla/5.0 Firefox/55.0" -O tz.htm 'https://betalyst.com/tips-zone/' --2018-08-15 11:23:15-- https://betalyst.com/tips-zone/ Resolving betalyst.com (betalyst.com)... 192.124.249.62 Connecting to betalyst.com (betalyst.com)|192.124.249.62|:443... connected. HTTP request sent, awaiting response... 301 Moved Permanently Location: https://www.betalyst.com/tips-zone/ [following] --2018-08-15 11:23:15-- https://www.betalyst.com/tips-zone/ Resolving www.betalyst.com (www.betalyst.com)... 192.124.249.62 Connecting to www.betalyst.com (www.betalyst.com)|192.124.249.62|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 12039 (12K) [text/html] Saving to: ‘tz.htm’ tz.htm 100%[========================================================================================================>] 11.76K --.-KB/s in 0.01s 2018-08-15 11:23:15 (922 KB/s) - ‘tz.htm’ saved [12039/12039] $ grep -F -e '<table class="todayList' tz.htm | wc 0 0 0
Rick Deckard · 2018-08-15 17:36
>>10096 If you want to know what's going on, you have to look at the headers and the page content. Web scrapers are fragile by nature and you can't expect other people to help when things break.
Jane Doe · 2018-08-15 23:10
>>10096 The 301 response is caused by the fact that, rather than copying the command from >>10092, you decided to remove the 'www.' part for some reason. However on my end the site still responds with the full document of size ~50K after the 301, so I am unable to replicate your size 12K result. To move this along you could state how you determined the 12K document to be "a binary file", post the output of running 'file' on it, upload it somewhere and post a link since the site will usually give at least a hint of what went wrong, post a 12K wget run with --server-response added before --user-agent, or even post the source code that is giving you trouble.
Cereal Killer · 2018-08-17 20:49
not really a simple question, huawei stopped offering bootloader unlock keys to customers. I'm wondering if its possible to reverse it from a collection of unlock codes available rn if people are willing to submit them. Any inputs?
Unknown · 2018-08-17 21:29
>>10107 You would want to start by reverse engineering the firmware.
JARGON · 2018-08-17 21:40
>>10108 so independent of the unlock code mechanism they use?
let · 2018-08-18 15:06
I'm doing an exercise (C language) to check if a given Sudoku is correct, but I'm facing with a little problem. The input is something like this (53467891267219534819834256785976142342685379171392485696153728428419635345286179 [with each 9-number disposition representing a row in the sudoku]). I'm having difficult figuring out how to transform that string in an int matrix for me to work on (is there a better approach?).
Linda Lee · 2018-08-18 15:09
This is such a simple answer, but I've tried to look it up and can't seem to understand it. I'm trying to append a string to the front of another string in C++, but I can only figure out how to place it at the end of the string. Here's an example #include <iostream> #include <string> using namespace std; int main() { string ext; ext = "txt"; ext.append("del /S *."); cout << ext; } Outputting txtdel /S *. When I would like the output to be del /S *.txt I know it's a really stupid question, but any help would be seriously appreciated.
Dozer · 2018-08-18 15:21
>>10117 Okay, prepend is the word I'm looking for. Apologies, it's been a late night.
nil · 2018-08-18 15:31
>>10117 >>10118 Solved, I should have used the insert function but I was having trouble figuring out how to use it properly.
Zero Cool · 2018-08-18 16:53
Any ideas of c projects that involve linux system calls?
Unidentified · 2018-08-18 17:11
>>10120 ive been playing around with seccomp lately. Maybe find some vulnerable version of software and try to mitigate exploits by applying seccomp filters. Writing your own version of strace can be fun
Random · 2018-08-19 04:31
>>10116 Yeah, it'll most likely be easiest to reason about if you put it into a 9x9 matrix. Which part is giving you trouble? The entire concept of parsing an input string? Allocating and filling a matrix? What have you tried so far?
JARGON · 2018-08-20 19:29
Hello Lainons, Two things on my mind today that you might have something to say about. Firstly, I want to start a new hobby project, which will be an IRC bot like literally every other hobby project of mine, and learn a new language while doing it. Recommend me a language you think is fun! Good base unicode support is a must, and I already know Python and Go rather well. Other than that anything goes! Secondly, when I was looking at potential languages for this, I noticed that when a JVM language came up I kind of leaned towards it because Java is what we use at my job. So these things stood out because they might be useful for work. But I don't program in my spare time to become a better moneymaker for my boss, I do it because it's fun. On the flipside, if I don't learn any other """industry-ready""" languages than Java, I might be stuck in Javaland forever. How do you people handle this?
The Phantom Phreak · 2018-08-20 20:49
Kotlin if you want something you might use at work, Elixir if you want something trendy, and Red if you want something different.
DavidGabriel · 2018-08-20 21:16
>Recommend me a language you think is fun! Rust lang! it pretty fun and actually I like it. but don't take this advice cuz I just start learn it couple days ago. Racket, or Guile scheme, but I'm not sure about unicode support. finally, cuz you know java and you use it. I hilght recommned to lean scala. (•ω•)
Lukasiewicz · 2018-08-20 23:21
>>10100 Well, turns out the problem was that the python HTML parser kinda is like kicking dead whales down the beach, lxml worked like a charm. About the binary file, turns out it was a gzipped version of the website, I have no idea how that ended up there. And, about the 301, I was running that on a later time, so didn't needed to copy it. I also knew that it was irrelevant, as it was a redirection. I might be a noob but I can read c; Anyway, thanks for the help lains!
Yet Another Lainon · 2018-08-21 09:11
+1 for Racket and Rust Racket's handling of Unicode is up to task. You could look into Clojure since your (presumably) comfy with the JVM, I know little about it though. The way strings in general are handled in Rust is from another world. if you like Python and Go then Rust will definitely open your eyes in a good way, though the road to learning is a long one.
The Fin · 2018-08-21 11:37
write in pure C++ while trying to use as many of the new things introduced in the C++14/17 standard as possible.
Unidentified · 2018-08-21 11:43
>>10157 AAAAAAAAAAAAAAAAHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
The Oracle · 2018-08-21 12:45
>>10158 You made my day. The funny/sad thing is I write C++ for a living. But yeah, there is nothing fun about C++... >>10149 > I might be stuck in Javaland forever You know Python and that is widely used in the industry so there is allways a way out for you.
Crash Override · 2018-08-22 19:57
What would be the best way to create a string array in C++ without knowing the size? I have a for loop that grabs data and stores it as a string, but I need to store all of the strings that loop produces in a string array without knowing the size. For background, I am using the libconfig C++ library to grab data from a file, and from there I need that to return a value in the form of a string array. Please forgive the stupid question, I'm a first semester student working way ahead of class materials. try { for (int i = 0; i < cfg.getRoot()["files"].getLength(); ++i) { // Only output the record if all of the expected fields are present. string filetype; if (!(cfg.getRoot()["files"][i].lookupValue("filetype", filetype))) continue; cout << filetype << endl; } } catch (const SettingNotFoundException &nfex) { // Ignore. }
Bob Arctor · 2018-08-22 23:35
>>10171 There are lots of ways, including reallocing it every time you find a new item, but the easiest would be to create a vector (google it), then call your_vector.emplace_back(thing) for each thing. You can convert it from a vector to an array at the end if you need to.
Nobody special · 2018-08-24 18:10
my pycharm matplotlib is not working. I'm doing the code correctly, and the directories seem to be all right, and the figure shows up, but the plot itself does not show even though i have done plt.show()
Leto Atreides I · 2018-08-24 18:11
>>10190 could it be that im using arange?
Spooky · 2018-08-28 12:38
C questions that google couldn't answer me. I want to create a function to close a file (int close_file(FILE *arq)). But how do I verify if I was able to actually close the file (this verification to be put inside the function. [Return 0 able, return something else unable])? feof, setting equal to NULL, something like that?
FILLER · 2018-08-28 14:58
>>10219 Not sure what are you asking. Are your using fopen/fclose from stdio? If yes then fclose returns 0 if successfully closed the file: http://www.cplusplus.com/reference/cstdio/fclose/ Check the return value of fclose and map it to your own error code if you want. If your trying to recreate fclose function from stdio then I suggest finding a implementation of fclose and checking what it dose.
Milner · 2018-08-28 20:25
Lainons, I need help with css selectors. I've been at this all day and I cant get either one selector to catch both <tr>'s as one or each one individually. I want the ones inside <table CLASS="datadisplaytable>. pls and thanks you https://paste.sh/bxCvhsMP#e5s_gmh3knfUkZ9aNLWm8ri9(Don't use an external service to upload a program of yours, unless it can't reasonably be avoided.)
Elliot Alderson · 2018-08-29 00:44
>>10223 Upload somewhere without an expired certificate. Until then you can try something generic like: table.datadisplaytable tr { /* do stuff here */ }
Yamaoto Toshi · 2018-08-29 08:35
>>10226 >table.datadisplaytable tr This picks up the table within each row aswell. I want the root rows only
roll · 2018-08-29 09:36
>>10230 >the table within each row >the root rows We can't blindly guess your document structure. You will have to post a usable version of your document.
null · 2018-08-30 14:10
Whats wrong with this AVL tree inplementation? It wont print 15, if its inserted at the end. Here is code i was inspired by https://www.geeksforgeeks.org/avl-tree-set-1-insertion/ and Appel book #include <string.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> typedef struct tree *T_tree; struct tree { T_tree left; int key; T_tree right; int height; //int size = 0; }; T_tree Tree (T_tree l, int k, T_tree r) { T_tree t = malloc(sizeof(*t)); t-> left=l; t-> key=k; t->right = r; if (l==NULL && r == NULL) { t->height = 1; } return t; } //bigger of 2 integers: int max(int a, int b) { if (a>=b) { return a; } else { return b; } } //actual height of tree int height(T_tree t) { if (t==NULL) return 0; return t->height; } T_tree rightRotate(T_tree t) { T_tree t1 = t->left; T_tree t2 = t1->right; //rotation: t1->right = t; t->left = t2; //update heights: t->height = max(height(t->left), height(t->right))+1; t1->height = max(height(t1->left), height(t1->right))+1; return t1; }; T_tree leftRotate(T_tree t) { T_tree t1 = t->right; T_tree t2 = t1->left; //rotation: t1->left = t; t->right = t2; //update heights: t->height = max(height(t->left), height(t->right))+1; t1->height = max(height(t1->left), height(t1->right))+1; return t1; }; //get balance factor of node N int getBalance(T_tree node) { if (node == NULL) return 0; return height(node->left) - height(node->right); } T_tree insert(int key, T_tree t) { if (t==NULL) { return Tree(NULL, key, NULL); } if (key < t->key) { Tree(insert(key,t->left), t->key, t->right); } else if (key > t->key) { return Tree(t->left, t->key, insert(key, t-> right)); } else return Tree(t->left, key, t-> right); //update height of this node t->height = max(height(t->left), height(t->right))+1; //is node becomed unbalanced? int balance = getBalance(t); if (balance>1 && key > t->left->key) { t->left = leftRotate(t->left); return rightRotate(t); } if (balance < -1 && key < t->right->key) { t->right = rightRotate(t->right); return leftRotate(t); } return t; } void preOrder(T_tree root) { if(root != NULL) { printf("%d ", root->key); preOrder(root->left); preOrder(root->right); } } int main(int argc, char const *argv[]) { T_tree t1 = NULL; t1 = insert(10, t1); t1 = insert(20, t1); t1 = insert(30, t1); t1 = insert(40, t1); t1 = insert(50, t1); t1 = insert(15, t1); preOrder(t1); return 0; }
Incognito · 2018-08-30 14:12
>>10238 Thats weird i copy-pasted it from sublime text, where i have ok indentation. Sorry
Unsigned · 2018-08-30 17:30
wwhat is ddifferent from princ tto print?
Crazy Jake · 2018-08-30 17:35
>>10242 are you drugged lain? lol
Zuse · 2018-08-30 23:53
>>10238 >Whats wrong with this AVL tree inplementation? You have both C problems and AVL problems. - The height recomputation is pasted around numerous times with trivial changes. It needs to go into a recomputation and an in-place update function. - The node creation function leaves all non-leaf heights uninitialized. All heights should be initialized properly to put the node into a consistent state. - For the body of your max function look up the ternary conditional expression. - In insert you can't return on the > branch because that would skip the balancing. - On the < branch the newly created node is not stored anywhere, so it is popped off the stack and lives on as a memory leak. - All nodes replaced with newly built nodes must be freed. - On the key equality branch with a set implementation there's no point in building a new node. - With the way you are trying to combine single and double rotations you never do a single rotation on its own, so your balancing strategy is wrong. As a test case, an empty tree with insertions of (3, 2, 1) must result in a single rotation, but your code does nothing. You have to split up the single rotation and double rotation cases. - Printing a BST in pre-order rather than in-order is a curious choice.
wtf · 2018-08-31 15:54
>>10245 Can anyone help with this hacker rank puzzle: https://www.hackerrank.com/challenges/reverse-shuffle-merge/problem Reading other people's solutions, I still don't get the algorithm. It looks like people are using min-heaps to look ahead for viable permutations of the letters that give the lexically smallest result, but I can't fully grasp how you that is put together. The part I get is: 1) scan the string backwards 2) If you are out of chances to see a letter you must take it. 3) You decide to add a letter to your string if you think it is lexically smallest you can get without causing a conflict down the road. The part I'm stuck on is how to best look down the road. This is supposed to be a greedy algorithm, so I can't imagine it want me to simulate a bunch of branches going way ahead in the algorithm. Shouldn't a greedy algorithm be making very local decisions?
Cypher · 2018-08-31 17:49
not >>10245 , but if you want an example of a working AVL tree: http://0x0.st/sty2.c
Chani · 2018-08-31 20:43
>>10250 >an example of a working AVL tree >http://0x0.st/sty2.c At first glance your code seems to employ only single rotations, but this impression might be wrong. Out of curiosity, and to verify this impression, precisely what tree is produced from an empty one by inserting (3, 1, 2)?
Batou · 2018-08-31 22:21
Hello everybody im completely new to programming. I plan on getting an EE degree when I get out of the navy and my goal as of right now is to know the ins and outs of the hardware/software of computers to try to get a taste of everything and see which niche i find fun. I plan on getting a mba afterwards and hopefully have my own business with said niche. right now i am starting out with python with the book learning python the hard way. i was then going to learn the C book from the same author before delving into C and SICP books then going into assembly then branching off from there. Am i on the right track or do you guys know a better/more fundamentally sound way to approach this? Thank you for your time in advance.
Mentat · 2018-08-31 23:03
>>10250 I just noticed that you are using the keys as a set, like the other Lain >>10238, and you have a quick return path from node_insert. There is nothing wrong with that in itself. What is wrong, however, is that >current->data = data; >return root; you have a memory leak on the old data pointer, which is immediately overwritten and silently lost, since in your current design it cannot be communicated to the outside world by node_insert which is already tasked with returning the root.
Tequila · 2018-08-31 23:31
>>10242 You mean in Common Lisp ? Hang on I’ll open my PERSONAL JUST BOUGHT USED COPY OF COMMON LISP THE LANGUAGE 2nd EDITION print is like prin1 but with trailing whitespaces prince is like prin1 but it’s output has no escape characters (no surrounding double quotes around strings...) >The general rule is that output from princ is intended to look good to people, while output from prin1 is intended to be acceptable to the function read.
Void · 2018-09-01 15:35
Lainons, I want to get better at C. What books can I read besides The C programming language?
Hopper · 2018-09-01 17:10
>>10257 Do you mean in the case where they insert the two things with the same key? >>10253 Aah, yes it is incorrect. It does rotate 3 and 1, but produces a linear chain of 1-3-2. I know that case worked when I had a recursive definition of height, but I later converted it to a field on the node, and I guess I did my math wrong.
The Plague · 2018-09-01 17:14
>>10274 Me again. Interesting though, when I insert 0..9 in numerical order, it works perfect. I took another look at the 3, 1, 2 case. It incorrectly calculates the height of 3 (the one in the middle). Its right child is 1 but its left child is NULL, and its height is also recorded (incorrectly) as 1. The other two heights are correct. I will have to look at it again later.
Lunch · 2018-09-01 21:00
>>10274 >>10275 >the case where they insert the two things with the same key? Yes, that is your "quick return path from node_insert", and that is the only place where the old data pointer is overwritten, since the other branches use node_new. >produces a linear chain of 1-3-2 >I guess I did my math wrong >when I insert 0..9 in numerical order, it works perfect >look at it again later While you may have had a previous working version, it had to have looked quite different, because changing the height calculation does not cover the issue. The root cause is that using single rotations exclusively is insufficient to balance an AVL tree. Double rotations are also needed, and this is what the empty+(3, 1, 2) case exposes. You can see the other AVL Lain >>10238 trying to use double rotations exclusively, which is also insufficient. The reason some of your test cases worked is that they were special cases that only required single rotations to balance.
Ivan Horvat · 2018-09-02 18:25
Lainons, i need some help here. It's about operational systems. I want to know which one of these programs is the most efficient, using the time it takes to conclude, and varying the buffer from 1,2,4,8,16,..... until 1.048.576 bytes. i will make a graph in execution time per bytes, for each program. First I made a datafile, using the following command on root: dd if=/dev/zero of=datafile bs=1024 count=10K Then I have the following programs, which are the ones i need to compare the execution time of each one for each measure of bytes in the buffer. The first one uses system calls, i named it prog_syscall: main(){ char buffer; int i; i = read(0,&buffer,1); while (i>0){ write(1,&buffer,1); i = read(0,&buffer,1); } } The other one, uses library routines, i named it prog_libc: main(){ char buffer; int i; i = fread(&buffer, 1, 1, stdin); while (i>0){ fwrite(&buffer, 1, 1, stdout); i = fread(&buffer, 1, 1, stdin); } } I am trying to use the following commands to each one of them: – $ time prog_syscall < datafile > /dev/null – $ time prog_libc < datafile > /dev/null But I am getting this error message: zsh: command not found: prog_syscall Thing is, I don't know how to get all the execution time for each program. I wish I could find a way to make a list of each time of execution, and the bytes in the buffer for that execution time. This for each program. But I can't even make this show me the execution time. If anyone could help me out with this, I would be grateful.
Pulse · 2018-09-02 22:25
>>10290 You first need to compile your programs. Usually: cc my-code.c -o my-exe chmod u+x ./my-exe ./my-exe
drop · 2018-09-02 22:30
>>10290 And you must include stdio.h You should read a beginner tutorial about C programming. It won’t hurt.
drop · 2018-09-02 23:47
>>10297 I noticed that I had to include stdio.h I've managed to make it work, just had to compile it and execute time ./prog_syscall < datafile > /dev/null
swap · 2018-09-03 01:23
How do I install gentoo on a raspberry pi? Preferably without using crossdev because it requires an existing system with the distribution on it.
Random · 2018-09-03 22:48
>>10298 Nice you succeeded :)
Church · 2018-09-03 22:51
>>10271 21th century C Mastering algorithms with C
Jim Hilger · 2018-09-03 22:54
>>10271
Naomi Nascimento · 2018-09-04 17:01
>>10290 Lainons, I've managed to make it run, but when i change the buffer with this piece of code the execution time doesn't change. What am I doing wrong? int tam = 10000; char *buffer = (char*) malloc(tam*sizeof(char));
bit · 2018-09-05 08:19
>>10316 It is normal. Anyway this part of the code is only « executed » once so no matter what you change there, it won’t really affect execution time if at all. When using fread, you should compute the size using sizeof(char) Oh and if you wanted to filter tam = 10000 bytes of data at once in your program, then you’ll need to update the aforementioned argument of fread accordingly so it can process at most 10000 objects of size sizeof(char).
progn · 2018-09-07 15:40
What's a good multipurpose language for home projects? Perl 6? Golang? C++?
Lain Iwakura · 2018-09-07 16:42
>>10350 What's a home project? Like home automation? C++ on Arduino and Python on Raspberry Pi are safe bets.
Knuth · 2018-09-07 17:33
>>10351 >What's a home project? I project not for work/school presumably.
queue · 2018-09-08 01:42
>>10351 Just programs for personal use.
Zhora · 2018-09-08 02:50
>>10350 They're all fine.
over · 2018-09-08 02:53
>>10350 What projects did you have in mind? Your choice of language will always come with tradeoffs. Some other questions you might want to ask yourself: Are the compiler/interpreter easy to install/uninstall on your setup? Are there libraries for the projects you have in mind? Are they actively maintained? What editor/IDE tooling exists (if any!)? Is this easily available for your setup? Are there particular aspects of the language that interest you? Do you really want to stare at code in this language for hours on end?
Roy Batty · 2018-09-09 00:31
I think I just had a really cool idea! A long time ago, I made a program that would check a range of multiplicative-duos (e.g. 1x1, 1x2... 1x999, 1x1000, 2x1, 2x2... etc.) for pythagorean triples. Then, it would record the triple into an array so if other triples were discovered, they could be checked for whether or not they were already entered into the array. The program would then print out a list of the pythagorean triples that occur within the selected range. I thought it was beautiful but the issue I had was that I had to blindly guess what dimensions my array should have. "If only there was some other way to record the information that didn't require knowing how much would need to be recorded in advance" I thought to myself. I initially had the idea of just listing all the numbers together into one big number but even floats have a limit. Then, I had my eureka moment. What about strings?! I could encode the information using a base-26 counting system and have letters represent the numbers, separate each number with a 0 in the string and then separate each triple with a 1 and then finalise the string with a 2. Am I correct in believing that strings don't need to have a preset length? At the moment, in my beginners' book, I've seen char arrays. I think my idea of freely adding to a string comes from things I vaguely recall reading on C++ from earlier attempts to get into programming several years ago. So, what do you think guys? Rather than use arrays, just use a string?
Lukasiewicz · 2018-09-09 00:50
>>10372 Aww man. It's just as a I feared. In C, strings have to have a fixed length. In C++ however, the strings' length doesn't need to be specified. Darn it.
if · 2018-09-09 03:14
>>10372 https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-24.html#%_thm_3.69
Eldon Tyrell · 2018-09-09 03:41
>>10372 >If only there was some other way to record the information that didn't require knowing how much would need to be recorded in advance You can do this using dynamic memory allocation. in C, the appropriate calls are malloc and free. There are libraries that will provide dynamic allocation on the fly for you. I'm sure you'll be exposed to them as you continue reading your book, but if you want to implement one yourself, the basic idea is that you malloc an array, and add to it until you get to the point where you can't anymore. At that point, you malloc a bigger array, copy the contents of the older array into it, and free the old array. something like (pseudo code, everything except the item to add should be passed by reference.) add_to_dynamic_array(item_to_add, array, size, current_index){ current_index++; if (current_index > size) { tmpArray = malloc(size * 2) // use a for loop to copy contents of array into tmpArray old_array = array array = tmpArray free(old_array) } array[current_index] = item_to_add; return array; }
Elliot Alderson · 2018-09-09 07:07
sizeof · 2018-09-09 11:55
>>10374 Wow. The SICP actually has a question like that in it. I've been seeing the book for years but just disregarded it as a meme. I guess I'll give it a go at some point. >>10375 Thank you so much for letting me know that C can do stuff like that. I appreciate it.
Dozer · 2018-09-10 08:45
I know php, but wouldn't mind moving to something better. What language/framework should I use to make my relatively simple webpage. HTML alone is not an option.
Pulse · 2018-09-10 09:00
I had a thought recently: Are programming languages "natural"? Is it possible that the development of programming languages has been steered in a particular direction due to whatever hardware has been most popular or was pushed by an institution of sorts? Just to give an example, there was a company that made a new kind of harp that could do chromatic notes but nobody was really making compositions that used the harp so they had Maurice Ravel do it. Rather than music be a pure expression of one's feelings, Ravel instead composed a piece because he was asked to in order to help a company advertise their product. The process of music creation was distorted by corporate interests. Are programming languages "distorted", perhaps? https://www.youtube.com/watch?v=bBm1w8J63mg
hash table · 2018-09-12 18:31
>>10391 Your thinking is too narrow. You have constrained the act of corporations as not naturally human, but they are indeed naturally human. Programming languages are natural in the same way everything humans create is natural. This is not too different than considering a beehive or honeycombs natural for bees. The only distinction between natural and unnatural is some arbitrary restriction.
Masami Eiri · 2018-09-14 06:41
>>10402 Oh, I see. Well, in that case, I guess I should rephrase my question: What role, if any, have corporations played in the form of programming languages? Suppose one lived in a world where it was unanimously agreed upon that it is right and just that 50% of the taxpayer's money goes to those with an IQ above 130 and either intend to work or are working in a tech-related career. Suppose all the brainy people in the tech field no longer see programming as a mere job then and that it really is just a hobby. In such a society then where programming is just a hobby, what form would programming languages take, if that form were to be different at all?
Church · 2018-09-15 17:13
>>10411 they might look more like ruby and less like .NET
dup · 2018-09-15 21:20
I want to make a link to go to a url that is dynamically made, but I don't know how to do this with my code. Here is my Router class ` class Router { public $routes = [ 'GET' => [], 'POST' => [] ]; public static function load($file) { $router = new static; require $file; return $router; } public function get($uri, $controller) { $this->routes['GET'][$uri] = $controller; } public function post($uri, $controller) { $this->routes['POST'][$uri] = $controller; } public function direct($uri, $requestType) { if (array_key_exists($uri, $this->routes[$requestType])) { return $this->routes[$requestType][$uri]; } throw new Exception('No route defined for this URI.'); } } and here is my routes page <?php $router->get('', 'controllers/index.php'); $router->get('message', 'controllers/message.php'); $router->get('loginForm', 'controllers/loginForm.php'); $router->get('register', 'controllers/register.php'); on my page with my html I put an <a>tag with a dynamic link href='displayPost<?php echo $image->id; ?> but I'm not sure how to add that $image->id; part into my router list and class to make dynamic url's.
fsociety · 2018-09-20 04:43
>>10427 I don't know PHP, but if you'd like I'd be interested in helping you achieve what you want in a different language. PHP is just all around a bad language, but all of this stuff can seem like wizard magic if you're not familiar with it. How much programming experience do you have, if you'd want to tell me?
Iverson · 2018-09-21 12:40
GUYS I NEED A HELP! I need to make yet another REST API, it should represent flights and tourists, i could add, edit remove tourists, and add edit, remove flight, typical methods. My question is could i write OOP code in REST api? Cause it sounds to me like OOP-approach, so i thought about making class Flights and class Tourists and make GET,POST,PUT methods as methods of these particular classes. Can i do it? ANOTHER PROBLEM - both classes has methods that "intercept" themselves - i mean remove flight from tourist - method in Tourist class, and remove tourist from list of passengers - method in Flights class, should i inherit list of tourists in both classes? And how does OOP-approach works in Javascript? App should be in javascript, do you recommend any specific stack?
Sipho Nkosi · 2018-09-22 14:52
>>10477 You first design your database / What tables / What columns. Typically, you’ll have a Tourist table and a Flight table. You could look at ORM and a simple framework with basic routing routines should do. Then Heroku for deployment because it’s free with a PostgreSQL database.
Jane Doe · 2018-09-22 21:34
>>10486 Yes i started to make it in pure Javascript as in: https://www.youtube.com/watch?v=eB9Fq9I5ocs Main problem is: that values of 2 of the arguments of schemas are taken from another schema. I mean: var touristSchema = mongoose.Schema({ name: { type:String, }, surname: { type: String, }, gender: { type:String, enum: ['Male','Female', 'other'], }, country: { type:String, } listOfFlights:[flightSchema], }) AND var flightSchema = mongoose.Schema({ arrivalDate: { created: {type:Date, default:Date.now}, }, departureDate: { created: {type:Date, default:Date.now}, }, placesToSitInPlane: { type: Integer, } listOfTourists: [touristSchema], }) As you see: list of Tourists is number of Tourists that takes this flight (number must be less than placesToSit) it means i need to iterate in some way through all Tourists in tourists.collection and find how many of them booked this flight. I dont know how to do it. Also right now POST new tourist dont work and i have no idea why? Here is all my code: Tourist model: var mongoose = require('mongoose') //import Flight from './flight.js' var touristSchema = mongoose.Schema({ name: { type:String, }, surname: { type: String, }, gender: { type:String, //enum: ['Male','Female', 'other'], }, country: { type:String, } //listOfFlights:[flightSchema], }) var Tourist = module.exports = mongoose.model('Tourist', touristSchema) module.exports.getTourists = function(callback, limit) { Tourist.find().limit() } module.exports.getTouristById = function(id, callback) { Tourist.findById(id, callback) } module.exports.addTourist = function(tourist, callback) { Tourist.create(tourist, callback) } Flight model: var mongoose = require('mongoose') //import Tourist from './tourist.js' var flightSchema = mongoose.Schema({ arrivalDate: { created: {type:Date, default:Date.now}, }, departureDate: { created: {type:Date, default:Date.now}, }, placesToSitInPlane: { type: Number, } //listOfTourists: [touristSchema], }) var Flight = module.exports = mongoose.model('Flight', flightSchema) module.exports.getFlights = function(callback, limit) { Flight.find(callback).limit() } module.exports.addFlight = function(flight, callback) { Flight.create(flight, callback) } App.js: var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var mongoose = require('mongoose') Flight = require('./models/flight') Tourist = require('./models/tourist') mongoose.connect('mongodb://localhost/airport?flights', {useMongoClient:true}) var db = mongoose.connection app.get('/', function(req, res) { res.send('Hello World') }) app.get('/api/flights', function(req, res) { Flight.getFlights(function(err, flights) { if (err) { throw err } res.json(flights) }) }) app.post('/api/flights', function(req, res) { var flight = req.body; Flight.addFlight(flight, function(err, flight) { if (err) { throw err; } res.json(flight); }) }) app.get('/api/tourists', function(req, res) { Tourist.getTourists(function(err, tourists) { if (err) { throw err } res.json(tourists) }) }) app.post('/api/tourists', function(req, res) { var tourist = req.body; Tourist.addTourist(tourist, function(err, flight) { if (err) { throw err; } res.json(tourist); }) }) app.get('/api/tourists/:id', function(req, res) { Tourist.getTouristById(req.params._id, function(err, tourists) { if (err) { throw err } res.json(tourist) }) }) app.listen(3000) console.log("Running on 3000")
藤原純一 · 2018-09-23 22:35
>>10488 On the first problem, when a tourist books a flight, you have as input both the flight and the tourist. By updating both lists at the same time, you won’t have to iterate over every tourists. I don’t know if that’s clear enough feel free to ask more. Now I’m no JS expert so I can’t address your second issue, sorry .
nil · 2018-09-24 14:59
>>10501 I did one one of those functions but i forget i had to connect to db, then i tried to use mongodb client instead of mongoose, because i dont like json schemas a lot... And i fuarrrked up something and i think i need to start it again for a third time... But maybe you could help, well ill try... So i have function: function findAll(collection, cb) { var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost/"; MongoClient.connect(url, function(err, db, res) { if (err) throw err; var dbo = db.db("flights"); dbo.getCollection(collection).find({}).toArray(function(err, res, result) { if (err) throw err; cb(result) }); db.close(); }); } I wanted to use it in GET request to get all documents so: app.get('/api/tourists', (req,res) => { findAll("tourists", function(result) { res.send(result) }) }); But its not working. If i connect and try to make GET request in postman i got nothing as response (but if i try to console.log result in function it logs to terminal - very weird), but i dont get any error in terminal... But if i make POST which seems to be working function addToDb(object, collection) { var MongoClient = require('mongodb').MongoClient; var url = 'mongodb://localhost/'; MongoClient.connect(url, object, collection, function(err, db) { if (err) throw err; var dbo = db.db("flights"); if (object.length > 1) { dbo.collection(collection).insertMany(object, function(err, res) { if (err) throw err; console.log(object.length + " documents inserted"); db.close(); }); } else { dbo.collection(collection).insertOne(object, function(err, res) { if (err) throw err; console.log("1 document inserted"); db.close(); }); } }); } app.post('/api/tourists', (req, res) => { const tourist = [{ id: tourists.length + 1, name: req.body.name, surname: req.body.surname, gender: req.body.gender, country: req.body.country, birthDate: req.body.birthDate, listOfFlightsById: req.body.listOfFlightsById },]; tourists.push(tourist); addToDb(tourist, "tourists") res.send(tourist); }); and THEN i try sending GET request i get this error in terminal: /home/nedlo/node_full/expr_demo/node_modules/mongodb/lib/operations/mongo_client_ops.js:466 throw err; ^ MongoError: doc parameter must be an object at Function.create (/home/nedlo/node_full/expr_demo/node_modules/mongodb/node_modules/mongodb-core/lib/error.js:43:12) at insertOne (/home/nedlo/node_full/expr_demo/node_modules/mongodb/lib/operations/collection_ops.js:847:18) at executeOperation (/home/nedlo/node_full/expr_demo/node_modules/mongodb/lib/utils.js:420:24) at Collection.insertOne (/home/nedlo/node_full/expr_demo/node_modules/mongodb/lib/collection.js:463:10) at /home/nedlo/node_full/expr_demo/index.js:26:33 at result (/home/nedlo/node_full/expr_demo/node_modules/mongodb/lib/utils.js:414:17) at executeCallback (/home/nedlo/node_full/expr_demo/node_modules/mongodb/lib/utils.js:406:9) at err (/home/nedlo/node_full/expr_demo/node_modules/mongodb/lib/operations/mongo_client_ops.js:286:5) at connectCallback (/home/nedlo/node_full/expr_demo/node_modules/mongodb/lib/operations/mongo_client_ops.js:241:5) at process.nextTick (/home/nedlo/node_full/expr_demo/node_modules/mongodb/lib/operations/mongo_client_ops.js:463:7) at process._tickCallback (internal/process/next_tick.js:61:11)
Torvalds · 2018-09-24 23:38
>>10518 Not >>10501. This looks a bit curious to me: >if (object.length > 1) >insertMany(object, >else >insertOne(object, Shouldn't you get the element out of object for the insertOne call? You may also want to provide for the length zero case.
Zuse · 2018-09-25 14:55
>>10526 insertMany is for inserting array of object, insertOne - for one object (json - name, surname etc). Those are mongo functions
Zhora · 2018-09-25 23:09
>>10538 That does not address my question. Are you certain that giving insertOne the array of length 1 like the code in >>10518 does, instead of the element of that array, is valid? To me, having never used mongodb, that does not seem valid, just based on the docs: https://docs.mongodb.com/manual/reference/method/db.collection.insertOne/ https://docs.mongodb.com/manual/reference/method/db.collection.insertMany/ As an additional hint, here's the source file with the definition of insertOne: https://github.com/mongodb/node-mongodb-native/blob/master/lib/operations/collection_ops.js The latter starts with the following conditional: function insertOne(coll, doc, options, callback) { if (Array.isArray(doc)) { return callback( MongoError.create({ message: 'doc parameter must be an object', driver: true }) ); }
Terzibashjian · 2018-09-26 14:17
Lainions, what do you think about Pascal? It's surely not a popular language, but does it have a special circle like Lisp or APL? I doubt so though, as it provides nothing special.
Technician · 2018-09-26 15:05
>>10551 >Pascal Isn't it kind of like C with vectors? My only experience with it is linking the BLAS library in C before I realized cblas.h existed.
Boole · 2018-09-26 15:28
>>10552 > Lainions, what do you think about Pascal? pascal is elegant but boring, so there's not going to be a "hackernews revival", unlike some of the other fad languages from the past. it has all the features necessary for structured progamming, but no clever functionality you'd find in e.g. functional languages (there are no first order fuctions >>10551
Emmanuel · 2018-09-26 17:16
>>10552 >C with vectors? How vectors differ from arrays?
Y.T · 2018-09-27 08:04
>>10551 It's not that bad. It was the first programming language I have learned back in the late 90s. I remember it had a build in module for doing simple graphics and simple module for terminal control (something like curses but simpler). At least the Turbo Pascal version I used then had those modules. The default IDE was also nice and add to this a very good documentation (with examples of code to almost all functions) and that was a perfect language for me to start programming back then (I was without a internet connection back then). Now it's not used very often (especially in the industry) as the market is dominated by Java or C++. If you know how to program then there is no real reason to learn it, if your just starting to learn then you might be interested in giving it a try (you can use Free Pascal). Also DoomRL was writen in Pascal, so bonus points for that. All that said you should keep in mind that programming language is only a tool and it more important what you do with that tool then haw it looks in comparison with other languages.
Kay · 2018-10-02 17:46
I have a dumb issue. My loops aren't terminating upon meeting the conditions and I'm at lost of what's happening. https://pastebin.com/2ks9evQT I already tried running the program with a string being previously initiated instead of scanning text and skipping the first loop, that's how I know the second loop isn't working.(Don't use an external service to upload a program of yours, unless it can't reasonably be avoided.)
Splicer · 2018-10-02 18:45
>>10679 Here's what I recommend you do: 1) compile your program with debug symbols (gcc -g main.c -o main) 2) load your program in gdb (gdb ./main) 3) run it (run) 4) step (next or step) through every instruction, printing every variable of the program (print Findex, print String[Findex]...) at each step. You'll probably think I'm an asshole for refusing to point out the problem in your program but you'll thank me later, debugging is a crucial skill that is rarely taught in school.
Cowboy · 2018-10-02 18:52
>>10679 Maybe it would help to pretend you are the computer and run through the loop with a pen and paper. Keep track of Index and String. Below is what I think is happening if you don't manage to catch it yourself. Index = 0 String[0] = ? while (String[0] not_eq '#') = False* String[0] = getchar() Index=1 while (String[1] not_eq '#') = False* String[1] = getchar() Index=2 and so on. The code is checking String before the user types '#' everytime. Note that because String[Index] is unititlizatied, there is random data inside so it will occasionally be '#' by accident and stop the loop. Hope this helps.
Pulse · 2018-10-02 23:10
>>10683 Actually I debug all my programs, that is how I know the loops are not working and for example not another issue like getchar not getting the string. >>10684 >and so on. The code is checking String before the user types '#' everytime. I'm aware of this, I've seen it happen on the debugger and it has happen on other programs I've made but I still can't come up with a persistent solution. I'm thinking of redesigning the program with another variable to specifically control when do the loops end.
Lunch · 2018-10-02 23:13
>>10679 You've already been told what's wrong with your first loop: you are accessing uninitialized memory in String and your check is always one step ahead of the last assignment. You need to perform the check on the character you've just read. The problem with your second loop is that you are using 'or' to combine your tests, so you only terminate on two consecutive '#' characters. 'Or' only becomes false when both its constituents are false. If you want to keep your current design you need to switch to 'and'. You can also check for the first '#' once, before the loop, and only check Sindex in the loop, thus halving your tests. You are currently testing each character twice, once at Sindex and on the next step again as Findex, which is wasted work. You also have several problems in isei. One of your intended equality tests is an assignment. A semicolon immediately after an if condition makes the if block have an empty body, and makes the following statement unconditional. Using >if (Second == 'I' or 'i') does not test Second against both 'I' and 'i'. It makes 'i' itself the second part of the 'or', which is always true. To get the desired effect you need to repeat 'Second ==' after the 'or'. As a minor point, printing a newline character at the end of your last output line would be a good idea. After you make this version work, you could think about how to limit user input to the size of String, so that you don't start writing outside of it and overwrite things on the stack. You might also take this opportunity to read up on finite state machines, which will allow a cleaner solution to this problem and will be a useful addition to your toolbox.
Tomohisa "Tom" Kanezaki · 2018-10-03 18:53
>>10693 >your check is always one step ahead of the last assignment. You need to perform the check on the character you've just read. I know but I can't come up with a fitting solution. I just tried using a scanf to get the first character before the loop and synchronize the loop but still gets stuck at the same point. > 'Or' only becomes false when both its constituents are false That's really interesting, so or should be seen as a joint thing in these cases? Either way the new design check only against Findex. >You also have several problems in isei[...] I hope this new design is better char isei (char First, char Second) { if (First == 'E') { if ((Second == 'I') or (Second == 'i')) return 1; } else if (First == 'e') { if ((Second == 'I') or (Second == 'i')) return 1; } else return 0; } >After you make this version work Right now only the second loop is working properly. >As a minor point, printing a newline character at the end of your last output line would be a good idea. Also done but it would had happen anyway upon seeing it actually print. >you could think about how to limit user input to the size of String, so that you don't start writing outside of it and overwrite things on the stack I've heard about "dynamic strings" but I'm unsure how far deep are they into my book. >You might also take this opportunity to read up on finite state machines, Tell me more
BloodCat · 2018-10-03 22:49
>>10702 >I know but I can't come up with a fitting solution. In C and friends assignments are expressions. Their value is the value they just assigned. You can take advantage of this to move getchar into the while condition: while ((String[Index] = getchar()) not_eq '#') >That's really interesting, so or should be seen as a joint thing in these cases? "joint thing" is a rather vague term that will not help with 'or' versus 'and'. You can think about a while loop with a two part 'or' test like this: in an RPG in a room with two monsters you may advance after defeating both. While the first monster is_alive() or the second monster is_alive() the fight continues. Both is_alive() tests must become false for the fight to end. >I hope this new design is better This works as intended. After everything else works as well, this could be simplified in various ways, such as by combining the 'E' and 'e' tests in the same way as the 'I' and 'i' tests, so that you do not have to duplicate the latter. >I've heard about "dynamic strings" but I'm unsure how far deep are they into my book. I simply meant that you could stop taking user input when either you get a '#' or the character count reaches the storage limit. >Tell me more After things work you can start here: https://en.wikipedia.org/wiki/Finite_state_machines
Void · 2018-10-04 02:30
Hello lainons. I have a question about Haskell. How can I make a function that recieves a list such as [a,b,c] and returns me a list of combinations of all elements of the sublists such as (given the example) [[a], [b],[c],[a,b],[a,c],[b,c],[a,b,c]] ?
Iverson · 2018-10-04 03:46
>>10708 http://rosettacode.org/wiki/Power_set#Haskell
Knuth · 2018-10-04 10:48
>>10708 >[a,b,c] >[[a], [b],[c],[a,b],[a,c],[b,c],[a,b,c]] (A) Write a base case for the empty list or the one element list. With more elements, separate the first and call yourself recursively on the rest, then return the result of the subcall concatenated with prepending the separated first to each element of the subcall result. After everything remove the empty list, if you wish, which will be first. (B) Count up from 0 to 2^items-1 in binary and for each number output the input list with elements included/excluded if the bit value in that position is 1/0. To exclude the empty list start counting from 1 instead of 0.
Emmanuel · 2018-10-04 20:39
>>10704 >You can take advantage of this to move getchar into the while condition: I've done this before with functions in other programs, I need to wrap my head around this concept. >You can think about a while loop with a two part 'or' test like this:[...] I'll have to check and see how different logic operators work depending on their true or false condition. >such as by combining the 'E' and 'e' tests in the same way as the 'I' and 'i' tests, so that you do not have to duplicate the latter. Just did this, I have to get used to streamline like this. >After things work you can start here: https://en.wikipedia.org/wiki/Finite_state_machines I think I see how it could be applied to my program, Eh... when I started people told me I should concern myself with optimization later on but I feel I should do and get up with other programming stuff like learning how to keep version control or algorithm theory. Either way the program is working as intended now.
Nguoi La · 2018-10-07 00:22
I'm learning C as my first programming language. I've finally made a program that lists palindromes, despite my inability to manipulate strings! It took me all day to get this right. #include <stdio.h> /*"ss" = "superscript" "b10exp" = "Base-10 Exponentiation"*/ int b10exp(int ss) { int counter; int num; counter = 0; num = 1; while (counter < ss) { num = num * 10; counter = counter + 1; } return num; } int numlen(float num) { int counter; counter = 0; while (num >= 1) { num = num / 10; counter = counter + 1; } return counter; } int mirror(int num1, int num2) { return (numlen(num1) - num2 + 1); } int dgtpkr(int num1, int num2) /*Digit-Picker*/ { int counter; counter = 1; while (counter <= (numlen(num1) - num2)) { if ((num1 % b10exp(counter)) == 0) { counter = counter + 1; } else { num1 = num1 - b10exp(counter - 1); } } num1 = num1 / b10exp((numlen(num1) - num2)); while (num1 >= 10) { num1 = num1 - b10exp(numlen(num1) - 1); /*10 to the TWO is in fact a THREE-digit number*/ } return num1; } int main(void) { int a; int digit; int potentially_palin; a = 10; digit = 1; potentially_palin = 1; /*make-shift boolean, sorry*/ while (a < 1000000) { while ((digit < mirror(a, digit)) && (potentially_palin == 1)){ if (dgtpkr(a, digit) == dgtpkr(a, mirror(a, digit))) { digit = digit + 1; } else { potentially_palin = 0; } } if (potentially_palin == 1) { printf("%d\n", a); } digit = 1; potentially_palin = 1; a = a + 1; } return 0; }
swap · 2018-10-07 00:30
Whilst I am quite happy to gloat about my achievement, I think I should instead be asking: How do the pros do it? What does it look like when a programmer with years of experience writes C software that creates a list of palindromes? In fact, if possible, I'd even like to see what the program would look like if the programmer had the same "no strings" limitation that I do.
Yamaoto Toshi · 2018-10-07 09:34
I'm the guy that made the palindrome program. I really wanted the mirror function to work in a way such that, you just tell it what digit you want mirrored (e.g. you're looking at the third digit in a 9-digit number, the function would just take the 3 as its input and just give the 7 as its output) but the problem was that you had to tell the mirror function what number is being looked at in combination to what digit you want to find the mirror to. This led to the mirror function needing two arguments which made readability quite poor. By making the variable "a" a global variable instead, the function can instead just take one input and give one input, just as I desired and just fetch the number being checked from the now global variable instead. The code is far more readable now, I believe. int main(void) { int digit; int potentially_palin; a = 10; digit = 1; potentially_palin = 1; /*make-shift boolean, sorry*/ while (a < 1000000) { while ((digit < mirror(digit)) && (potentially_palin == 1)){ if (dgtpkr(a, digit) == dgtpkr(a, mirror(digit))) { digit = digit + 1; } else { potentially_palin = 0; } } if (potentially_palin == 1) { printf("%d\n", a); } digit = 1; potentially_palin = 1; a = a + 1; } return 0; } It literally just reads now as "mirror digit". I'm tempted to replace the potentially_palin make-shift boolean (I had no idea C doesn't have boolean) with a char that would either hold 'y' or 'n' but beyond this, I believe I'm done and I'm ready to continue with the tutorial books in order to learn this language properly.
if · 2018-10-08 11:44
What is Spring platform? When should i use and when i am ready to learn it? Why it is so complicated to even start to use it?
Elliot Alderson · 2018-10-08 13:45
>>10765 >>10766 >a program that lists palindromes >"no strings" limitation >How do the pros do it? >a programmer with years of experience writes C software that creates a list of palindromes Here's a version from someone not in the group you asked for. It keeps your convention for main and your starting value. #include <stdio.h> #include <stdlib.h> #define ENOUGH 10 #define LIMIT 7 void work_2 (long *cache) { long k; int out = 11, inc = 11; int ceche_index = 0; for (k = 1; k < 10; k++) { cache [ceche_index++] = k; printf ("%d\n", out); out += inc; } } void work_even (int digits, int half, long *exp10, long *cache_in, long *cache_out) { long index_in = 0, index_out = 0; int inner_k; long outer_k; long outer_to = exp10 [half - 1] - exp10 [half - 2]; long left = exp10 [digits - 1]; long left_inc = exp10 [half]; long right; long right_inc = exp10 [half - 1]; long out; for (outer_k = 0; outer_k < outer_to; outer_k++) { right = cache_in [index_in++]; for (inner_k = 0; inner_k < 10; inner_k++) { out = left + right; printf ("%ld\n", out); cache_out [index_out++] = right; right += right_inc; left += left_inc; } } } void work_odd (int digits, int half, long *exp10, long *cache) { long cache_index = 0; long right; long left = exp10 [digits - 1]; long left_inc = exp10 [half + 1]; long center_inc = exp10 [half]; long outer_k; long outer_to = exp10 [half] - exp10 [half - 1]; int inner_k; long out; for (outer_k = 0; outer_k < outer_to; outer_k++) { right = cache [cache_index++]; out = left + right; for (inner_k = 0; inner_k < 10; inner_k++) { printf ("%ld\n", out); out += center_inc; } left += left_inc; } } int main (void) { long exp10 [ENOUGH]; int k, digits, half; long *cache1, *cache2; long cache_size; long *cache_swap; exp10 [0] = 1; for (k = 1; k < ENOUGH; k++) { exp10 [k] = 10 * exp10 [k - 1]; } cache_size = exp10 [(ENOUGH - 1) >> 1]; cache1 = malloc (cache_size * sizeof (long)); cache2 = malloc (cache_size * sizeof (long)); work_2 (cache1); digits = 3; half = 1; while (digits < LIMIT) { work_odd (digits, half, exp10, cache1); digits++; half++; if (digits < LIMIT) { work_even (digits, half, exp10, cache1, cache2); digits++; cache_swap = cache1; cache1 = cache2; cache2 = cache_swap; } } free (cache2); free (cache1); return 0; } Output match and timing comparison: $ cgcc () { gcc -O3 -o bin/"${1%.c}" "$1" ; } $ cgcc c10765.c $ bin/c10765 > out/c10765.txt $ cgcc lain.c $ bin/lain > out/lain.txt $ diff out/c10765.txt out/lain.txt $ sha1sum out/* cd7b88f77c5c7a4a32ab39d9f83c560e311edbe3 out/c10765.txt cd7b88f77c5c7a4a32ab39d9f83c560e311edbe3 out/lain.txt $ noprint () { sed -r -e 's#^([ ]+)(printf[ ]*\(.+\);)$#\1; /* \2 */#' "$1" > "${1%.c}"-noprint.c ; } $ noprint c10765.c $ diff c10765.c c10765-noprint.c 78c78 < printf("%d\n", a); --- > ; /* printf("%d\n", a); */ $ cgcc c10765-noprint.c $ noprint lain.c $ diff lain.c lain-noprint.c 14c14 < printf ("%d\n", out); --- > ; /* printf ("%d\n", out); */ 35c35 < printf ("%ld\n", out); --- > ; /* printf ("%ld\n", out); */ 60c60 < printf ("%ld\n", out); --- > ; /* printf ("%ld\n", out); */ $ cgcc lain-noprint.c $ time bin/c10765-noprint real0m3.084s user0m3.080s sys0m0.003s $ time bin/lain-noprint real0m0.001s user0m0.000s sys0m0.000s >I am quite happy to gloat about my achievement >gloat Since that is how you feel, perhaps you could post the time for your version up to one billion, if you have the patience to wait it out. $ sed -r -e 's/^#define LIMIT .+/#define LIMIT 10/' lain.c > lain-lim10.c $ diff lain.c lain-lim10.c 5c5 < #define LIMIT 7 --- > #define LIMIT 10 $ cgcc lain-lim10.c $ bin/lain-lim10 > out/lain-lim10.txt $ wc out/lain-lim10.txt 109989 109989 1065537 out/lain-lim10.txt $ sha1sum out/lain-lim10.txt 11d7036b1802b2806c97b89991e796c665811e51 out/lain-lim10.txt $ sed -r -e 's/<[ ]*1000000\)/< 1000000000)/' c10765.c > c10765-billion.c $ diff c10765.c c10765-billion.c 67c67 < while (a < 1000000) { --- > while (a < 1000000000) { $ noprint lain-lim10.c $ cgcc lain-lim10-noprint.c $ noprint c10765-billion.c $ cgcc c10765-billion-noprint.c $ time bin/lain-lim10-noprint real0m0.001s user0m0.000s sys0m0.000s $ time bin/c10765-billion-noprint ^C
bit · 2018-10-08 20:49
>>10787 What the heck? Well first off, I cannot help but notice that you seem to have made two separate algorithms, depending on whether or not the number has an even or odd amount of digits (am I correct in thinking this?) in which case, I just want to assert why I think that's unnecessary. Consider a 6-digit number and you want to check that it's palindromic. What pairs of numbers do you compare? The 1st and 6th, 2nd and 5th and 3rd and 4th. Consider a 7-digit number. What pairs do you consider? 1st&7th, 2nd&6th, 3rd&5th. In both cases, there's only three pairs to consider. What really matters then in my eyes is that, for the pair being considered, that the numerical position of one has to be lower than the other one. My algorithm was designed using a "mirror" function such that it could automatically calculate what the symmetrical opposite of a digit within a number would be. It's as if there's an arrow on the left-side of the number pointing right and an arrow on the right-side pointing left and my rule is simply that as both arrows grow in length moving from one digit onto the next, the left-arrow must never neither reach nor cross the right arrow. Secondly, I'm seeing things like "k++" in your code. Is that really C? Can C do that? I thought that was strictly C++? Then there's the things where you declare multiple variables in a single line and even initialise them within the very line within which they were declared. Is this really C? I've rewritten my code to make it easier to follow through with. I consider it perhaps a bit over-commented but otherwise finalised now. #include <stdio.h> int a; /*ss means superscript and b10exp is Base-10 Exponentiation*/ /*Receives the exponent that 10 is to be raised to and then returns the result*/ int b10exp(int ss) { int counter; int num; counter = 0; num = 1; while (counter < ss) { num = num * 10; counter = counter + 1; } return num; } /*Divides the number it receives by 10 repeatedly, until the number is less than 1 to calculate LENgth of the NUMber*/ int numlen(float num) { int counter; counter = 0; while (num >= 1) { num = num / 10; counter = counter + 1; } return counter; } /*Tell it the numeric position of a digit within a number and it will find the numeric position held by said digit's symmetrical opposite. E.g. The symmetrical opposite of the 2nd digit within a 7-digit number is the 6th one*/ int mirror(int num) { return (numlen(a) - num + 1); } int digitpicker(int num1, int num2) /*Digit-Picker*/ { int counter; counter = 1; /*If the 4th digit of a 7-digit number were selected then take away 1s until the number is a multiple of 10, take away 10s until the number is a multiple of 100, etc. until 0s are all that follow on from that 4th digit*/ while (counter <= (numlen(num1) - num2)) { if ((num1 % b10exp(counter)) == 0) { counter = counter + 1; } else { num1 = num1 - b10exp(counter - 1); } } /*Then, remove those zeroes at the end*/ num1 = num1 / b10exp((numlen(num1) - num2)); /*Then finally, remove the 1,000,000s until the number is less than a 1,000,000, then remove the 100,000s until the number is less than a 100,000, etc. Until the last digit is all that remains*/ while (num1 >= 10) { num1 = num1 - b10exp(numlen(num1) - 1); /*10 to the TWO is in fact a THREE-digit number*/ } return num1; } int main(void) { int digitposition; char potentially_palin; a = 10; digitposition = 1; potentially_palin = 'y'; /*make-shift boolean, sorry*/ while (a < 1000000) { /*The numeric position of the digit being examined must be less than the numerical position of its "mirror". If that's not true, it means every digit has been compared to its mirror opposite*/ while ((digitposition < mirror(digitposition)) && (potentially_palin == 'y')){ /*Now, actually compare the digits within those numeric positions and see if they match. If they do, check the next mirror-pair and if they don't, stop assuming the number could potentially be palindromic*/ if (digitpicker(a, digitposition) == digitpicker(a, mirror(digitposition))) { digitposition = digitposition + 1; } else { potentially_palin = 'n'; } } /*If that while-loop has been exited and potentially_palin is still true, it must be because the number actually was palindromic*/ if (potentially_palin == 'y') { printf("%d\n", a); } /*Reset the digitposition, reassume the next number could potentially be palindromic (until proven otherwise) and increment a before starting the whole process again*/ digitposition = 1; potentially_palin = 'y'; a = a + 1; } return 0; } >not in the group you asked for The phrasing's a bit ambiguous. You mean, no string manipulation? It doesn't look like there was any in the code, honestly. I don't know how to "output match" but yeah, I don't mind measuring the timing for my program going up to one billion (that's 10^9, right?). It's just that I don't know to compile code on Linux so I use the online IDE available on codechef.com. I'm a bit new to Linux and all this "terminal" business.
Unsigned · 2018-10-08 21:43
I don't know why but Lainchan fudged up my code. Please copy and paste it into an IDE when you attempt to read through it in order to boost readability.
word · 2018-10-09 10:32
>>10797 >you seem to have made two separate algorithms, depending on whether or not the number has an even or odd amount of digits (am I correct in thinking this?) The algorithm is the overall one contained in the main function. The different handling based on length parity is there for efficiency. >in which case, I just want to assert why I think that's unnecessary. It is not necessary, it is an efficiency improvement. >Is this really C? Yes. >>not in the group you asked for >The phrasing's a bit ambiguous. You mean, no string manipulation? It doesn't look like there was any in the code, honestly. That refers to the poster. >>from someone not in the group you asked for. >I don't mind measuring the timing for my program going up to one billion (that's 10^9, right?). That was more of a tongue-in-cheek request rather than a serious one. Your version would take over an hour to go up to one billion, as a rough estimate. The point was merely to show you the timing comparison, which is posted above, since you asked to see other versions. And a billion is indeed 10^9. >It's just that I don't know to compile code on Linux so I use the online IDE If your code is in a file named palindromes.c you can compile it with optimizations turned on using gcc -O3 -o palindromes palindromes.c then run it with ./palindromes to see the output in the terminal. To redirect to a file you can use ./palindromes > output.txt To time it you can use time ./palindromes > output.txt
Drano · 2018-10-09 12:20
>>10811 Regarding the line "from someone not in the group you asked for", what is "the group"? I'm genuinely lost with regards to how to interpret that phrase within the context of this thread and our interaction within it. If your code is truly C, is it compatible with the C90 standard? Because a lot of the guides I seek out regarding C refer to the C90 standard, especially as that's the one most compilers support. From my understanding, C99 gets some support whereas C11 is virtually unsupported. How could my algorithm be so inefficient that it would an hour to get to a billion? Especially when it does one million just fine in a dandy amount of time? Also, I'm on Linux Mint 19 and when I use the terminal to follow through with your advice (I even changed the file's filename so that it would match what you wrote), it still didn't compile. I get: gcc: error: palindromes.c No such file or directory gcc :error: unrecognised command line option '-03' gcc: fatal error: no input files compilation terminated
The Plague · 2018-10-09 23:31
>>10812 >what is "the group"? From your post >>10766 >How do the pros do it? >What does it look like when a programmer with years of experience writes C software that creates a list of palindromes? >is it compatible with the C90 standard? $ gcc -std=c90 -o lain lain.c $ ls -l lain -rwxr-xr-x 1 ... 6024 Oct 9 11:11 lain $ file lain lain: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked ... >How could my algorithm be so inefficient that it would an hour to get to a billion? There's no need to take some random Lain's word for it, you can time it yourself. If you want to try to forcefully terminate your program before it runs to completion you can press Ctrl-C. You can see in >>10787 that your version takes 3 seconds to get to one million, and the rough estimate of over an hour for one billion is based on the observations that the search space is one thousand times larger, the digit count 50% higher and the pair count 33% higher. >Especially when it does one million just fine in a dandy amount of time? Perhaps, in the future, you will change your opinion on whether 3 seconds is "a dandy amount of time" to reach one million. >gcc: error: palindromes.c No such file or directory You need to be in the directory that contains the palindromes.c file. To get there use cd /path/to/directory/ For example, if the file is in /home/username/learningc/ you can use cd /home/username/learningc/ Alternatively, your file manager will have an option to open a terminal in its current directory. >gcc :error: unrecognised command line option '-03' Even though it might be a little difficult to see if the font is unhelpful, you can check in >>10811 that the command uses the capital letter 'O' rather than the digit '0'. You also appear to be retyping text that is already available to you in the terminal, in order to post it. If that is the case, you can select a portion of text by pressing and dragging the left mouse button, then once your selection is made you can click the mouse wheel over an editable text component to paste the selection there immediately.
Nameless · 2018-10-10 17:36
What are some options of gcc and clang that directly affects binary’s size and performances beside -O1,2,3 ?
Chan Siu Ming · 2018-10-10 17:47
>>10831 -Os optimizes for binary size. -Ofast optimizes for speed, but at the cost of standard-compliance
Anamika · 2018-10-10 20:32
>>10831 https://gcc.gnu.org/onlinedocs/gcc-7.3.0/gcc/Optimize-Options.html https://gcc.gnu.org/onlinedocs/
Bob Arctor · 2018-10-11 09:51
>>10787 Well, I finally know how to compile C code on my Linux Mint installation. Alright so according to the results: real: 146m33.091s user: 146m28.491s sys: 0m1.020s So, ha! It wasn't one hour! It was two! Nah, but seriously, when I finished the program, there was one thing that I couldn't really ignore about the algorithm. It's the fact that, in the digitpicker function I made, whenever the length of the number is needed for a calculation, it gets recalulated. There are even some while-loops where the length of the number is part of the condition which means it's getting recalculated a lot and completely unnecessarily. The solution I've come up with to resolve this is to make a new global variable called numlen_a, then numlen(a) just gets recalculated once at the start of each loop and stored in there. Every other function can just fetch the value from that variable. Done. Unfortunately, the new and improved algorithm is running right now as I type, doesn't seem that much faster. I guess the algorithm is just fundamentally flawed? (ignoring the "no strings" rule of course)
Yamaoto Toshi · 2018-10-11 11:33
>>10787 80m18s with the numlen_a tidying-up. I had no idea it was that bad. Okay, next, I will rewrite the digitpicker function such that b10exp is not necessary. I will rewrite the whole function such that one calculation of numlen(a) at the start of the loop is all that's necessary for the entire loop with that particular a-value.
J.C. Denton · 2018-10-11 12:45
>>10832 >>10838 Thanks!
pop · 2018-10-11 14:44
I'm interested in getting into assembly (64bit) programming (more for fun than purpose), and I've been looking around at a bunch of different books and such. Most seem to use either NASM or some higher level interface(like Art of Assemly's HLA), but is there anything around for fasm? Or I am I better off just using a NASM book and trying to understand the differences for fasm later? Any tips for a known good book or online resource for modern 64bit ASM?
push · 2018-10-11 18:14
>>10787 I rewrote the entire program, getting rid of the Base-10 Exponentiation function and just integrating its functionality into the DigitPicker function. So the way the program works now is that numlen(a) is only calculated once for a new a-value and then that's it. From then on, the value is just stored in a variable. With this combination with the riddance of the Base-10 Exp function, I've rewritten the DigitPicker function such that no function calls are made within any while or if conditions. Everything has been re-written to minimise the number of times a function is being called. With this, my program now attains a time (roughly) of 21m48s. I cannot believe I've brought it down to this from 2.5hours with these simple changes. I also reintroduced use of the Base10_Exp function whilst ensuring it was only used minimally. The time came out to 43m24s. I thought using functions in a program was good because it makes following what's happening easier and I guess I presumed that would follow through and make the performance better as well but now I see just how crippling they really are with regards to performance. And then, I just tried compiling your code. It only runs to 1 million but my goodness, I thought I literally could've blinked and missed it. I cannot understand what you have written and I cannot believe this level of efficiency, without strings, is attainable. Clearly, I have a long road ahead.