Rock, Paper, Scissors. Determine win/loss/tie using math? - math

So I was writing a rock paper scissors game when I came to writing this function:
a is player one's move, b is player two's move. All I need to figure out is if player one won, lost, or tied.
//rock=0, paper=1, scissors=2
processMove(a, b) {
if(a == b) ties++;
else {
if(a==0 && b==2) wins++;
else if(a==0 && b==1) losses++;
else if(a==1 && b==2) losses++;
else if(a==1 && b==0) wins++;
else if(a==2 && b==1) wins++;
else if(a==2 && b==0) losses++;
}
}
My question is: What's the most elegant way this function can be written?
Edit: I'm looking for a one-liner.

if (a == b) ties++;
else if ((a - b) % 3 == 1) wins++;
else losses++;
I need to know exactly which language you are using to turn it into a strictly one-liner...
For JavaScript (or other languages with strange Modulus) use:
if (a == b) ties++;
else if ((a - b + 3) % 3 == 1) wins++;
else losses++;

A 3x3 matrix would be "more elegant", I suppose.
char result = "TWLLTWWLT".charAt(a * 3 + b);
(Edited: Forgot that a and b were already zero-origin.)

I suppose you could use the terniary operator like this -
if (b==0) a==1? wins++ : loss++;
if (b==1) a==1? loss++ : wins++;
if (b==2) a==1? loss++ : wins++;

You can do it with a simple mathematical formula to get the result and then compare with if like this:
var moves = {
'rock': 0,
'paper': 1,
'scissors': 2
};
var result = {
'wins': 0,
'losses': 0,
'ties': 0
};
var processMove = function (a, b) {
var processResult = (3 + b - a) % 3;
if (!processResult) {
++result['ties'];
} else if(1 == processResult) {
++result['losses'];
} else {
++result['wins'];
}
return result;
};
jsFiddle Demo
One line processMove function without return:
var processMove = function (a, b) {
((3 + b - a) % 3) ? 1 == ((3 + b - a) % 3) ? ++result.losses : ++result.wins : ++result.ties;
};

how do you do it in java?
result = (comp - x ) % 3 ;
System.out.println (result);
if (result == 0 )// if the game is tie
{
System.out.println ("A Tie!") ;
}
else if (result == 1 || result == 2 )
{
//System.out.println (user + " " + "beats" + " " + computer_choice + " you win" );
System.out.println ("comp win");
}
else
{
System.out.println ("you win");
//System.out.println (computer_choice + " " + "beats" + " " + user + "you lose");
}

Related

Recursion func w/o recursion

function findNum(a, b) {
if (!b) {
b = 0;
}
if (a < 2) {
throw new Error('wrong');
}
if (a === 2) {
return 1 / a + b;
}
return findNum(a - 1, b + 1 / (a * (a -1)));
}
Is there any way to write this func w/o recursion and without using while in it?

Why am i getting different output if I use "return"?

Why do I need to use return statement before recursively calling BubbleSort function?
without return statement : no output
void BubbleSort(int arr[], int n, int j)
{
if(n == 1)
return;
if(j == n - 1)
{
BubbleSort(arr, n - 1, 0);
}
if(arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
}
BubbleSort(arr, n, j + 1);
return;
}
with return statement : gives the correct output
void BubbleSort(int arr[], int n, int j)
{
if(n == 1)
return;
if(j == n - 1)
{
return BubbleSort(arr, n - 1, 0);
}
if(arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
}
BubbleSort(arr, n, j + 1);
return;
}
By specifying return keyword we are assure that the control of program will move to its caller.
BubbleSort(arr, n - 1, 0);
when you're executing this, without return keyword, it's calling self and the control is not returning to it's caller therefore rest of the code also executing and it does change the business which was not intended and you might getting some messy things to your result.
the following snippet might help you to understand it better:
if(j == n - 1)
{
BubbleSort(arr, n - 1, 0);
return; // returns to it caller.
}

using else if in a function in R

I 'm trying to use else if within a function in R
new<-function(a,b,c,d){
if (a==1){
var1<-100+100+100
var2<-500+500+500
var3<-500-100
}else if (a==2){
var1<-100+100
var2<-500+500
var3<-500-10
} else if (a==3){
var1<-100
var2<-500
var3<-500
}
b<-var1-var2
c<- var2+var3
d<-var3-var1
if (b<100)
{print ("the value is good")
}else if (b>100)
{ print("check teh value")
}else
{print ("repeat")
}
}
output<-new(3,b,c,d)
I feel something fundamental is wrong with this which I m missing. I 'm trying to use else if to populate the values to be used as an input to call the same fucntion.
Help is greatly appreciated
You can simplify to:
new <- function(a) {
if (a == 1) {
b <- -1200
} else if (a == 2) {
b <- -800
} else if (a == 3) {
b <- -400
}
if (b < 100)
{
print ("the value is good")
} else if (b > 100)
{
print("check the value")
} else
{
print ("repeat")
}
return(b) # for fun return the value of b
}
output <- new(2)
But this function will always have the side effect of printing "the value is good" because b always evaluates to a negative number. What's the purpose?
If you would want to return values a to d, you could do the intermediate calculations as per your example and do: return(list(a = a, b = b, c = c, d = d)) instead of return(b).

Division with numerator 2^64

