Generating every possible position In Tick Tack Toe - javascript

I want to generate every singe way a tick tack toe board can look. The data format i would like is a simple array that looks kind of like this:
["", "X", "O",
"", "X", "X",
"", "O", "O"]
I need to know witch ones are empty too. I have no idea how to do this. Should iterate over each one and then iterate over every one behind...
Lets say I'm at the third one. Should i then go back to number two and do one for it's every possible state and inside that go to number one?
Is a recursive function what i need?
btw this is actually a screenshot of made with JavaScript. I do have some code.

Basically you could consider to use only the numbers
0 for empty places,
1 for user which goes first
2 for user which goes second
The whole space of the board is nine fields, which can have in maximum all places filled with player 2.
The numerical value of this is 2222222223 = 1968210.
From this value you have to skip the state of board like the last one, which is not possible, because it misses the player 1 and it have to much places with player 2 on it.
To check which (end) position is valid, you need a check for containing same count of pieces for player 1 and 2 +/- 1,
var value = parseInt('222222222', 3);
console.log(value);
To get all positions, you could iterate form zero to the 19682, convert the number to a string with radix = 3 and pad the string with zero to the lenght of 9.
Then check the board and eliminate impossible states.
function pad9(v) { return ('000000000' + v).slice(-9); }
var max = parseInt('222222222', 3),
i,
output = '';
for (i = 0; i <= max; i++) {
// add some checks brefore output
output += pad9(i.toString(3)) + '\n';
}
document.getElementById('out').innerHTML = output;
<pre id="out"></pre>

Related

How to determine the time and space complexity of this algorithm?

As I am preparing for an upcoming interview I worked on the string permutations problem. -
Problem statement - Write a function for generating all permutations of an input string.
Here's the solution that I feel is pretty good.
function getPermutations(string) {
// base case
if (string.length <= 1) {
return new Set(string);
}
var allCharsExceptLast = string.slice(0, -1);
var lastChar = string[string.length - 1];
// recursive call: get all possible permutations for all chars except last
var permutationsOfAllCharsExceptLast = getPermutations(allCharsExceptLast);
// put the last char in all possible positions for each of the above permutations
var permutations = new Set();
permutationsOfAllCharsExceptLast.forEach(function(permutationOfAllCharsExceptLast) {
for (var position = 0; position <= allCharsExceptLast.length; position++) {
var permutation = permutationOfAllCharsExceptLast.slice(0, position) + lastChar + permutationOfAllCharsExceptLast.slice(position);
permutations.add(permutation);
}
});
return permutations;
}
Even though I understand the solution (took me a few tries and about a million console logs), recursion confuses the crap out of me. Would someone please break down time and space complexity for me?
Let's think about the process. Say our String is n characters long. First, we must pass over each character in the string (n operations), and then for each character, recursively generate a permutation of the other n-1 characters in the string, from which we will for each 2nd character, recursively generate a permuation of n-2 chars in the string, and so on... until there is only 1 char left. To calculate the total time complexity, we multiply all these terms together (n * (n-1) * (n-2) * ... * 1 = n!), getting a time complexity in Big-O notation of O(n!).
To think about why we multiply them, we can think of the much simpler problem as follows: How many different permutations are there of clothes to wear if we have 2 pairs of pants and 3 shirts. The answer is clearly six, and we get this by noting that for each shirt, we have two choices for pants, so we take the number of shirts and multiply by the number of pants.
We can translate this example to a easy string, say the word "cat". To get every permutation, your code first chooses a character (it does not matter what order you choose the characters in, so I will first choose the 'c'), and then find the permutations in the remaining string, in this case "at". It is trivial that the only two permuations of this are "at" and "ta", so we add the strings "atc" and "tac" to overall permutations. Next, we take out 'a', and the remaining String is "ct", from which the permutations are "ct" and "tc". Thus, we add "cta" and "tca" to our overall permutations. Finally, doing the same thing when we take out 't', we end up with "ca" and "ac" as our remaining permutations, so we add "cat" and "act" to our overall permuations, and we are done. Notice that in this case they are all unique, but if a letter had been duplicated, (such as in "wow"), then your algorithm will double count, which is okay, as this not really necessary to account for.
Anyway, hope this helps, please leave a comment if you have an additional question.

list fo random numbers separated by commas

Okay so I am making a mario inspired game with randomly generating terrain, It is all working fine however the array of random numbers that randomises the terrain must be the same each time so that the user can enter a seed which is then merged with the larger list to provide a set of random numbers based off of the seed however I cannot think of any way to make this array the same each time without writing it out, and even then making an array of 1000 numbers will be timely. Can anyone suggest a fast way (number generators online dont format it in one single line of numbers separated by numbers so cannot use them)
or could someone provide me with a list that is on a single line separated by numbers that i can easily copy and paste into an array thanks! :)
The following code in Javascript will generate 1000 random numbers separated by commas.
var string = "";
var numberOfRandomNumbers = 1000;
for (var i = 0; i < numberOfRandomNumbers; i++) {
var randomNumber = Math.floor((Math.random() * 1000) + 1); //Will generate random number between 1 and 1000
string += randomNumber+",";
}
console.log(string.substring(0, string.length - 1)); //Print string to console and remove last comma

Change last names into numbers, which relate and display images

