Card Game
Source: codechef
Difficulty: 671

Card Game
There is a set of$N$cards where each card is numbered$1$to$N$.
Chef throws a card numbered$X$.
Find the number of ways, Chefina can chose a card from the remaining deck such that, the sum of chosen card and$X$is
even
.
Input Format
The first line of input will contain a single integer$T$, denoting the number of test cases.
Each test case consists of two space-separated integers$N$and$X$— the number of cards and the card thrown by Chef.
Output Format
For each test case, output on a new line, the number of ways, Chefina can chose a card from the remaining deck such that, the sum of chosen card and$X$is
even
.
Constraints$1 \leq T \leq 10^5$$2 \leq N \leq 1000$$1 \leq X \leq N$Sample 1:
Explanation:
Test case$1$:
Chefina can only chose card numbered$3$such that the sum is$3+1=4$, which is even.
Test case$2$:
There are two cards and Chef throws card numbered$2$. Thus, Chefina cannot chose any card such that sum is even.
Test case$3$:
Chefina can only chose card numbered$2$such that the sum is$4+2=6$, which is even.

Sample Input:
3
3 1
2 2
5 4

Sample Output:
1
0
1

C++ solution:
#include <bits/stdc++.h>
#include <chrono>
#include <random>

using namespace std;
#define pb push_back
#define mp make_pair
#define f first
#define s second
#define all(x) x.begin(), x.end()
#define sz(x) (int)x.size()
#define forall(x) for(auto &it:x)
#define fOr(i,b) for(ll i=0;i<b;++i)
#define endl '\n'

typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;     
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<pii> vpii;
typedef vector<pll> vpll;

const int mod = 1e9 + 7;
const int inf = 1e9 + 5; 
const ld PI = 3.14159265358979323846;
const int MAXN = 1e5 + 5;

#define NIKHIL_DEBUG

template<typename T> ostream& operator<<(ostream &os, const vector<T> &v) {
    os << '{';
    for (size_t i = 0; i < v.size(); ++i) {
        if (i > 0) os << ", ";
        os << v[i];
    }
    return os << '}';
}

template<typename T1, typename T2> ostream& operator<<(ostream &os, const pair<T1, T2> &p) {
    return os << '(' << p.first << ", " << p.second << ')';
}

void dbg_out() { cerr << endl; }
template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) {
    cerr << ' ' << H;
    dbg_out(T...);
}
#ifdef NIKHIL_DEBUG
#define dbg(...) cerr << '[' << #__VA_ARGS__ << "]:", dbg_out(__VA_ARGS__)
#else
#define dbg(...)

#endif

#define sortv(v) sort(all(v))
#define revsortv(v) sort(all(v), greater<int>())
#define lb lower_bound
#define ub upper_bound

#define mem(a, x) memset(a, x, sizeof(a))

mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());

int random(int a, int b) {
    return uniform_int_distribution<int>(a, b)(rng);
}

int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
}

int gcd(int a, int b, int c) {
    return gcd(a, gcd(b, c));
}


int lcm(int a, int b) {
    return (a / gcd(a, b)) * b;
}
bool isPrime(int num) {
    if (num <= 1) return false;
    for (int i = 2; i <= sqrt(num); i++) {
        if (num % i == 0)
            return false;
    }
    return true;
}
int mod_add(int a, int b, int m = mod) {
    return (a + b) % m;
}

int mod_sub(int a, int b, int m = mod) {
    return (a - b + m) % m;
}

int mod_mul(int a, int b, int m = mod) {
    return (1LL * a * b) % m;
}

int mod_exp(int base, int exp, int m = mod) {
    int res = 1;
    while (exp > 0) {
        if (exp % 2 == 1) res = (1LL * res * base) % m;
        base = (1LL * base * base) % m;
        exp /= 2;
    }
    return res;
}

vector<int> compress(vector<int> &v) {
    vector<int> temp = v;
    sort(all(temp));
    temp.erase(unique(all(temp)), temp.end());
    for (auto &x : v) x = lower_bound(all(temp), x) - temp.begin();
    return v;
}
ll n, m, k, q, l, r, x, y, z;
string s, t;
ll ans = 0;


void solve(){
    cin >> n >> k;
    int evencard = n/2;
    if(k%2==0){
        cout << evencard-1 << endl; 
    }else{
        cout << n-evencard-1 << endl;
    }
    
}
signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0);

