Timing recursive functions and general being stuck-ness - javascript

I am working on a project to create an energy cost/savings calculator for a client. I have been writing it in pure JavaScript so far, but am more than happy to use jQuery where necessary. I'm still starting out learning the language, so I apologize in advance for any bad practices, egregious errors, or simple mistakes.
There are two requirements:
The user can input their energy use information, and see how much they will save by using the client's product (I just have the input so far, am planning to use those returned values to output the savings later)
The numbers animate in some way when they are presented.
For the animation, I'm just going with the number counting up or down from its current position. My problem is I'm absolutely stuck with how to achieve this. I'm told that I want to use a timer on a recursive function that either increments or decrements the displayed number based upon the old value versus the newly input value.
So when the user selects a number, the display will count up to that number from zero with a space of, say, ~300ms between each change. And if they select a different number, it will count up or down.
Here is a link to the live page. For some reason the selected number doesn't show up in the DOM in the jsfiddle version. Here is the .js file.
I would very much appreciate any help to nudge me out of my little rut. As I said, I'm still in the baby stages of learning JavaScript, so I can't quite think fluidly in the language yet. Thank you in advance.

this may be enough to get you started:
http://jsfiddle.net/pLJU6/
var number = 0;
var div = $('#numberDiv');
var incrementNumber = function () {
div.text(number);
number++;
setTimeout(incrementNumber, 300);
};
incrementNumber();

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.

Slot machine Random generator

so i saw this: https://www.quora.com/What-algorithm-do-slot-machines-use
How is acually these random numbers generated, and how are the acually translated further on?
i was planning to make a basic slot machine, but no idea where to start.
Well, i had an idea to use something like:
$randomNumber1 = rand(1,X);
for each slot, but that dont seem very effective,
How would i solve this?
By the way, here is one image from the link above, that conserns my issue.
edit: Would it be the same style functionality with a slot machine with 3x3 instead of 1x3 lines?
It depends on how realistic you want the slot machine to be. If you just want it to randomly pay out, then a simple r = rand(1,X) is fine. That's a good way to start because you can then prove that the mechanics of your game work: all the graphics and animations display correctly, the user interface controls work as expected, etc.
But a real slot machine doesn't just randomly display every possible combination. For example, if three sevens pays out more often than three cherries, then the slot machine is designed to show the three sevens much less frequently. After all, the goal of the slot machine is for the house to make money.
The math behind slot machines is quite involved: much too involved for a Stack Overflow answer. How you generate the random numbers, assuming you get a uniform distribution, is not a major concern compared to setting up your wheels to give a consistent payout.
My suggestion is that you use your built-in random number generator until you get your game working. Then, if you want it to work more like a real slot machine, type "slot machine math" into your favorite search engine, and start studying.
I would use the old tried-and-true Fisher-Yates shuffle algorithm for this. This question has a JavaScript implementation, and it can be used for slots like so:
let slotOptions = ["cherry", "seven", "bell", "bar"];
function play() {
return [shuffle(slotOptions), shuffle(slotOptions), shuffle(slotOptions)];
}
let [slot1, slot2, slot3] = play();
// do something with those slots here

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...

Is it possible to use Javascript to randomly generate a pre-determined link color and hover color on page refresh?