Im new to JavaScript and don't have the knowledge to write this myself yet. Any help would be great.
I'm creating pseudorandom illustration generator, comprised of 3 images. They'd be chosen by their name and displayed. Live update would be the best.
I'd like to have the user enter their last name (into a field) which will be changed into an individual set of 3 numbers. From those numbers I'd like the images to be chosen, the 1st from the first etc. then display them vertically respectively.
Any input is welcome, I'm sure there's an easier way of doing it. Thanks for your time.
Edit:
I'd like to change the last name that the user enters into a 3 digit number(000-999), then display 3 images based of the numbers given. If the number made is 015, then the first image displayed would be 000.jpg, the second 010.jpg and the third would be 005.jpg. Id like the same result each time a name is entered and I'd like to update on real time if possible. I hope this helps clear things up, I'm still trying to figure out the best way. Thanks
You can use the ASCII table to get the number matching with a letter.
Then, you can iterate on every char of the last name and sum it.
At the end, you might want to use the % (modulo) of the sum to get a value lesser than 1.000.
A tested code would be:
var lastName = "Connor";
var sum = 0;
for(var i=0; i<lastName.length;i++)
{
sum += lastName[i].charCodeAt(0);
}
sum = (sum%1000);
In your case, the result would be: 623
Then, you might want to get the files: 600.jpg, 020.jpg and 003.jpg
var firstPic = (sum + "").split('')[0] + "00.jpg";
var secondPic = "0" + (sum + "").split('')[1] + "0.jpg";
var thirdPic = "00" + (sum + "").split('')[2] + ".jpg";

Chunk a string every odd and even position

I know nothing about javascript.
Assuming the string "3005600008000", I need to find a way to multiply all the digits in the odd numbered positions by 2 and the digits in the even numbered positions by 1.
This pseudo code I wrote outputs (I think) TRUE for the odd numbers (i.e. "0"),
var camid;
var LN= camid.length;
var mychar = camid.charAt(LN%2);
var arr = new Array(camid);
for(var i=0; i<arr.length; i++) {
var value = arr[i]%2;
Alert(i =" "+value);
}
I am not sure this is right: I don't believe it's chunking/splitting the string at odd (And later even) positions.
How do I that? Can you please provide some hints?
/=================================================/
My goal is to implement in a web page a validation routine for a smartcard id number.
The logic I am trying to implement is as follows:
· 1) Starting from the left, multiply all the digits in the odd numbered positions by 2 and the digits in the even numbered positions by 1.
· 2) If the result of a multiplication of a single digit by 2 results in a two-digit number (say "7 x 2 = 14"), add the digits of the result together to produce a new single-digit result ("1+4=5").
· 3) Add all single-digit results together.
· 4) The check digit is the amount you must add to this result in order to reach the next highest multiple of ten. For instance, if the sum in step #3 is 22, to reach the next highest multiple of 10 (which is 30) you must add 8 to 22. Thus the check digit is 8.
That is the whole idea. Google searches on smartcard id validation returned nothing and I am beginning to think this is overkill to do this in Javascript...
Any input welcome.
var theArray = camid.split(''); // create an array entry for each digit in camid
var size = theArray.length, i, eachValue;
for(i = 0; i < size; i++) { // iterate over each digit
eachValue = parseInt(theArray[i], 10); // test each string digit for an integer
if(!isNaN(eachValue)) {
alert((eachValue % 2) ? eachValue * 2 : eachValue); // if mod outputs 1 / true (due to odd number) multiply the value by 2. If mod outputs 0 / false output value
}
}
I discovered that what I am trying to do is called a Luhn validation.
I found an algorithm right here.
http://sites.google.com/site/abapexamples/javascript/luhn-validation
Thanks for taking the time to help me out. Much appreciated.
It looks like you might be building to a Luhn validation. If so, notice that you need to count odd/even from the RIGHT not the left of the string.

Counting rounds in a tournament

I've written a huge page in JavaScript for a tournament I'm hosting on a game. I've gotten everything I really need worked out into arrays, but I want to add rounds. The whole script adjusts to tournament settings (for more in the future) and I'd like this to adjust itself as well. So, let's say the tournament settings are [game,teamsize,entrylimit]. The entrylimit will be the key to finding the solution, because that decides the rounds. It works in a tree system (or however it's called). Let's say the entrylimit is 8. That means the first round will consist of 4 matches, and the second will consist of 2. If the entrylimit were 16, then the first round would consist of 8 matches, the second would consist of 4, and the third would consist of 2. I want to find a way to stick this into my loop where matches are written, and use the entrylimit and match number to generate the round number. All I need is a formula that can use those two variables to get my desired result. Also I apologize for the excessive amount of detail.
If I understand the problem, here's an example of how the entrylimit can get the number of rounds and the number of matches in each round.
Calculations:
var entrylimit=16;
var amount_of_rounds = Math.log(entrylimit) / Math.log(2);
for(i=amount_of_rounds; i>0; i--)
{
s = 'Round '+(amount_of_rounds-i+1)+' of '+amount_of_rounds+' consist of '+Math.pow(2, i-1)+' matches';
alert(s);
}
​
Try this:
var entryInfo = [];
function populateEntryInfo(entryLimit)
{
entryInfo = [];
var i = entryLimit;
while(i>1)
{
i = i/2;
entryInfo.push(i);
}
entryInfo.push(i);
}

Categories

Resources