Check taken location on Tic Tac Toe board Matlab - arrays

I'm trying to make a small function that checks whether a spot is taken on a Tic Tac Toe board or not. I have created an array of zeroes called tttArray where when each spot is filled, its location is changed to 1. So I first take the input from the player from the below function.
function [pXInputRow, pXInputCol] = pickXspot(playerInput)
%This function is to take inputs from Player X
pXInputRow = 0;
pXInputCol = 0;
%Set text for Row/Col Prompt
prompt = {'Row (1,2, or 3)', '(Col (1, 2, or 3)'};
name = 'Player X Turn';
%Show prompt to input values
playerInput = inputdlg(prompt, name);
pXInputRow = str2num(playerInput{2});
pXInputCol = str2num(playerInput{1});
tttArray(pXInputRow, pXInputCol) = 1;
end
And then use the below function to see if the spot is taken.
function [spotTaken] = checktaken(tttArray)
%Function used to check if spot is taken
%Setup Error Messages
errorMessage = 'This spot is taken, please choose another spot';
errorMessageTitle = 'Spot Taken';
if tttArray(pXInputRow, pXInputCol) || tttArray(pOInputRow, pOInputCol) == 1
msgbox(errorMessage, errorMessageTitle)
spotTaken = 1;
end
end
However, I keep getting the following error after I run and put a row/col in the prompt dialog box. Any Suggestions?
Not enough input arguments.
Error in checktaken (line 8)
if tttArray(pXInputRow, pXInputCol) || tttArray(pOInputRow, pOInputCol) == 1

Couple of problems.
You supplied the tttArray as an input parameter to your checkTaken function as a call argument:
function [spotTaken] = checktaken(tttArray)
but you do not appear to have supplied the row and column parameters pXInputRow, pXInputCol or pOInputRow, pOInputCol as arguments.
So those parameters are undefined when you call
if tttArray(pXInputRow, pXInputCol) || tttArray(pOInputRow, pOInputCol) == 1
You need to supply those coordinates as arguments to your checkTaken function.
You could do the brute force method
function [spotTaken] = checktaken(tttArray, pXInputRow, pXInputCol, pOInputRow, pOInputCol)
or you could do something more elegant like put the coordinates in an array.
Another problem is if you want to check if either of the array elements is equal to 1, your if statement syntax is not correct.
in effect you have
if a || b == 1
but that is probably not what you want. Se the Matlab documentation on operator precedence
Instead you probably want
if (a == 1) || (b == 1)
so you if statement should be
if (tttArray(pXInputRow, pXInputCol) ==1) || (tttArray(pOInputRow, pOInputCol) == 1)

Related

Dice game simulator kotlin