I've never tried my hand at javascript but I'm just wanting to know if it is actually possible to do this before I spend time learning the code.
I've spent a couple of days looking around the forums and trying to use code already generated on a demo site to see how changing certain properties affects a section as a whole.
My CSS specifies the 'a:link', 'a:active' and 'a:visited' as a set colour and the a:hover as its complementary color (#128EED = color, #ED7112 = complementary).
I want one of 8 pre-determined colors to be randomly selected when any of the pages are loaded, and the complementary color of the pre-determined, random color to be the a:hover color.
Any information would be greatly appreciated before I start to attempt to do this.
Thank you and kind regards.
Yes, you can do that. You can set the style on an element through javascript, you could create several classes to color what you need and apply those classes randomly, etc. There are multiple solutions to your problems, but it's very doable.
Also, it's never a waste of time to learn javascript if you are web programming. It can take a lot of stress off of a page needing to go back and forth to the server as well as add functionality that HTML can't provide or can't easily provide.
EDIT: it is not possible to set certain style attributes, including hover, etc. But there are workarounds to this, one being linked in a comment to this answer. Apologies if I misled you.
Yup it is possible! Just use something like this; assuming you have an array called ColorArray which is an array of arrays (each sub array is the pair of complementary colors):
I'm not sure if the words after .style are accurate, but they should be easy enough to look up. I separated it into 5 lines so its easy to see what's going on, but im sure there is a better or more compressed way to express this.
// choose a random complementary pair
var pair = ColorArray[Math.floor(Math.random() * CollorArray.length)];
// grab elements and assign them style attributes
document.getElementsByTagName("tag").style.link = pair[0]
document.getElementsByTagName("tag").style.active = pair[0]
document.getElementsByTagName("tag").style.visited = pair[0]
// Your complementary color assignment now:
document.getElementsByTagName("tag").style.hover = pair[1]

Grade Sudoku difficulty level

I am building a Sudoku game for fun, written in Javascript.
Everything works fine, board is generated completely with a single solution each time.
My only problem is, and this is what's keeping me from having my project released to public
is that I don't know how to grade my boards for difficulty levels. I've looked EVERYWHERE,
posted on forums, etc. I don't want to write the algorithms myself, thats not the point of this
project,and beside, they are too complex for me, as i am no mathematician.
The only thing i came close to was is this website that does grading via JSbut the problem is, the code is written in such a lousy undocumented, very ad-hoc manner,therefor cannot be borrowed...
I'll come to the point -Can anyone please point me to a place which offers a source code for Sudoku grading/rating?
Thanks
Update 22.6.11:
This is my Sudoku game, and I've implemented my own grading system which relies
on basic human logic solving techniques, so check it out.
I have considered this problem myself and the best I can do is to decide how difficult the puzzle is to solve by actually solving it and analyzing the game tree.
Initially:
Implement your solver using "human rules", not with algorithms unlikely to be used by human players. (An interesting problem in its own right.) Score each logical rule in your solver according to its difficulty for humans to use. Use values in the hundreds or larger so you have freedom to adjust the scores relative to each other.
Solve the puzzle. At each position:
Enumerate all new cells which can be logically deduced at the current game position.
The score of each deduction (completely solving one cell) is the score of the easiest rule that suffices to make that deduction.
EDIT: If more than one rule must be applied together, or one rule multiple times, to make a single deduction, track it as a single "compound" rule application. To score a compound, maybe use the minimum number of individual rule applications to solve a cell times the sum of the scores of each. (Considerably more mental effort is required for such deductions.) Calculating that minimum number of applications could be a CPU-intensive effort depending on your rules set. Any rule application that completely solves one or more cells should be rolled back before continuing to explore the position.
Exclude all deductions with a score higher than the minimum among all deductions. (The logic here is that the player will not perceive the harder ones, having perceived an easier one and taken it; and also, this promises to prune a lot of computation out of the decision process.)
The minimum score at the current position, divided by the number of "easiest" deductions (if many exist, finding one is easier) is the difficulty of that position. So if rule A is the easiest applicable rule with score 20 and can be applied in 4 cells, the position has score 5.
Choose one of the "easiest" deductions at random as your play and advance to the next game position. I suggest retaining only completely solved cells for the next position, passing no other state. This is wasteful of CPU of course, repeating computations already done, but the goal is to simulate human play.
The puzzle's overall difficulty is the sum of the scores of the positions in your path through the game tree.
EDIT: Alternative position score: Instead of completely excluding deductions using harder rules, calculate overall difficulty of each rule (or compound application) and choose the minimum. (The logic here is that if rule A has score 50 and rule B has score 400, and rule A can be applied in one cell but rule B can be applied in ten, then the position score is 40 because the player is more likely to spot one of the ten harder plays than the single easier one. But this would require you to compute all possibilities.)
EDIT: Alternative suggested by Briguy37: Include all deductions in the position score. Score each position as 1 / (1/d1 + 1/d2 + ...) where d1, d2, etc. are the individual deductions. (This basically computes "resistance to making any deduction" at a position given individual "deduction resistances" d1, d2, etc. But this would require you to compute all possibilities.)
Hopefully this scoring strategy will produce a metric for puzzles that increases as your subjective appraisal of difficulty increases. If it does not, then adjusting the scores of your rules (or your choice of heuristic from the above options) may achieve the desired correlation. Once you have achieved a consistent correlation between score and subjective experience, you should be able to judge what the numeric thresholds of "easy", "hard", etc. should be. And then you're done!
Donald Knuth studied the problem and came up with the Dancing Links algorithm for solving sudoku, and then rating the difficulty of them.
Google around, there are several implementations of the Dancing Links engine.
Perhaps you could grade the general "constrainedness" of a puzzle? Consider that a new puzzle (with only hints) might have a certain number of cells which can be determined simply by eliminating the values which it cannot contain. We could say these cells are "constrained" to a smaller number of possible values than the typical cell and the more highly constrained cells that exist the more progress one can make on the puzzle without guessing. (Here we consider the requirement for "guessing" to be what makes a puzzle hard.)
At some point, however, the player must start guessing and, again, the constrainedness of a cell is important because with fewer values to choose between for a given cell the easier it is to find the correct value (and increase the constrainedness of other cells).
Of course, I don't actually play Sudoku (I just enjoy writing games and solvers for it), so I have no idea if this is a valid metric, just thinking out loud =)
I have a simple solver that looks for only unique possibilities in rows, columns and squares. When it has solved the few cells solvable by this method, it then picks a remaining candidate tries it and sees if the simple solver then leads to either a solution or a cell empty of possibilities. In the first case the puzzle is solved, in the second, one possibility has shown to be infeasible and thus eliminated. In the third case, which leads to neither a final solution nor an infeasibility, no
deduction can be reached.
The primary result of cycling through this procedure is to eliminate possiblities until picking
a correct cell entry leads to a solution. So far this procedure has solved even the hardest
puzzles without fail. It solves without difficulty puzzles with multiple solutions. If the
trial candidates are picked a random, it will generate all possilbe solutions.
I then generate a difficulty for the puzzle based on the number of illegal candidates that must
be eliminated before the simple solver can find a solution.
I know that this is like guessing, but if simple logic can eliminated a possible candidate, then one
is closer to the final solution.
Mike
I've done this in the past.
The key is that you have to figure out which rules to use from a human logic perspective. The example you provide details a number of different human logic patterns as a list on the right-risde.
You actually need to solve the puzzle using these rules instead of computer rules (which can solve it in milliseconds using simple pattern replacement). Every time you change the board, you can start over from the 'easiest' pattern (say, single open boxes in a cell or row), and move down the chain until you find one the next logical 'rule' to use.
When scoring the sodoku, each methodology is assigned some point value, which you would add up for every field you needed to fill out. While 'single empty cell' might get a 0, 'XY Chain' might get 100. You tabulate all of the methods needed (and frequency) and you wind up with a final weighting. There are plenty of places that list expected values for those weightings, but they are all fairly empirical. You're trying to model human logic, so feel free to come up with your own weightings or enhance the system (if you really only use XY chains, the puzzle is probably easier than if it requires more advanced mechanisms).
You may also find that even though you have a unique sodoku, that it is unsolvable through human logic.
And also note that this is all far more CPU intensive than solving it in a standard, patterned way. Some years ago when I wrote my code, it was taking multiple (I forget exactly, but maybe even up to 15) seconds to solve some of the generated puzzles I'd created.
Assuming difficulty is directly proportional to the time it takes a user to solve the puzzle, here is an Artificially Intelligent solution that approaches the results of the ideal algorithm over time.
Randomly generate a fixed number of starting puzzle layouts, say 100.
Initially, offer a random difficulty section that let's a user play random puzzles from the available layouts.
Keep an average random solution time for each user. I would probably make a top 10/top X leaderboard for this to generate interest in playing random puzzles.
Keep an average solution time multiplier for each puzzle solution (if the user normally solves the puzzle in 5 minutes and solves it in 20 minutes, 4 should be figured in to the puzzles average solution time multiplier)
Once a puzzle has been played enough times to get a base difficulty for the puzzle, say 5 times, add that puzzle to your list of rated puzzles and add another randomly generated puzzle to your available puzzle layouts.
Note: You should keep the first puzzle in your random puzzles list so that you can get better and better statistics on it.
Once you have enough base-rated puzzles, say 50, allow users to access the "Rated Difficulty" portion of your application. The difficulty for each puzzle will be the average time multiplier for that puzzle.
Note: When users choose to play puzzles with rated difficulty, this should NOT affect the average random solution time or average solution time multiplier, unless you want to get into calculating weighted averages (otherwise if a user plays a lot of harder puzzles, their average time and time multipliers will be skewed).
Using the method above, a solution would be rated from 0 (already solved/no time to solve) to 1 (users will probably solve this puzzle in their average time) to 2 (users will probably take twice as long to solve this puzzle than their average time) to infinity (users will take forever to find a solution to this puzzle).

Categories