How to to divide the constant 2^64 (i.e. ULLONG_MAX + 1) by uint64 larger than 2, without using unit128?
In other words, given x such as 2 <= x <= 2^64-1, how to obtain the quotient 2^64 / x, using just uint64?
The problem is that I cannot represent 2^64, let alone to divide it so I was hoping there is a trick which would simulate the result.
How to to divide the constant 2^64 (i.e. ULLONG_MAX + 1) by uint64 larger than 2
a/b --> (a-b)/b + 1
First subtract x from (max _value + 1), then divide by x, add 1.
// C solution:
uint64_t foo(uint64_t x) {
return (0u - x)/x + 1; // max_value + 1 is 0 and unsigned subtraction wraps around.
}
Of course division by 0 is a no-no. Code works for x >= 2, but not x == 1 as the quotient is also not representable.
Take ULLONG_MAX / denom, and add 1 if denom is a power of 2. In pseudocode:
if (denom == 0) {
throw ZeroDivisionException;
} else if (denom == 1) {
throw OverflowException;
} else {
return ULLONG_MAX / denom + (denom & (denom-1) == 0);
}
Alternatively, take ULLONG_MAX / denom for odd denom, and take 2^63 / (denom / 2) for even denom:
if (denom == 0) {
throw ZeroDivisionException;
} else if (denom == 1) {
throw OverflowException;
} else if (denom & 1) {
return ULLONG_MAX / denom;
} else {
return (1ULL << 63) / (denom >> 1);
}

Strtol implementation different behaviour on 32 and 64 bit machine

#include <ctype.h>
#include <string.h>
#include <stdio.h>
#include <tgmath.h>
#include <limits.h>
#include <stdbool.h>
#include <errno.h>
#define NEGATIVE -1
#define POSITIVE 1
#define OCTAL 8
#define DECIMAL 10
#define HEXADECIMAL 16
#define BASE_MIN 2
#define BASE_MAX 36
long int strtol (const char * str, char ** endPtr, int base)
{
if(base < 0 || base == 1 || base > BASE_MAX)
{
errno = EINVAL;
return 0L;
}
else
{
bool conversion = true;
int i = 0, sign = POSITIVE, save;
while(isspace(*(str + i)))
i++;
if(*(str + i) == '\0')
{
conversion = false;
save = i;
}
if(*(str + i) == '-')
{
sign = NEGATIVE;
i++;
}
else if(*(str + i) == '+')
i++;
if(base == 0) // find out base
{
if(*(str + i) == '0')
{
if(toupper(*(str + i + 1)) == 'X')
{
base = HEXADECIMAL;
i++;
}
else
base = OCTAL;
i++;
}
else
base = DECIMAL;
}
else if(base == OCTAL)
{
if(*(str + i) == '0')
i++;
}
else if(base == HEXADECIMAL)
{
if(*(str + i) == '0')
if(*(str + i + 1) == 'x' || *(str + i + 1) == 'X')
i += 2;
}
int start = i, end, exp, check = i;
long int long_int, sum, multiplier;
if(conversion) // find out the correct part of the string corresponding to the number
{
if(base < DECIMAL)
{
while(*(str + i) >= '0' && *(str + i) < base + '0') // numbers from 0 to base - 1
i++;
}
else if(base == DECIMAL)
{
while(*(str + i) >= '0' && *(str + i) <= '9') // numbers from 0 to 9
i++;
}
else
{
while((*(str + i) >= '0' && *(str + i) <= '9') || (toupper(*(str + i)) >= 'A' && toupper(*(str + i)) < 'A' + base - 10))
i++;// numbers from 0 to 9 and uper and lowercase letters from a to a + base - 11
}
}
if(i == check && conversion) //no digits at all
{
conversion = false;
save = i;
}
else if(endPtr != NULL && conversion) // assign pointer
*endPtr = (char *) (str + i);
if(conversion)
{
for(end = i - 1, exp = 0, long_int = 0L; end >= start; end--, exp++)
{
multiplier = pow(base, exp);
sum = 0L;
if(*(str + end) >= '0' && *(str + end) <= '9')
sum = (*(str + end) - '0') * multiplier;
else if(*(str + end) >= 'A' && *(str + i) <= (base == BASE_MAX ? 'Z' : 'F'))
sum = (*(str + end) - 'A' + 10) * multiplier;
else if(*(str + end) >= 'a' && *(str + i) <= (base == BASE_MAX ? 'z' : 'f'))
sum = (*(str + end) - 'a' + 10) * multiplier;
if(long_int <= LONG_MIN + sum)
{
errno = ERANGE;
return LONG_MIN;
}
if(long_int >= LONG_MAX - sum)
{
errno = ERANGE;
return LONG_MAX;
}
else
long_int += sum;
}
return sign * long_int;
}
else
{
if(endPtr != NULL)
{// if base is 16 we check if the string given is not in the form 0xIncorrect string in that way we need to return xIncorrect part of the string
if(base == HEXADECIMAL && save >= 2 && toupper(*(str + save - 1)) == 'X' && *(str + save - 2) == '0')
*endPtr = (char *) str + save - 1;
else if(base == OCTAL && save >= 1 && *(str + save - 1) == '0')
*endPtr = (char *) str + save;// if the string is of base 8 and in the form 0incorrect string
else //then we return everything after the 0 as the endptr string
*endPtr = (char *) str;//in other cases no conversion was done so we return original pointer
}
return 0L;
}
}
}
I've got problem with writing implementation of strtol() function. The thing is i compiled it on 64 bit machine and the output was correct but today i checked it on another machine that is 32-bit and something got wrong. 32-bit machine showed the result that for example string "7FFFFFFF" is out of range when on 64-bits the results is that strtol succeded which is the same as for th standard function. I also checked errno value and for 32-bit machine it's set to ERANGE which shouldn't be and it's not not on 64-bit. I have program that checks if your implementation gives the same output as the standard one for different strings. I spent few hours looking for possible bug but i'm out of ideas? Any tips?

Resources