I'm writing a code where I am versing the computer. A player throws a six-sided die and scores as many points as the total shown on the die providing the die doesn’t roll a 1.
The player may continue rolling and accumulating points (but risk rolling a 1) or end his turn.
If the player rolls a 1 his turn is over, he loses all points he accumulated that turn, and he passes the die
to the next player.
If the player ends without throwing a 1, the turn total is then added to the player's grand total.
Play passes from player to player until a winner is determined.
We are playing against the computer. The computer will roll the die using this rule:
A random number between 1 and 2 is CALCULATED. IF the number is a 1, the computer will roll. IF the number is a 2 it will stop rolling and give the dice back to the player. This loops until the calculated random number is a 2.
If a 1 is rolled, the turn is over and the computer loses all points from that turn.
The sum of all the rolls of the dice during this turn are added to computer's grand total
The human player can choose from a menu whether to roll again or "hold" and allow the computer to have a turn.
The issue is when I press hold (2) to pass it to the computer (ai) or when I roll a 1 it does nothing. the program stops. I am trying to git the program to only stop if all conditions are met can someone please help this is what I have so far.
var player = 0
var turntotal = 0
var computerpoints = 0
var grandtotal = 0
var roll = (1..6).random()
var ai = (1..2).random()
println("1. Roll Dice")
println("2. Hold and pass to computer")
println("3. Quit")
println()
println("Please select a menu Item")
player = readLine()!!.toInt()
while (turntotal < 50 && computerpoints < 50 && player != 3)
if (player == 1) {
roll = (1..6).random()
println("You rolled a $roll")
turntotal += roll
println("Turn total: $turntotal")
println("***********************************")
println("* Grand Total - You: $turntotal Computer:$computerpoints *")
println("***********************************")
while (roll != 1) {
println("1. Roll Again")
println("2. Hold")
player = readLine()!!.toInt()
if (player == 2) break
roll = (1..6).random()
println("You rolled a $roll")
turntotal += roll
println("Turn total: $turntotal")
println("***********************************")
println("* Grand Total - You: $turntotal Computer:$computerpoints *")
println("***********************************")
}
if (roll == 1) {
turntotal = 0
println("You rolled a $roll")
println("You lose all your turn points and turn ")
println("***********************************")
println("* Grand Total - You: $turntotal Computer:$computerpoints *")
println("***********************************")
println()
println("Computer's turn to roll")
while ( ai != 1)
roll = (1..2).random()
if (roll == 1)
roll =(1..6).random()
println("Computer decides to roll: $roll")
computerpoints += roll
println("Computer's points: $computerpoints")
println("***********************************")
println("* Grand Total - You: $turntotal Computer:$computerpoints *")
println("***********************************")
if (roll== 1)
computerpoints = 0
println("Computer rolled a $roll")
println("Computer's points is $computerpoints")
println("***********************************")
println("* Grand Total - You: $turntotal Computer:$computerpoints *")
println("***********************************")
if (roll == 2 )
println("1. Roll Dice")
println("2. Hold and pass to computer")
println("3. Quit")
println()
println("Please select a menu Item")
player = readLine()!!.toInt()
}
}
}
That formatting's hard to read (it's hard to see how the ifs and whiles are nested without the indentation and the missing braces) but you're not actually handling the user pressing 2 anywhere, except breaking out of one of the while loops.
Since your whole game loop is in this outer while:
player = readLine()!!.toInt()
...
while (turntotal < 50 && computerpoints < 50 && player != 3) {
// stuff for this turn
}
you need to read the player's choice inside that loop, right? Right now it looks like your loop only does something if player == 1 (everything looks like it's supposed to be inside that if block) but if they entered 2 last turn, then player is still 2, so the while runs forever.
You could do something like this:
// inside your main turn loop
// player turn
val playerBust = false
do {
val playerChoice = showMenu()
// handle the user choosing to roll
if (playerChoice == 1) {
val result = roll()
if (result == 1) playerBust = true
}
} while (!playerBust && playerChoice != 2) // keep going until they bust or hold
By using do/while the loop always runs at least once, so you can show your menu in there, and then check if they get another go in the while check at the end. By not relying on any old player state, each turn starts "fresh" and you can set playerBust to false, read in their first choice and go from there. And you can do the same for the computer turn!
Also I simplified it by using functions like showMenu() (returns the option the player chose) and roll() (rolls the die and returns the result). It's up to you if you want to implement functions like that, but it can really clean up the repeated code and make it simpler to reason about. The computer can call roll() too, right? Same for printing out the results - you can put all that formatting in a separate function, so your game loop is shorter and just contains the core logic. Smaller blocks of code are easier to work with!

Javascript - Giving alert for string input but number