#ifndef ONLINE_JUDGE
    //freopen("Input.txt", "r", stdin);
    //freopen("Output.txt", "w", stdout);
    //freopen("Error.txt", "w", stderr);
#endif

    auto start = chrono::high_resolution_clock::now();

    int tt ;
    cin >> tt;
    for(int i=1;i<=tt;i++){
    //cout << "Case #"<<i << ": ";
        solve();  
    }
    /*
    auto end = chrono::high_resolution_clock::now();
    auto duration = chrono::duration_cast<chrono::milliseconds>(end - start);
    cerr << "Execution Time: " << duration.count() << " ms" << endl;
    */
    return 0;
}

Go solution:
package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    reader := bufio.NewReader(os.Stdin)
    writer := bufio.NewWriter(os.Stdout)
    defer writer.Flush()

    var T int
    fmt.Fscan(reader, &T)

    for t := 0; t < T; t++ {
        var N, X int
        fmt.Fscan(reader, &N, &X)

        oddCount := (N + 1) / 2
        evenCount := N / 2

        var result int
        if X%2 == 0 {
            result = evenCount
        } else {
            result = oddCount
        }

        if X%2 == 0 && evenCount > 0 {
            result--
        } else if X%2 != 0 && oddCount > 0 {
            result--
        }

        fmt.Fprintln(writer, result)
    }
}

Java solution:
import java.util.*;
import java.lang.*;
import java.io.*;

class Codechef
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        Scanner scn = new Scanner(System.in);
        int t = scn.nextInt();
        for(int i=0; i<t; i++) {
            int n = scn.nextInt();
            int x = scn.nextInt();
            int even = n/2;
            int odd = 0;
            if(n%2 == 0) {
                odd = n/2;
            }else {
                odd = (n/2)+1;
            }
            
            if(x%2 == 0) {
                System.out.println(even-1);
            }else {
                System.out.println(odd-1);
            }
        }
    }
}

JavaScript solution:
process.stdin.setEncoding('utf8');
let input = '';

process.stdin.on('data', function(chunk) {
    input += chunk;
});

process.stdin.on('end', function() {
    const lines = input.trim().split('\n'); // Split input by lines
    const T = parseInt(lines[0]); // First line is the number of test cases
    let results = []; // Array to store results for each test case

    for (let i = 1; i <= T; i++) {
        const [N, X] = lines[i].split(" ").map(Number); // Read N and X for each test case

        // Calculate number of even and odd cards from 1 to N
        const evenCards = Math.floor(N / 2); // Evens are half of N (or nearly half if N is odd)
        const oddCards = N - evenCards; // Remaining cards are odd

        // Check if X is even or odd
        if (X % 2 === 0) {
            results.push(evenCards - 1); // If X is even, count remaining even cards
        } else {
            results.push(oddCards - 1); // If X is odd, count remaining odd cards
        }
    }

    console.log(results.join('\n')); // Output all results at once
});



//  if(N==X){
//         console.log("0");
//     }else{
//         console.log("1");
//     }
//     }

Python solution:
import sys

def solve():
    input = sys.stdin.read().split()
    idx = 0
    T = int(input[idx])
    idx += 1
    results = []
    for _ in range(T):
        N, X = map(int, input[idx:idx+2])
        idx += 2
        if X % 2 == 0:
            total_even = N // 2
            count = total_even - 1
        else:
            total_odd = (N + 1) // 2
            count = total_odd - 1
        results.append(count)
    print('\n'.join(map(str, results)))

solve()

Ruby solution:
def main
  input = $stdin.read.split
  idx = 0
  test_cases = input[idx].to_i
  idx += 1
  results = []
  
  test_cases.times do
    n = input[idx].to_i
    x = input[idx + 1].to_i
    idx += 2
    
    if x.even?
      # Total even numbers is n / 2
      total_even = n / 2
      # Subtract 1 only if there are other even numbers
      count = [total_even - 1, 0].max
    else
      # Total odd numbers is (n + 1) / 2
      total_odd = (n + 1) / 2
      # Subtract 1 only if there are other odd numbers
      count = [total_odd - 1, 0].max
    end
    
    results << count
  end
  
  puts results.join("\n")
end

main