When Should Reading/Understanding Algorithms & Programming Logic Become Not Difficult - javascript

I've been going through JS tutorials for a week and a half (Lynda.com, and HeadFirst series). Things make general sense, but JS is not nearly as easy for me as HTML/CSS. When I look at really simple, beginner, code (e.g. Lynda.com's tutorial where you create a bingo card), I'm struggling to really read through the code in terms of the representation of logical arguments. My guess is that if I don't tackle this rightaway any other language I try to learn will be impossible, not to mention that I won't learn JS well-- or at all.
So can anybody suggest a book/web site that offers good basic instruction about algorithms? OR, am I just being too impatient and after a couple weeks, things should settle and the code will make more sense.
Here is an example of the silly basic code that still preplexes.
function newCard() {
if (document.getElementById) {
for (var i=0; i<24; i++) {
setSquare(i);
}

HTML/CSS are document description languages, a way of representing visual structure and information, they are not programming languages as such.
JavaScript is not necessarily a simple language per se, so take it easy and you could do with an elementary programming introduction book.
Try to convert what you are reading to English, line by line, in order. The syntax, the symbols and the way it is written are probably the main source of confusion as you are not used to them. People who are not used to algebra panic at the sight of it, with cries of "I will never understand that, how do you read it?" - in time you will become accustomed.
Take this simple bit of code:
1 for (var i=0; i<24; i++) {
2 setSquare(i);
3 }
Line 1: a "for-loop"
A loop is a block of code (denoted by the braces {}) that is repeated until some point. In the case of a for loop, there are 3 settings (arguments) that control the loop.
The first is for initialisation, starting conditions, in this case setting the new variable i to 0, i=0.
The second is the condition it tells the loop whether to keep going and is checked every time the loop starts over. Here the condition is i < 24, keep going while the variable i is less than (<) 24.
The final part is an increment, whatever happens in the last part happens once per list. In this case at the end of the list, before the next loop. i++ means increment i by one, shorthand for i = i + 1.
So the loop is run multiple times, i starts at 0 and goes up by 1 each time, and once it is no longer less than 24, ie. it reaches 24, it ends. So the block of code is executed 24 times, with i = 0 to 23.
Line 2: Inside the loop is a single statement, a function call, to a function called setSquare, the value i is passed to it each time.
Line 3: The closing brace of the for-loop.
So all together, this code calls the setSquare() function 24 times, with values from 0 to 23.
What setSquare() does is a mystery without seeing that code as well.

Answering your question
It seems to me you're having some problems with basic programming constructs, such as functions, loops, variable declaration, etc - and if you don't understand those you're bound to never understanding any code at all. So my suggestion is to grab a book about programming (preferably about Javascript, in your case). I never learned JS from a book as I already had a programming background so the main concepts were already there, but a friend of mine liked O'Reilly Head First Javascript. Then, when the main concepts of the language are learned, take a look at the jQuery library.
Also, two quick notes:
HTML and CSS are not programming languages
You don't need to concern yourself with algorithms, at least for now - an algorithm is a series of complex procedures designed to solve a specific problem, and not a simple for loop used to iterate an array :)

You find learning JavaScript harder than the other two more difficult because it is a programming language where as CSS and HTML are markup/styling.
JavaScript isn't an easy first language to learn either. I wouldn't be too worried if you find yourself confused, programming is hard and it doesn't come naturally to everyone. Eventually, your mindset will change and things that seemed impossible at first will seem very intuitive.
That being said, there are very few good starting resources to learn JavaScript. Your best bet is to look at a book like Head First JavaScript. They will take a very slow progression through how to program (the mentality of writing algorithms to solve problems) and also introduce you to all of the features of JavaScript.
Keep your head up : ).

I would hope that you're not having trouble with the for-loop as that's fundamental to programming.
1 for (var i=0; i<24; i++) {
2 setSquare(i);
3 }
To follow up on on #Orbling's detailed answer, line 2 reveals the main point of the program. Assuming that setSquare(i) means what it says, the for loop apparently has the side effect of changing the state of a square to the current value of i in a for loop. My guess is that the width of the square changes with i.
A key team I mentioned is "side effect", which means that a program will affect the state of another entity outside of itself. The following for loops also has a side effect.
1 for (var i=0; i<24; i++) {
2 print(i);
3 }
where I will stipulate that print(i) will render the value of i in a JS popup.

Related

AI bot for a simple game

There is a relatively simple game with such rules:
There is a safe which needs to be unlocked.
Code to the safe is a 4 digits number without repetitions(1234, 4867, 1092, etc., code like 1231 isn't possible in this game).
The game gives 5 attempts to guess the right code.
Let's say I start a new game and on the first try I test code like 0123.
The game responds with 2-1. 2 means that code 0123 has 2 right numbers which I need to use in the final unlock code. 1 means that one of those 2 numbers is at the correct position already.
After this I have 4 more exact same steps where I try different codes based on the previous tested numbers and responses from the game.
The goal is to get final code, let's say 9135(based on the prev 0123 try) and response from the game needs to be 4-4(4 right numbers, 4 in place). The earlier it happens - better.
I know that this can be solved using combinatorics just by excluding some combinations but I don't know how to choose the most weighted combination for the next try and hope AI can do it better.
I'm a frontend developer and an absolute beginner in AI. I don't really understand how complex code will be to solve this problem and what effort it requires. I will really appreciate if you can explain to me and share some links/code examples(lang doesn't matter but would be good if it is JS or Python) of similar solved tasks, so I can solve my problem based on this.
Feel free to tell me if my explanation wasn't clear, I will try more simple words then:)
Thanks!
Your game sounds similar to Mastermind, only with numbers instead of colored pegs.
Googling "Mastermind AI" leads to e.g. this implementation using a genetic algorithm to solve Mastermind, which you could probably look at for inspiration.
While #AKX is correct that this is a variant of Mastermind, a genetic algorithm might not be the first place to look, as this is probably more complex that simpler approaches.
Donald Knuth is famous (among many other things) for working out a solution to the game. There is a good overview of this approach on the Puzzling Stack Exchange site, and if you look at the other answers on that question, there is also a discussion of how to code the solution.
In your case, the simple approach is to write a function that iterates from 0000 to 9999. These are all potential answers. But, when you iterate through the numbers you want to remove (1) all numbers with duplicate digits and (2) all numbers that are inconsistent with the guesses so far. Any other numbers can be put in an array or list storing potential answers. From these remaining numbers, you can just guess any number and then continue the process.
A more complicated approach would be to make the next guess using an algorithm similar to ID3 to try to find the guess that maximizes the information gain you get from the response. But, given how much information you get from each guess, this is unlikely to be needed.

Poker hand generator and evaluator

I'm sure this topic has been covered to bits, but I've spent hours trying to work something out and I can't find enough resources that explain the process. Please note, I am new to JS and still relying on tutorials and code snippets to write code. I'm still not confident enough to write code from complete scratch.
THE GOAL:
In JavaScript, 'draw' 5 random cards
Evaluate the cards' rank among all possible hands
Return a score from a Variable min/max, based on the rank of the card, unless it's less than a pair.
Lastly, be able to draw a RANDOM hand based on rank (less than, more than, or exactly) EG. Return a hand that is of rank 100 or smaller. (could bring back 100 different hands)
Eg. While Min-Max score is 10-30. If a royal flush comes out, return 30 (best hand means best score). If low Two Pair (6H 6D 2C 2H 5S) comes out return 13. If high Two Pair (AH AD QC QH 5S), return 14. Etc.
[Those are probably not accurate scores but you get the drift]
My Research results:
Random Draw: Many applications have achieved this. My favorite so far has been this tutorial:
http://www.informit.com/library/content.aspx?b=STY_JavaScript_24_hours&seqNum=229
it is quite simple and gets the result, however does not offer a full evaluation, only by category (pair, two pair, three of a kind etc). I need an evaluation that would be able to give a higher score to the superior of two hand that have two pairs.
Evaluators: This got a bit confusing. I found a very basic evaluator, that uses javascript: http://jsfiddle.net/subskybox/r4mSF/ but it was too basic. Doesn't give me a complete rank. I found this one too: https://github.com/chenosaurus/poker-evaluator which uses the Two Plus Two algorithm and a lookup table. Now, it sounds really good, but I'm terribly confused as to how to install it on into my website, or how to use it. It says: to install: npm install poker-evaluator, which I never heard of before.
Convert rating to score: Should be fairly easy maths. Perhaps: thisRank/maxRank*(MaxScore-MinScore)+MinScore
Draw hand by rank: Haven't seen any way of doing this anywhere. Wouldn't mind seeing some examples or ideas. I'm not sure this can be done with the Two Plus Two poker-evaluator. It's more like the reverse process.
Now, it feels like I'm getting close with all this, but I'm not a 100% sure how to compile this completely. I feel like I could use the code I found in section 1, and the Two Plus Two poker-evaluator to achieve what I need. I would love to it if you could shed a light on the 'npm install', if I'm going in the right direction, or if you know other methods I could achieve the same thing.
Please don't tell me I have to try doing it myself first, because I really don't know how to do this from scratch without a little guidance.
I will post another beginner's advice :
Write the algorithm of what you want to achieve in pseudo-code (e.g., words that are easy for you to read). If the algorithm is not clear in your head before you start coding it is not going to get clearer by itself. You are not able to write code : it is fine; you hope to write a program without having a detailed low-level vision of every one of its steps : it is not. At least that is how I see things.
Example of pseudo-code that I would write for this case:
1-
create card deck
loop on number of cards to be drawn
-generate random integer and remove corresponding card from card deck
-add drawn card to hand
end loop
2-
check if hand is highest figure and associate rating
else check if hand is 2nd highest and associate rating
else...
OR
get data with all possible hands and search for this hand to retrieve score...
(see github repo)
3-
I did not get 3-
4- If you have data with all hands and their value, you just have
to search this data by value instead of searching by hand like in 2-
Second, looking for code snippets on github is a good idea; read the javascript files in the projects which interest you and understand what they do. I think you will need to install node.js for that particular project, because it is used to import the lookup table. Just download the javascript files and include them in your project...do not forget to credit/thank the author.
Third, your question is not about a precise difficulty : it is a question about how to start programming stuff when you never did it before. I do not think stackoverflow is the right place for this, but I still answered your question because after all, this is also a help forum. My last advice would be to find a good book / tutorial; in every good book there is a sample project to follow in which you develop a complete program and will teach you the basics.
P.S.: if you are really interested, don't give up because programming can be hard but it is also very rewarding to see stuff work...

Method chaining- d3.js

It says method chaining in D3.js performs several actions in single line of code. But i am not sure how much it cares about performance while executing.
For example,
By method chaining ,we would like to put the code like below:
var data =[10,20,30,40]
wrap.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("x",function(d, j) {return scale(j); })
.attr("y",function(d,i){ return (h-d)})
.attr("width",scale.rangeBand())
.attr("height",function(d,i){ return (d)})
.style("fill","red");
In the above code,it will generate 4 rectangles, then for each 4 rectangles we are setting the attribute "x","y","width","height".
No.of rectangles ---> 4 No.of attributes("x","y","width","height")
---> 4 No.of iteration for each attribute ---> 4 (sine 4 rectangles) No.of iteration for 4 attributes ---> 4*4=16 times
Is it really necessary of such number of iterations?Is it fast performance?
Normally we do like this,
wrap.forEach(function(d,i){
d.setAttribute("x", scale(i))
d.setAttribute("y",(h-d))
d.setAttribute("width",w)
d.setAttribute("height",h)
})
In the above method ,No.of iterations used --> 4
So whats the advantage of d3.js method chaining and selection.daa with the above mentioned conventional approach
Please clarify me??
I was thinking about this today.
I think there is a fundamental problem with chaining.
Namely, you cannot partition data into different shapes that easily. And, if you could, you can't assume similar attributes chained from different shapes. A square and a circle say, have different attributes to define their size and location.
But, assigned from this conflict, which is not resolved by symbols, there remains the question, which you have asked,
"Is it an efficient representation?"
It make the code look nice. But, in fact each one is a function call that can go down a deep stack for anything to happen. And, that's slow.
So, one begins to think of an alternative similar to your loop. Or, perhaps the attributes can be gathered and assigned in one last shot - almost a compilation.
Don't forget that JavaScript is interpreted.
It is easy to get deceived into thinking that JavaSript will provide the efficiency you are looking for in certain applications. Of course, a tired user clicking on this and that would not notice the difference. But, there is the animation and the interaction of working parts when changes cascade in some way. Certain applications really need the efficiency.
Even the forEach that you are using can be suspect. I was working with a younger programmer last year, using D3. And, there was some part of one of our displays that ran woefully slowly. (A tired used would have certainly been awoken into a tizzy.) We took it out of the forEach and ran it in a regular "for" loop construct. Then, the same code ran with incredible speed. So, there are parts of JavaScript that are not as ready for prime time as you might think.
It is probably better to use many of the new constructs that are making their way into the language for many parts of an application. But, when it counts, you might wait for some update and use more optimized parts of the language.
I am fairly sure that d3 is not optimal in setting attributes. And, now I am trying to think of some better representation than chaining.
Remember the act of iterating itself is negligible. If the cost of setting an attribute was 1 you are comparing 16 * 1 with 4 * 4. Therefore it's not really a big problem. The chaining is a matter of concision.
Using Big O notation to analyse the algorithms, both are O(n).

Equations Game. Finding solution for a random Goal from random Resource

I'm writing an AI for a game called Equations in Javascript.
For the sake of the question, let's pretend that the game is this simple:
There is a Goal, which can be a number(eg 5) or an expression (that can be
evaluated to a number. eg: 2+3).
There are 20 random numbers(1-9) and operators(+-*/) I can use, let's call them
the array resources[]. I need to find one combination of the elements
in resources[] that is evaluated to the Goal, let's call that the
solution (eg 1+6-2+1).
There is no limit of how many numbers or operators I can use, as long
as they are in resource[]. Once they are used, they cannot be used
again. So the longest solution might be 20 symbols long.
Is there a way I can quickly find such solution? The AI might need to evaluate this many times when analysing a move's score.
Thanks guys

In which situations should I use 'while loops' instead' for loops' in JavaScript?

I've been always confused at the time to choose between the for and while loop.
In which situations should I use 'while loops' instead' for loops' in JavaScript? Does it make a difference?
In terms of "what works", they're interchangeable.
In terms of best practices and conventions, for loops are for a known number of iterations and while loops are to be executed until their intended job is done.
There are three things you might have in a loop control structure: Something you do before the loop (like set the loop variable to zero), something you do in each iteration of the loop (like increment the loop variable), and something you do to tell if you're done looping (like compare the loop variable to something). If you have all three, and they're all simple, use for. If you only have a condition to tell if you're done looping, use while.
(This will soon get closed as too subjective, or moved to another forum, but anyway...)
Obviously any for loop can easily be rewritten using "while". But given the syntax of:
for ([initialization]; [condition]; [final-expression])
that is used by the for loop it is obviously very well suited to situations where there is some simple initialisation and a simple end-of-iteration update or counter increment. Putting all of the loop control logic right there in the loop's opening statement makes it easy to see at a glance what makes the loop tick.
With a while loop the end-of-iteration processing generally has to happen at the bottom of the loop's body, so it's harder to see at a glance how the loop works, but also that is much more suited to the situation where you have to perform a number of calculations to decide whether to keep the loop going.
Of course you can shove multiple statements in a for loop initialisation or final-expression by separating them with commas, but if that is anything more complicated than i++, j++, k-- it quickly gets too messy for my taste and a while loop would be a better choice.
For loops are great for doing the same task over and over when you know ahead of time how many times you'll have to repeat the loop.
On the other hand, while loops are ideal when you have to loop, but you don't know ahead of time how many times you'll need to loop.
Say, for example, you wanted to keep choosing playing cards from a
deck until you get a spade. You don't know how many cards you'll need
to choose, so a for loop won't work. In situations like these where
you don't know in advance when to stop looping, we can use a while
loop.
Courtesy: codecademy.com

Categories