Hi recently I was writing a code which basically askes users to input a cost for any item.
The item name or price are not important so far.
How the system works is that a prompt pops up and asks what is the cost of the item, and when you enter a cost, it asks you again (while loop). When total cost reaches $36, while loop ends and an alert screen pops up saying your shipping is free since it is over $35.
My problem is when I enter string value as a user input it takes the value into cost array and since it goes as Nan value, my cost calculation never end even though it passes $36.
How can I eliminate any string input and do not push it into the array?
Here is my code:
while (complete === false) {
var costValue = prompt('Enter the cost of the item?');
//If user click cancel
if (costValue === null) {
alert('Process canceled');
complete = true;}
//AT THIS LINE HOW CAN I ELIMINATE STRING VALUES
//convert input to a number
userInput = parseInt(costValue);
/push the value into the array
myCost.push(userInput);
Leading special character will give you NAN and if you use a special character after the Int value then the parseInt will give you the correct result. You can also use regex to remove all the special characters.
userInput.replace(/[^\w\s]/gi, '')
You can read about parseInt from here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
After you parse your user input into an integer (i.e. using parseInt method), then have an if statement that checks whether the parsed values is not NaN. If so, then only push the parsed value into your array.
// TRY parse user input into an integer
userInput = parseInt(costValue);
// only push into your array when it is not `NaN`
if (userInput !== 'NaN') {
// push the value into the array
myCost.push(userInput);
}
Try this code, it should work
var userInput;
var totalInput=0;
var complete = false;
var costValue;
var numPattern = /^\d+$/;
while (!complete) {
costValue = prompt('Enter the cost of the item?');
//If user click cancel
if (costValue === null)
{
alert('Process canceled');
complete = true;
}
//convert input to a number if it matches regular expression
if (costValue.match(numPattern)){
userInput = parseInt(costValue);
totalInput+=userInput;
if (totalInput>35) {
complete=true;
alert("Cost is $" + totalInput + ". Shipping is free over $35");
}
}
}
On the other hand, if you want to go another route, you can check for NaN using this function isNaN(userInput) and exclude it from your calculations

How to use a While Loop to repeat the code based on the input variable

i'm having a rough time trying to do a loop with the while function.
Basicly i want the code to show me all prime numbers from 0 to the number i wrote in input.
Then, to ask a question if i want to do it one more time (if yes to repeat the code from the start) or if not to exit.
How i got it now is just to repeat the last results infinitely.
All results i found online with the while loop don't really explain how to repeat a certain part of the code.
I'm by no means even a little bit educated when it comes to this stuff so if its a stupid question, please forgive me.
# Python program to print all primes smaller than or equal to
# n using Sieve of Eratosthenes
def start(welcome):
print ("welcome to my calculation.")
value = input("number?:\n")
print(f'you have chosen: {value}')
value = int(value)
def SieveOfEratosthenes(n):
prime = [True for i in range(n + 1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p ** 2, n + 1, p):
prime[i] = False
p += 1
prime[0] = False
prime[1] = False
print("Primary numbers are:")
for p in range(n + 1):
if prime[p]: print(p)
# driver program
if __name__ == '__main__':
n = value
SieveOfEratosthenes(n)
pitanje = input("do you want to continue(yes/no)?")
while pitanje == ("yes"):
start: SieveOfEratosthenes(n)
print("continuing")
if pitanje == ("no"):
print("goodbye")
strong text
Firstly you should remove
value = input("number?:\n")
print(f'you have chosen: {value}')
value = int(value)
from the top of your code, everything must be inside your __main__ program.
Basically what you need to do is create a main While loop where your program is gonna run, it will keeps looping until the response is not "yes".
For each iteration, you ask a new number at the beggining and if it has to keep looping at the end.
Something like this:
# driver program
if __name__ == '__main__':
# starts as "yes" for first iteration
pitanje = "yes"
while pitanje == "yes":
# asks number
value = input("number?:\n")
print(f'you have chosen: {value}')
value = int(value)
# show results
start: SieveOfEratosthenes(value)
# asks for restart
pitanje = input("do you want to continue(yes/no)?")
#if it's in here the response wasn't "yes"
print("goodbye")

Multiple logical operator || (OR) conditions in for loop in C

I started studying C a week ago and decided to write my own tic-tac-toe game for practise.
I have a game loop in main:
for(int i = 1; player1.isWinner!=1 || player2.isWinner!=1 || noWinner!=1; i++){...}
Where i - counts turns and condition of end of the game is one of players has won, or no one has won (draw).
For now, it quits executing only if all conditions are 1.
How can I make it work right?
Is a value of 1 where someone won?
If so, then you would need check any of those conditions is true and loop if they are not:
!(player1.isWinner==1 || player2.isWinner==1 || noWinner==1)
Or using AND, check and loop when none are set:
(player1.isWinner!=1 && player2.isWinner!=1 && noWinner!=1)
Consider extracting the condition to a well-named function in order to aid readability and maintanability:
int hasWinner(/*...*/)
{
return player1.isWinner == 1 || player2.isWinner == 1 || noWinner == 1;
}
It then becomes obvious what the condition should be:
for(int i = 1; !hasWinner(/*...*/); i++){ /*...*/ }
You seem to be using some sort of backwards boolean logic. If 1 represents the boolean value true, then the condition should be
!(player1.isWinner || player2.isWinner || noWinner)
This assumes that you set player1.isWinner to 1 when player1 has won.
It would probably be easier to use bool with values true or false from stdbool.h.

Lua determining when out of range

I have a function called preprocess. It looks like this
function image_utils.preprocess(meanfile, oneD_image_table)
local img_mean = torch.load(meanfile).img_mean:transpose(3,1)
return function()
for t_class, img_path in pairs(oneD_image_table) do
local im3 = image.load(img_path)
local im4 = image.scale(im3,227,227,'bilinear')*25
return im4 - image.scale(img_mean, 227, 227, 'bilinear')
end
end
Here's how I call it:
im_f = image_util.preprocess(meanfile, path_list)
repeat
im=im_f()
batch[count]:copy(im)
count = count + 1
until count == batchSize
This works. However, I would like to be detect when im_f doesn't have any more iterations left and use that to determine when I should stop looping.In other words, something like this:
repeat
im = im_f()
count = count+1
batch[count] = im
until im == nil (or im is some sentinel value that tells me to stop)
However, I have not been able to make this work due to out of range error.
In short, I want to loop until im_f tells me to stop; rather than using a predetermined number to tell me when to stop.

Resources