beginner – Queue related Codeforces problem in C++

my solution is getting time limit error after 15 test cases and i couldn’t come up with a better solution. can’t find it in internet too. Please help me with the logic.

my code :

#include <bits/stdc++.h>
using namespace std;

#define ll long long
#define fo(i, k, n) for (ll i = k; i < n; i++)
#define defo(i, k, n) for (ll i = k; i >= n; i--)
#define Size(n) ((int)(n).size())
typedef vector<ll> vl;

ll solve(vl a, ll k)
{
    queue<ll> q;
    defo(i, Size(a) - 1, k) q.push(a(i));
    while (Size(q) > 1)
    {
        if (q.front() < q.back())
            return Size(q) - 2;
        else
            q.pop();
    }

    return -1;
}

int main()
{
    ll n;
    cin >> n;
    vl a(n);
    fo(i, 0, n) cin >> a(i);
    fo(i, 0, n) cout << solve(a, i) << " ";
    cout << endl;

    return 0;
}

beginner – gpuIncreaseOne Function Implementation in CUDA

I am trying to perform the basic operations + with CUDA for GPU computation. The function vectorIncreaseOne is the instance for the operation details and gpuIncreaseOne function is the structure for applying the operation to each element in the parameter data_for_calculation.

The experimental implementation

The experimental implementation of gpuIncreaseOne function is as below.

#include <stdio.h>
#include <cuda_runtime.h>
#include <cuda.h>
#include <helper_cuda.h>
#include <math.h>

__global__ void CUDACalculation::vectorIncreaseOne(const long double* input, long double* output, int numElements)
{
    int i = blockDim.x * blockIdx.x + threadIdx.x;

    if (i < numElements)
    {
        if (input(i) < 255)
        {
            output(i) = input(i) + 1;
        }
    }
}

int CUDACalculation::gpuIncreaseOne(float* data_for_calculation, int size)
{
    // Error code to check return values for CUDA calls
    cudaError_t err = cudaSuccess;

    // Print the vector length to be used, and compute its size
    int numElements = size;
    size_t DataSize = numElements * sizeof(float);

    // Allocate the device input vector A
    float *d_A = NULL;
    err = cudaMalloc((void **)&d_A, DataSize);
    if (err != cudaSuccess)
    {
        fprintf(stderr, "Failed to allocate device vector A (error code %s)!n", cudaGetErrorString(err));
        exit(EXIT_FAILURE);
    }

    // Allocate the device input vector B
    float *d_B = NULL;
    err = cudaMalloc((void **)&d_B, DataSize);
    if (err != cudaSuccess)
    {
        fprintf(stderr, "Failed to allocate device vector B (error code %s)!n", cudaGetErrorString(err));
        exit(EXIT_FAILURE);
    }

    // Allocate the device output vector C
    float *d_C = NULL;
    err = cudaMalloc((void **)&d_C, DataSize);
    if (err != cudaSuccess)
    {
        fprintf(stderr, "Failed to allocate device vector C (error code %s)!n", cudaGetErrorString(err));
        exit(EXIT_FAILURE);
    }

    // Copy the host input vectors A and B in host memory to the device input vectors in
    // device memory
    err = cudaMemcpy(d_A, data_for_calculation, DataSize, cudaMemcpyHostToDevice);

    if (err != cudaSuccess)
    {
        fprintf(stderr, "Failed to copy vector A from host to device (error code %s)!n", cudaGetErrorString(err));
        exit(EXIT_FAILURE);
    }

    // Launch the Vector Add CUDA Kernel
    int threadsPerBlock = 256;
    int blocksPerGrid =(numElements + threadsPerBlock - 1) / threadsPerBlock;
    printf("CUDA kernel launch with %d blocks of %d threadsn", blocksPerGrid, threadsPerBlock);
    vectorIncreaseOne <<<blocksPerGrid, threadsPerBlock>>>(d_A, d_C, numElements);

    err = cudaGetLastError();

    if (err != cudaSuccess)
    {
        fprintf(stderr, "Failed to launch vectorAdd kernel (error code %s)!n", cudaGetErrorString(err));
        exit(EXIT_FAILURE);
    }

    // Copy the device result vector in device memory to the host result vector
    // in host memory.
    err = cudaMemcpy(data_for_calculation, d_C, DataSize, cudaMemcpyDeviceToHost);

    if (err != cudaSuccess)
    {
        fprintf(stderr, "Failed to copy vector C from device to host (error code %s)!n", cudaGetErrorString(err));
        exit(EXIT_FAILURE);
    }

    // Free device global memory
    err = cudaFree(d_A);

    if (err != cudaSuccess)
    {
        fprintf(stderr, "Failed to free device vector A (error code %s)!n", cudaGetErrorString(err));
        exit(EXIT_FAILURE);
    }

    err = cudaFree(d_B);

    if (err != cudaSuccess)
    {
        fprintf(stderr, "Failed to free device vector B (error code %s)!n", cudaGetErrorString(err));
        exit(EXIT_FAILURE);
    }

    err = cudaFree(d_C);

    if (err != cudaSuccess)
    {
        fprintf(stderr, "Failed to free device vector C (error code %s)!n", cudaGetErrorString(err));
        exit(EXIT_FAILURE);
    }
    return 0;
}

Test cases

The test case for gpuIncreaseOne function is as below.

auto data_pointer = (float*)malloc(100 * sizeof(float));
for (int i = 0; i < 100; i++)
{
    data_pointer(i) = static_cast<float>(1);
}
CUDACalculation::gpuIncreaseOne(data_pointer, 100);


free(data_pointer);

All suggestions are welcome.

If there is any possible improvement about:

  • Potential drawback or unnecessary overhead
  • Error handling

please let me know.

beginner – Tic-Tac-Toe code using c#

In this review let me try to focus on the longest part of your code: WinCondition.

  • Try to separate condition checks from user interaction, do not mix them
  • Try to use better naming, like: CheckVictory, HasAWinner, HasGameEnded, etc.
  • Try to separate data and logic during condition checks

When they are not separated

var conditions = new List<bool>
{
    // checks for horizontal wins
    options(0) == options(1) && options(1) == options(2),
    options(3) == options(4) && options(4) == options(5),
    options(6) == options(7) && options(7) == options(8),
    // checks for vertical wins
    options(0) == options(3) && options(3) == options(6),
    options(1) == options(4) && options(4) == options(7),
    options(2) == options(5) && options(5) == options(8),
    // checks for diagonal wins
    options(0) == options(4) && options(4) == options(8),
    options(2) == options(4) && options(4) == options(6)

};

return conditions.FirstOrDefault(condition => condition));

When they are separated

//Data
var horizontalMarks = new List<(int, int, int)>
{
    (0, 1, 2),
    (3, 4, 5),
    (6, 7, 8)
};

var verticalMarks = new List<(int, int, int)>
{
    (0, 3, 4),
    (1, 4, 7),
    (2, 5, 8)
};

var diagonalMarks = new List<(int, int, int)>
{
    (0, 4, 8),
    (2, 4, 6)
};
var marks = horizontalMarks.Union(verticalMarks).Union(diagonalMarks);

//Logic
bool hasAWinner = false;
foreach (var (first, second, third) in marks)
{
    //If all data in this three positions are the same then we have found a winner
    if (new() {options(first), options(second), options(third)}.Distinct().Count() != 1) continue;
    hasAWinner = true;
    break;
}

return hasAWinner;

If you wish you can introduce a helper class instead of relying on ValueTuples.

beginner – Java Macro Program

I’ve created a macro program using java applet, I’m planning on adding more ways to add a macro but I’ve been stuck on the “Key binds” part of my plan. I’ve tried many ways of adding a keybind to start the macro when the applet window is not focused/selected. I want to use a keybind to activate the macro as if it were the button I’ve added labeled “Run Macro”, but make it activate even if the applet is not selected as a window, meaning I want to for example be inside the game Minecraft and then just press “CTRL+P” which activates the macro.

Question:
How would I add keybinds that affect the applet even when the applet is not the “active window”?

Note:
I did use JDK 8(for applet aka appletviewer.exe) and modified the policy to allow permission for macro robot commands.

Code:
MacroApplet.java

//Robot Imports
import java.awt.Robot;
import java.awt.AWTException;
import java.awt.event.KeyEvent;

//Applet Imports
import java.applet.Applet;
import java.awt.geom.*;
import java.awt.event.*;
import java.awt.*;
import java.applet.*;

public class MacroApplet extends Applet implements ActionListener
{
    int buttonpresses=0;
    int counter=0;
    int timee=0;

    Button button1 = new Button ("Start");

////////////////////////////////////////////////////////////////////////////////
////
        Label Long = new Label ("                                                                                                                                                                                                                                                                                     ");
        Label Long1 = new Label ("                                                                                                                                                                                                                                                                                     ");
        Label Long2 = new Label ("                                                                                                                                                                                                                                                                                     ");
        Label Long3 = new Label ("                                                                                                                                                                                                                                                                                     ");
        Label Long4 = new Label ("                                                                                                                                                                                                                                                                                     ");
        Label Long5 = new Label ("                                                                                                                                                                                                                                                                                     ");
        Label Long6 = new Label ("                                                                                                                                                                                                                                                                                     ");
        Label Long7 = new Label ("                                                                                                                                                                                                                                                                                     ");
        Label Long8 = new Label ("                                                                                                                                                                                                                                                                                     ");
        Label Long9 = new Label ("                                                                                                                                                                                                                                                                                     ");
        Label Long10 = new Label ("                                                                                                                                                                                                                                                                                     ");
////
////////////////////////////////////////////////////////////////////////////////

    Label status = new Label ("Waiting..");

    Label inputkeys = new Label ("Input keys:");
    TextField textfield1 = new TextField ("");
    Label Lwaittime = new Label ("Start waittime:");
    TextField TFwaittime = new TextField ("1500");
    Label Lholdtime = new Label ("Key holdtime:");
    TextField TFholdtime = new TextField ("500");
    Label Lendtime = new Label ("Key waittime:");
    TextField TFendtime = new TextField ("250");

    Checkbox M1 = new Checkbox("At start click");
    Checkbox M2 = new Checkbox("At end click");

    Label Plays = new Label ("Run amount:");
    TextField Rtimes = new TextField ("1");

////////////////////////////////////////////////////////////////////////////////
////Check invis characters (only for testing)
    public void paint (Graphics g)
    {
        //setBackground(Color.gray);
    }
////
////////////////////////////////////////////////////////////////////////////////


    public void init ()
    {
        add(button1);
        button1.addActionListener(this);

////////////////////////////////////////////////////////////////////////////////
////
                    add(Long1);
                    add(Long2);
                    add(Long3);
                    add(Long4);
                    add(Long5);
                    add(Long6);
                    add(Long7);
                    add(Long8);
                    add(Long9);
                    add(Long10);
////
////////////////////////////////////////////////////////////////////////////////
        add(Plays);
        add(M1);
        add(M2);
        add(status);
        add(textfield1);
        add(Lwaittime);
        add(TFwaittime);
        add(Lholdtime);
        add(TFholdtime);
        add(TFendtime);
        add(Lendtime);

        add(Rtimes);

        add(inputkeys);
    }

    public void actionPerformed (ActionEvent e) //Method for get action
    {
        buttonpresses=buttonpresses+1;
        textfield1.setBounds(115,50,135,20);
        inputkeys.setBounds(45,50,105,20);
        button1.setLabel("Run Macro");
        button1.setBounds(145,20,80,20);
        status.setBounds(70,20,80,20);
        Lwaittime.setBounds(45,75,80,20);
        TFwaittime.setBounds(135,75,80,20);
        Lholdtime.setBounds(45,95,80,20);
        TFholdtime.setBounds(135,95,80,20);
        Lendtime.setBounds(45,115,80,20);
        TFendtime.setBounds(135,115,80,20);
        M1.setBounds(130,135,180,20);
        M2.setBounds(130,155,180,20);
        Rtimes.setBounds(130,185,40,20);
        Plays.setBounds(45,185,80,20);

////////////////////////////////////////////////////////////////////////////////
////
                        Long1.setBounds(0,0,0,0);
                        Long2.setBounds(0,0,0,0);
                        Long3.setBounds(0,0,0,0);
                        Long4.setBounds(0,0,0,0);
                        Long5.setBounds(0,0,0,0);
                        Long6.setBounds(0,0,0,0);
                        Long7.setBounds(0,0,0,0);
                        Long8.setBounds(0,0,0,0);
                        Long9.setBounds(0,0,0,0);
////
////////////////////////////////////////////////////////////////////////////////

        if (e.getSource()==button1 && buttonpresses>1)
        {
            do
            {
                String times = Rtimes.getText();
                timee=Integer.parseInt(times);

                counter=counter+1;

                status.setText("Running..");
                try
                {
                    Robot robot = new Robot();

                    //string is the input box
                    String string = textfield1.getText();
                    String stringCaps = string.toUpperCase();

                    char() chars = string.toCharArray();
                    char() charsCaps = stringCaps.toCharArray();

                    //Wait abit
                    try
                    {
                        String waittime = TFwaittime.getText();
                        int time=Integer.parseInt(waittime);

                        Thread.sleep(time);
                    }

                    catch(InterruptedException ex)
                    {
                        Thread.currentThread().interrupt();
                    }
                    //Wait abit

                    //StartMouseClickCheckBox
                    boolean checked = M1.getState();
                    if(M1.getState())
                    {
                    robot.mousePress(InputEvent.BUTTON1_MASK);
                    robot.mouseRelease(InputEvent.BUTTON1_MASK);
                    }

                    for(int i=0; i < charsCaps.length; i++)
                    {
                        if(chars(i) ==charsCaps(i))robot.keyPress(KeyEvent.VK_SHIFT);
                        robot.keyPress(charsCaps(i));

                        //Hold time
                        //Wait abit
                        try
                        {
                            String holdtime = TFholdtime.getText();
                            int time=Integer.parseInt(holdtime);

                            Thread.sleep(time);
                        }

                        catch(InterruptedException ex)
                        {
                            Thread.currentThread().interrupt();
                        }
                        //Wait abit

                        robot.keyRelease(charsCaps(i));
                        robot.keyRelease(KeyEvent.VK_SHIFT);

                        //Ending time
                        //Wait abit
                        try
                        {
                            String endtime = TFendtime.getText();
                            int time=Integer.parseInt(endtime);

                            Thread.sleep(time);
                        }

                        catch(InterruptedException ex)
                        {
                            Thread.currentThread().interrupt();
                        }
                        //Wait abit
                    }
                    //EndMouseClickCheckBox
                    boolean on = M2.getState();
                    if(M2.getState())
                    {
                    robot.mousePress(InputEvent.BUTTON1_MASK);
                    robot.mouseRelease(InputEvent.BUTTON1_MASK);
                    }
                    status.setText("Completed!");
                }
            catch (AWTException s)
            {
                s.printStackTrace();
            }
        }while(timee!=counter); counter=0;
        }
    }
}

Thanks in advance for any tips or help on the keybinds part of my project!

beginner – Hangman Game from OCW MIT 6.0001 Pset No. 2

I’m going to go function by function and explain what I changed and why.

Imports I used:

from typing import List

def load_words() -> List(str):
    """
    Returns a list of valid words. Words are strings of lowercase letters.
    
    Depending on the size of the word list, this function may
    take a while to finish.
    """
    with open(WORDLIST_FILENAME, 'r') as file:
        wordlist = (word.strip() for word in file.readlines())
    return wordlist

I see that you have type hints above every variable. Luckily for you, you can do this inline with the exact same format.

variable: int = 10

Make sure you close files when you open them. If you don’t want to worry about that, use a with statement, which will automatically close the file once you exit the context.

You can also use type hints to display what types of parameters you accept, if any, and what types of values you return, if any.

def choose_word(wordlist: List(str)) -> str:
    """
    wordlist (list): list of words (strings)
    
    Returns a word from wordlist at random
    """
    return random.choice(wordlist)

Only thing I changed here was adding type hints. Now it’s clear wordlist is a List of string, and the function returns a string.

def is_word_guessed(secret_word: str, letters_guessed: List(str)) -> bool:
    '''
    secret_word: string, the word the user is guessing; assumes all letters are
      lowercase
    letters_guessed: list (of letters), which letters have been guessed so far;
      assumes that all letters are lowercase
    returns: boolean, True if all the letters of secret_word are in letters_guessed;
      False otherwise
    '''
    guess = ""
    for char in secret_word:
        for letter in letters_guessed:
            if char == letter:
                guess += char
            else:
                continue
    
    return guess == secret_word

Personally, I would just use "" when creating an empty string. Again, note the type hints.

Instead of return True else return False, you can return the boolean condition that is being evaluated. It does the same exact thing, but it’s shorter and looks a lot nicer.

def get_guessed_word(secret_word: str, letters_guessed: List(str)) -> str:
    '''
    secret_word: string, the word the user is guessing
    letters_guessed: list (of letters), which letters have been guessed so far
    returns: string, comprised of letters, underscores (_), and spaces that represents
      which letters in secret_word have been guessed so far.
    '''
    showbox_list = ('_ ' for _ in secret_word)
    for letter in letters_guessed:
        for count, char in enumerate(secret_word):
            if letter == char:
                showbox_list(count) = letter
            else:
                continue
    
    return ''.join(showbox_list)

Instead of using a traditional for loop, I would use list comprehension to construct your showbox list. The _ variable just indicates that the variable used in the loop should be ignored. Instead of creating a variable, then returning that variable, just return the value you would have assigned to that variable. Again, type hints.

def get_available_letters(letters_guessed: List(str)) -> str:
    '''
    letters_guessed: list (of letters), which letters have been guessed so far
    returns: string (of letters), comprised of letters that represents which letters have not
      yet been guessed.
    '''
    english_letters = (char for char in string.ascii_lowercase if char not in letters_guessed)
    
    english_letters_str = ''.join(english_letters)
    print('Available letters:', english_letters_str)
    
    return english_letters_str

Again, you can use list comprehension to construct your initial list. This adds every character in the string.ascii_lowercase list, but ONLY if the character is not in the letters_guessed list. Obligatory type hints point.

def match_with_gaps(my_word: str, other_word: str) -> bool:
    '''
    my_word: string with _ characters, current guess of secret word
    other_word: string, regular English word
    returns: boolean, True if all the actual letters of my_word match the 
        corresponding letters of other_word, or the letter is the special symbol
        _ , and my_word and other_word are of the same length;
        False otherwise: 
    '''
    my_word_stripped = my_word.replace(" ", "")
    same_char = ()
    blank_stripped = ()
    if len(my_word_stripped) != len(other_word):
        return False
    for index, letter in enumerate(my_word_stripped):
        if letter in string.ascii_lowercase:
            same_char.append(index)
        else:
            blank_stripped.append(index)

    mws = ''
    ow = ''
    for index_same in same_char:
        for index_dif in blank_stripped:
            if other_word(index_dif) == other_word(index_same):
                return False
            mws += my_word_stripped(index_same)
            ow += other_word(index_same)
    
    return mws == ow

The most important thing I want to stress here is guard clauses. These prevent you from having to indent into another context space. It makes your code look nicer, and is a good thing to practice.

You don’t need an else if the if returns from the function. Again, type hints and returning boolean expressions.

def show_possible_matches(my_word: str) -> str:
    '''
    my_word: string with _ characters, current guess of secret word
    returns: nothing, but should print out every word in wordlist that matches my_word
             Keep in mind that in hangman when a letter is guessed, all the positions
             at which that letter occurs in the secret word are revealed.
             Therefore, the hidden letter(_ ) cannot be one of the letters in the word
             that has already been revealed.

    '''
    possible_matches = (i for i in wordlist if match_with_gaps(my_word, i))
    return ' '.join(possible_matches)

Using list comprehension reduces the need for the for loop, allowing you to accomplish the same task in one line. Again, type hints.


One more thing I’d like to add. You said that you initially didn’t want to post the entire program because “it was too long”. Most of the length of your program comes down to docstrings. Now, this isn’t inherently a bad thing. Looking through them, this looks like a problem set, and these are instructions. Thats fine. But keep in mind that docstrings should really only display what the function does, what parameters it accepts (if any), and what it returns. I personally think the hangman_with_hints docstring goes a little over the top (25 lines!), but that’s just me.

beginner – Easter date calculator Android application

Since Easter holidays are close, I have decided to develop my Android skills by writing an Android app that calculate that date for the Western and Easter calendars.

The formulas were gotten from the Internet.
It is a simple app where, you enter the year and you get the dates for both calendars in a TextView, I’ve used EditText as labels and made them unclickable, they appear when the dates are visible and get hidden when the dates are not show.

I do not have any professional or internship experience whatsoever. Any input would help.
It was built and compiled on Android Studio 4.1.2 and ran on my device.

Here is the code for the XML.

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <TextView
        android:id="@+id/textView"
        android:layout_width="459dp"
        android:layout_height="56dp"
        android:layout_marginTop="8dp"
        android:layout_marginBottom="8dp"
        android:text="@string/welcome"
        android:textSize="22sp"
        app:layout_constraintBottom_toTopOf="@+id/editTextDate"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        android:gravity="center"
        app:layout_constraintTop_toTopOf="parent" />

    <EditText
        android:id="@+id/editTextDate"
        android:layout_width="wrap_content"
        android:layout_height="46dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:gravity="center"
        android:maxLength="4"
        android:digits="0123456789"
        android:inputType="date"
        android:textSize="22sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

    <TextView
        android:id="@+id/textViewWestern"
        android:layout_width="150dp"
        android:layout_height="48dp"
        android:layout_marginTop="60dp"
        android:gravity="center"
        android:text=""
        android:textSize="22sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.045"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextDate" />

    <TextView
        android:id="@+id/textViewEastern"
        android:layout_width="150dp"
        android:layout_height="48dp"
        android:layout_marginTop="60dp"
        android:gravity="center"
        android:text=""
        android:textSize="22sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.969"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextDate" />

    <EditText
        android:id="@+id/western"
        android:layout_width="150dp"
        android:layout_height="44dp"
        android:layout_marginStart="12dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:gravity="center"
        android:inputType="textPersonName"
        android:background="@android:color/transparent"
        android:text="Western"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextDate" />

    <EditText
        android:id="@+id/eastern"
        android:layout_width="150dp"
        android:layout_height="44dp"
        android:layout_marginTop="16dp"
        android:ems="10"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:inputType="textPersonName"
        android:text="Eastern"
        android:background="@android:color/transparent"
        android:gravity="center"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.969"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/editTextDate" />
</androidx.constraintlayout.widget.ConstraintLayout> 

The MainActivity.java code.

package com.example.easterdate;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        EditText Edit = findViewById(R.id.editTextDate);
        final TextView text = findViewById(R.id.textViewWestern);
        final TextView textEastern = findViewById(R.id.textViewEastern);
        final EditText eastern = findViewById(R.id.eastern);
        final EditText western = findViewById(R.id.western);

        eastern.setVisibility(View.INVISIBLE);
        western.setVisibility(View.INVISIBLE);

        Edit.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (s.toString().trim().length() == 0 || Integer.parseInt(s.toString()) < 1800) {
                    text.setText("");
                    textEastern.setText("");
                    eastern.setVisibility(View.INVISIBLE);
                    western.setVisibility(View.INVISIBLE);
                    return;
                }

                EditText Edit = findViewById(R.id.editTextDate);
                int AN = Integer.parseInt(Edit.getText().toString());

                int G = AN % 19;
                int C = AN / 100;
                int H = (C - C / 4 - (8 * C + 13) / 25 + 19 * G + 15) % 30;
                int I = H - (H / 28) * (1 - (H / 28) * (29 / (H + 1)) * ((21 - G) / 11));
                int J = (AN + AN / 4 + I + 2 - C + C / 4) % 7;

                int L = I - J;
                int MP = 3 + (L + 40) / 44;
                int JP = L + 28 - 31 * (MP / 4);

                int mon, day;

                int A = AN % 19;
                int b = AN % 7;
                int ce = AN % 4;
                int d = (19 * A + 16) % 30;
                int e = (2 * ce + 4 * b + 6 * d) % 7;
                int f = (19 * A + 16) % 30;
                int key = f + e + 3;
                if (key > 30)
                    mon = 5;
                else
                    mon = 4;
                if (key > 30)
                    day = key - 30;
                else day = key;

                String() month = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};

                eastern.setVisibility(View.VISIBLE);
                western.setVisibility(View.VISIBLE);
                text.setText("Sunday " + JP + " " + month(MP - 1));
                textEastern.setText("Sunday " + day + " " + month(mon - 1));

            }

            @Override
            public void afterTextChanged(Editable s) {


            }
        });

    }
}

How professional is this code? should I have used functions instead of imperative programming?
The TextWatcher is used to prevent the app from crashing and to have the dates display on input, any better solution?

Low cost Business for a beginner

I have been thinking about adding a side business to my online hustle.I have less than a $100 to start with and I have been researching on the best products or business to start with.

It could just be any thing provided it a sustainable and profitable business.Those in the know,what online business is very profitable and sustainable and can be started with small amount of money.

beginner – Company database REPL program in Rust for Chapter 8 of The Book

I implemented a solution for the third exercise of Chapter 8 of The Book. I’m still trying to build my intuition for what makes a good Rust program and so would really appreciate some pointers to help me improve. Here’s my current solution:

// Using a hash map and vectors, create a text interface to allow a user to
// add employee names to a department in a company. For example, “Add
// Sally to Engineering” or “Add Amir to Sales.” Then let the user retrieve
// a list of all people in a department or all people in the company by
// department, sorted alphabetically.

// @todo Add functions to remove people, departments and companies. Add a clear function.

use std::collections::HashMap;
use std::collections::HashSet;
use std::io;
use std::io::Write;

#(derive(Debug, PartialEq, Eq, Hash, Clone, PartialOrd, Ord))
struct Employee(String);
#(derive(Debug))
struct Department(HashSet<Employee>);
#(derive(Debug))
struct Company(HashMap<String, Department>);

fn make_company() -> Company {
    Company(HashMap::new())
}

#(derive(Debug))
struct ExistingDepartment(String);

// This assumes all department names are unique.
fn add_department(company: &mut Company, department: &str) -> Result<(), ExistingDepartment> {
    let department_name = String::from(department);
    match company.0.contains_key(&department_name) {
        true => Err(ExistingDepartment(department_name)),
        false => {
            company
                .0
                .insert(department_name, Department(HashSet::<Employee>::new()));
            Ok(())
        }
    }
}

#(derive(Debug))
enum AddEmployeeError {
    NonexistentDepartment(String),
    ExistingEmployee(Employee),
}

// This assumes that all employee names in a department are unique.
fn add_employee(
    company: &mut Company,
    department_name: &str,
    employee: Employee,
) -> Result<(), AddEmployeeError> {
    match company.0.get_mut(department_name) {
        None => Err(AddEmployeeError::NonexistentDepartment(String::from(
            department_name,
        ))),
        Some(department) => match department.0.insert(employee.clone()) {
            true => Ok(()),
            false => Err(AddEmployeeError::ExistingEmployee(employee)),
        },
    }
}

#(derive(Debug))
struct NonexistentDepartment(String);

fn get_employees_department(
    company: &Company,
    department_name: &str,
) -> Result<Vec<Employee>, NonexistentDepartment> {
    match company.0.get(department_name) {
        None => Err(NonexistentDepartment(String::from(department_name))),
        Some(department) => {
            let mut result: Vec<Employee> = department.0.iter().cloned().collect();
            result.sort_unstable();
            Ok(result)
        }
    }
}

fn get_employees_company(company: &Company) -> Vec<Employee> {
    let mut result = company
        .0
        .keys()
        .map(|department| get_employees_department(company, department).unwrap())
        .collect::<Vec<Vec<Employee>>>()
        .concat();
    result.sort_unstable();
    result
}

fn format_slice(slice: &(Employee)) -> Option<String> {
    match slice.len() {
        0 => None,
        _ => Some(
            slice
                .iter()
                .map(|employee| employee.0.to_string())
                .collect::<Vec<String>>()
                .join("n"),
        ),
    }
}

#(derive(PartialEq))
enum GetInput {
    Print,
    Read,
    Parse,
}

#(derive(PartialEq))
enum Mode {
    Greet,
    GetInput(GetInput),
    Quit,
}

struct State {
    mode: Mode,
    company: Company,
    input: String,
}

fn make_state() -> State {
    State {
        company: make_company(),
        mode: Mode::Greet,
        input: String::new(),
    }
}

fn print_flush(input: &str) -> Result<(), std::io::Error> {
    print!("{}", input);
    io::stdout().flush()
}

fn read_line(string: &mut String) -> Result<usize, std::io::Error> {
    string.clear();
    io::stdin().read_line(string)
}

// This assumes that department and employee names don't have whitespace.
fn process_input(state: &mut State) {
    let company = &mut state.company;
    match state.input.len() {
        0 => {
            state.mode = Mode::GetInput(GetInput::Print);
        }
        _ => {
            let tokens: Vec<&str> = state.input.split_whitespace().collect();
            match tokens.get(0) {
                None => {
                    state.mode = Mode::GetInput(GetInput::Print);
                }
                Some(token) => match *token {
                    "quit" => {
                        println!("Bye for now!");
                        state.mode = Mode::Quit;
                    }
                    command => {
                        match command {
                            "add-department" => match tokens(1..).len() {
                                0 => println!("Command "{}" requires at least 1 argument.", command),
                                _ => tokens(1..).iter().for_each(|element| match add_department(company, element) {
                                    Ok(_) => (),
                                    Err(error) => println!("Error: {:?}", error)
                                })
                            },
                            "add-employee" => match tokens(1..).len() {
                                0 ..= 1 => println!("Command "{}" requires at least 2 arguments.", command),
                                _ => match company.0.contains_key(tokens(1)) {
                                    true => tokens(2..).iter().for_each(|employee| match add_employee(company, tokens(1), Employee(employee.to_string())) {
                                        Ok(_) => (),
                                        Err(error) => println!("Error: {:?}", error)
                                    }),
                                    false => println!("Department "{}" doesn't exist.", tokens(1))
                                }
                            },
                            "get-employees" => match tokens(1..).len() {
                                0 => println!("Command "{}" requires at least 1 argument.", command),
                                _ => tokens(1..).iter().for_each(|department| match company.0.contains_key(*department) {
                                    true => match format_slice(&get_employees_department(company, department).unwrap()) {
                                        None => println!("Department "{}" has no employees.", department),
                                        Some(employees) => println!(
                                            "Employees in "{}":
{}", department, employees)
                                    },
                                    false => println!("Department "{}" doesn't exist.", department)
                                })
                            },
                            "get-employees-all" => match format_slice(&get_employees_company(company)) {
                                None => println!("Company has no employees."),
                                Some(employees) => println!(
                                    "Employees:
{}", employees)
                            },
                            "help" => println!(
                                "Commands:

add-department <department_name (department_name ...)>
  Add one or more departments to the company.

add-employee <department_name> <employee_name (employee_name ...)>
  Add one or more employees to a department.

get-employees <department_name (department_name ...)>
  Print a list of employees from one or more departments.

get-employees-all
  Print a list of all employees in the company.

help
  Print this message.

quit
  Quit."
                            ),
                            command => {
                                println!("Invalid command "{}".", command);
                            }
                        }
                        state.mode = Mode::GetInput(GetInput::Print);
                    }
                },
            }
        }
    }
}

fn state_machine(state: &mut State) {
    match &state.mode {
        Mode::Greet => {
            println!(
                "Database program.
Enter "help" for a list of commands."
            );
            state.mode = Mode::GetInput(GetInput::Print);
        }
        Mode::GetInput(get_input_step) => match get_input_step {
            GetInput::Print => {
                println!("Company: {:?}", state.company);
                match print_flush("> ") {
                    Ok(_) => {
                        state.mode = Mode::GetInput(GetInput::Read);
                    }
                    Err(error) => println!("Error {:?}", error),
                }
            }
            GetInput::Read => match read_line(&mut state.input) {
                Ok(_) => {
                    state.mode = Mode::GetInput(GetInput::Parse);
                }
                Err(error) => println!("Error: {:?}", error),
            },
            GetInput::Parse => process_input(state),
        },
        Mode::Quit => (),
    }
}

fn repl(function: fn(&mut State), state: &mut State) {
    while state.mode != Mode::Quit {
        function(state)
    }
}

fn main() {
    repl(state_machine, &mut make_state())
}

I previously tried to refactor the process_input function to try to decrease nesting by moving parts of it to different functions, but I ran across borrowing issues so I stopped trying. I also couldn’t figure out a nice way to implement it such that it accepts inputs that use the same format as the example (i.e., “Add Amir to Sales”), so I did it a little differently.

I’m also not sure if I’m using the Result type nicely and if the tuple structs and enum I made to pass to them are a good way to do error handling.

I also feel like some of the cloning I did is probably unecessary, but I’m not sure how I could refactor them away, so it would be nice to know if that is indeed the case and how I might refactor. In fact, I think it would be helpful to know how I might determine when it is appropriate to clone or when to borrow, as I think I’m a little iffy about that topic.

On a related note, how should I go about writing functions? Is it generally better to initially write functions such that they clone their arguments, then try to refactor the cloning away later on, or to try to borrow everything up front then try to fix any borrow-checker issues that crop up and only clone if I can’t fix them?

In any case, I’d really appreciate any constructive criticisms and advice.

python – Random number generator [Beginner]

First, an issue with behaviour: In guess_number you don’t make sure the input from the user is a number at all. So you might end up calling int("oops"). This raises a ValueError, and since there’s nothing to catch that, the program crashes. You’ll want to do something about that. A simple solution could be

try:
    guess = int(input(...))
    if guess == random_number:
        ...
    else
        ...
except ValueError:
    print("That doesn't look like a number to me, but that's OK, I'll count it anyway :)")
    guess_count += 1

Side note, guesses that aren’t in the interval also add to the counter. That might be on purpose, but since the validity of the input wasn’t checked at all I don’t want to assume, so I’m pointing it out.

There are also a couple minor issues with intro

First off, you’re duplicating the num_range = input() line. If you get the input at the start of the loop (before the if) instead it’ll be easier to change if for some reason you need to

Second, in python the usual approach is that it’s better to ask for forgiveness than permission. That if check would usually be written using a try/except KeyError block (a bit like above). But if you don’t want to do that, a more robust approach than the current one could be to check if num_range in num_guesses, in case a new option is added, or the program changes from accepting 1 and 2 to accepting "a" and "b".

On a related third note, the messages don’t actually know what options are available, so there’s a risk they get out of sync with the rest of the program. You can get a list of valid options as num_guesses.keys(), or use a for loop to iterate over the keys in num_guesses directly

Finally, I don’t love the variable names. num_guesses sounds like it should be the number of guesses, but it isn’t a number at all. Similarly, num_range doesn’t have much to do with ranges of numbers either. num_range feels like it would be better described by a name like selection or choice, and num_guesses is a collection of available options, so maybe it could be called options?

options = {
    "1": (5, 50),
    "2": (10, 100)
}

print("Welcome to ... on the range you choose.")

for option in options:
    print(f"From 0 - {options(option)(1)}, you'll get {options(option)(0)} chances.")

while True:
    print("Choose a range:")
    for option in options:
        print(f"{option}. 0 - {options(option)(1)}")

    selection = input()
    try:
        return options(selection)
    except KeyError:
        print(f"{selection} is not a valid selection.")

beginner – Tic-tac-toe Game Optimziation (C++)

I made a Tic-tac-toe game where you can play against the program or with another player in C++ and I know the code is far too long for what it is.
I’ve tried to optimize it using non-void functions (so I don’t have to create multiple functions instead of 1 for similar code) and loops to condense some repetitive code. But I couldn’t get anything to work.

I’m still a beginner, so I know I’m missing something.

//Tic-tac-toe
#include <iostream>
#include <string>
#include <vector>

//variables
bool AI_is_smart, game_over, cheat, mistake;
int order, move, x, y;
int turn=1;

//vectors
    std::vector<std::string> boxes{" ", " ", " ", " ", " ", " ", " ", " ", " "};

//functions
//Shows the progression of the game
void gameboard(){
    std::cout<<" ___ ___ ___ t _ _ _n";
    std::cout<<"| "<<boxes(0)<<" | "<<boxes(1)<<" | "<<boxes(2)<<" |t|0|1|2|n";
    std::cout<<" ___ ___ ___ t _ _ _ n";
    std::cout<<"| "<<boxes(3)<<" | "<<boxes(4)<<" | "<<boxes(5)<<" |t|3|4|5|n";
    std::cout<<" ___ ___ ___ t _ _ _ n";
    std::cout<<"| "<<boxes(6)<<" | "<<boxes(7)<<" | "<<boxes(8)<<" |t|6|7|8|n";
    std::cout<<" ___ ___ ___ t _ _ _nn";
}

//Determines if the game should end
bool game_over_conditions(){
    if (boxes(0)+boxes(1)+boxes(2)=="xxx"){std::cout<<"x WINS!n"; game_over = true;}
    else if (boxes(3)+boxes(4)+boxes(5)=="xxx"){std::cout<<"x WINS!n"; game_over = true;}
    else if (boxes(6)+boxes(7)+boxes(8)=="xxx"){std::cout<<"x WINS!n"; game_over = true;}
    else if (boxes(0)+boxes(3)+boxes(6)=="xxx"){std::cout<<"x WINS!n"; game_over = true;}
    else if (boxes(1)+boxes(4)+boxes(7)=="xxx"){std::cout<<"x WINS!n"; game_over = true;}
    else if (boxes(2)+boxes(5)+boxes(8)=="xxx"){std::cout<<"x WINS!n"; game_over = true;}
    else if (boxes(0)+boxes(4)+boxes(8)=="xxx"){std::cout<<"x WINS!n"; game_over = true;}
    else if (boxes(2)+boxes(4)+boxes(6)=="xxx"){std::cout<<"x WINS!n"; game_over = true;}
    else if (boxes(0)+boxes(1)+boxes(2)=="ooo"){std::cout<<"o WINS!n"; game_over = true;}
    else if (boxes(3)+boxes(4)+boxes(5)=="ooo"){std::cout<<"o WINS!n"; game_over = true;}
    else if (boxes(6)+boxes(7)+boxes(8)=="ooo"){std::cout<<"o WINS!n"; game_over = true;}
    else if (boxes(0)+boxes(3)+boxes(6)=="ooo"){std::cout<<"o WINS!n"; game_over = true;}
    else if (boxes(1)+boxes(4)+boxes(7)=="ooo"){std::cout<<"o WINS!n"; game_over = true;}
    else if (boxes(2)+boxes(5)+boxes(8)=="ooo"){std::cout<<"o WINS!n"; game_over = true;}
    else if (boxes(0)+boxes(4)+boxes(8)=="ooo"){std::cout<<"o WINS!n"; game_over = true;}
    else if (boxes(2)+boxes(4)+boxes(6)=="ooo"){std::cout<<"o WINS!n"; game_over = true;}
    else if (boxes(0)!=" "&&boxes(1)!=" "&&boxes(2)!=" "&&boxes(3)!=" "&&
            boxes(4)!=" "&&boxes(5)!=" "&&boxes(6)!=" "&&boxes(7)!=" "&&
            boxes(8)!=" ")
            {std::cout<<"TIE!n"; game_over = true;}
}
    
//Determines if the AI should move with winning intent. If not then it should move randomly
bool AI_type(){   
    if(game_over==true){std::cout<<" ";}
    else if(boxes(0)+boxes(2)=="oo"&&boxes(1)==" "){std::cout<<"Program's turn (o) ...n";boxes(1)="o";AI_is_smart=true;}
    else if(boxes(1)+boxes(2)=="oo"&&boxes(0)==" "){std::cout<<"Program's turn (o) ...n";boxes(0)="o";AI_is_smart=true;}
    else if(boxes(3)+boxes(4)=="oo"&&boxes(5)==" "){std::cout<<"Program's turn (o) ...n";boxes(5)="o";AI_is_smart=true;}
    else if(boxes(3)+boxes(5)=="oo"&&boxes(4)==" "){std::cout<<"Program's turn (o) ...n";boxes(4)="o";AI_is_smart=true;}
    else if(boxes(4)+boxes(5)=="oo"&&boxes(3)==" "){std::cout<<"Program's turn (o) ...n";boxes(3)="o";AI_is_smart=true;}
    else if(boxes(6)+boxes(7)=="oo"&&boxes(8)==" "){std::cout<<"Program's turn (o) ...n";boxes(8)="o";AI_is_smart=true;}
    else if(boxes(6)+boxes(8)=="oo"&&boxes(7)==" "){std::cout<<"Program's turn (o) ...n";boxes(7)="o";AI_is_smart=true;}
    else if(boxes(7)+boxes(8)=="oo"&&boxes(6)==" "){std::cout<<"Program's turn (o) ...n";boxes(6)="o";AI_is_smart=true;}
    else if(boxes(0)+boxes(3)=="oo"&&boxes(6)==" "){std::cout<<"Program's turn (o) ...n";boxes(6)="o";AI_is_smart=true;}
    else if(boxes(0)+boxes(6)=="oo"&&boxes(3)==" "){std::cout<<"Program's turn (o) ...n";boxes(3)="o";AI_is_smart=true;}
    else if(boxes(3)+boxes(6)=="oo"&&boxes(0)==" "){std::cout<<"Program's turn (o) ...n";boxes(0)="o";AI_is_smart=true;}
    else if(boxes(1)+boxes(4)=="oo"&&boxes(7)==" "){std::cout<<"Program's turn (o) ...n";boxes(7)="o";AI_is_smart=true;}
    else if(boxes(1)+boxes(7)=="oo"&&boxes(4)==" "){std::cout<<"Program's turn (o) ...n";boxes(4)="o";AI_is_smart=true;}
    else if(boxes(4)+boxes(7)=="oo"&&boxes(1)==" "){std::cout<<"Program's turn (o) ...n";boxes(1)="o";AI_is_smart=true;}
    else if(boxes(2)+boxes(5)=="oo"&&boxes(8)==" "){std::cout<<"Program's turn (o) ...n";boxes(8)="o";AI_is_smart=true;}
    else if(boxes(2)+boxes(8)=="oo"&&boxes(5)==" "){std::cout<<"Program's turn (o) ...n";boxes(5)="o";AI_is_smart=true;}
    else if(boxes(5)+boxes(8)=="oo"&&boxes(2)==" "){std::cout<<"Program's turn (o) ...n";boxes(2)="o";AI_is_smart=true;}
    else if(boxes(0)+boxes(4)=="oo"&&boxes(8)==" "){std::cout<<"Program's turn (o) ...n";boxes(8)="o";AI_is_smart=true;}
    else if(boxes(0)+boxes(8)=="oo"&&boxes(4)==" "){std::cout<<"Program's turn (o) ...n";boxes(4)="o";AI_is_smart=true;}
    else if(boxes(4)+boxes(8)=="oo"&&boxes(0)==" "){std::cout<<"Program's turn (o) ...n";boxes(0)="o";AI_is_smart=true;}
    else if(boxes(2)+boxes(4)=="oo"&&boxes(6)==" "){std::cout<<"Program's turn (o) ...n";boxes(6)="o";AI_is_smart=true;}
    else if(boxes(2)+boxes(6)=="oo"&&boxes(4)==" "){std::cout<<"Program's turn (o) ...n";boxes(4)="o";AI_is_smart=true;} 
    else if(boxes(4)+boxes(6)=="oo"&&boxes(2)==" "){std::cout<<"Program's turn (o) ...n";boxes(2)="o";AI_is_smart=true;}
    else if(boxes(0)+boxes(2)=="xx"&&boxes(1)==" "){std::cout<<"Program's turn (o) ...n";boxes(1)="o";AI_is_smart=true;}
    else if(boxes(1)+boxes(2)=="xx"&&boxes(0)==" "){std::cout<<"Program's turn (o) ...n";boxes(0)="o";AI_is_smart=true;}
    else if(boxes(3)+boxes(4)=="xx"&&boxes(5)==" "){std::cout<<"Program's turn (o) ...n";boxes(5)="o";AI_is_smart=true;}
    else if(boxes(3)+boxes(5)=="xx"&&boxes(4)==" "){std::cout<<"Program's turn (o) ...n";boxes(4)="o";AI_is_smart=true;}
    else if(boxes(4)+boxes(5)=="xx"&&boxes(3)==" "){std::cout<<"Program's turn (o) ...n";boxes(3)="o";AI_is_smart=true;}
    else if(boxes(6)+boxes(7)=="xx"&&boxes(8)==" "){std::cout<<"Program's turn (o) ...n";boxes(8)="o";AI_is_smart=true;}
    else if(boxes(6)+boxes(8)=="xx"&&boxes(7)==" "){std::cout<<"Program's turn (o) ...n";boxes(7)="o";AI_is_smart=true;}
    else if(boxes(7)+boxes(8)=="xx"&&boxes(6)==" "){std::cout<<"Program's turn (o) ...n";boxes(6)="o";AI_is_smart=true;}
    else if(boxes(0)+boxes(3)=="xx"&&boxes(6)==" "){std::cout<<"Program's turn (o) ...n";boxes(6)="o";AI_is_smart=true;}
    else if(boxes(0)+boxes(6)=="xx"&&boxes(3)==" "){std::cout<<"Program's turn (o) ...n";boxes(3)="o";AI_is_smart=true;}
    else if(boxes(3)+boxes(6)=="xx"&&boxes(0)==" "){std::cout<<"Program's turn (o) ...n";boxes(0)="o";AI_is_smart=true;}
    else if(boxes(1)+boxes(4)=="xx"&&boxes(7)==" "){std::cout<<"Program's turn (o) ...n";boxes(7)="o";AI_is_smart=true;}
    else if(boxes(1)+boxes(7)=="xx"&&boxes(4)==" "){std::cout<<"Program's turn (o) ...n";boxes(4)="o";AI_is_smart=true;}
    else if(boxes(4)+boxes(7)=="xx"&&boxes(1)==" "){std::cout<<"Program's turn (o) ...n";boxes(1)="o";AI_is_smart=true;}
    else if(boxes(2)+boxes(5)=="xx"&&boxes(8)==" "){std::cout<<"Program's turn (o) ...n";boxes(8)="o";AI_is_smart=true;}
    else if(boxes(2)+boxes(8)=="xx"&&boxes(5)==" "){std::cout<<"Program's turn (o) ...n";boxes(5)="o";AI_is_smart=true;}
    else if(boxes(5)+boxes(8)=="xx"&&boxes(2)==" "){std::cout<<"Program's turn (o) ...n";boxes(2)="o";AI_is_smart=true;}
    else if(boxes(0)+boxes(4)=="xx"&&boxes(8)==" "){std::cout<<"Program's turn (o) ...n";boxes(8)="o";AI_is_smart=true;}
    else if(boxes(0)+boxes(8)=="xx"&&boxes(4)==" "){std::cout<<"Program's turn (o) ...n";boxes(4)="o";AI_is_smart=true;}
    else if(boxes(4)+boxes(8)=="xx"&&boxes(0)==" "){std::cout<<"Program's turn (o) ...n";boxes(0)="o";AI_is_smart=true;}
    else if(boxes(2)+boxes(4)=="xx"&&boxes(6)==" "){std::cout<<"Program's turn (o) ...n";boxes(6)="o";AI_is_smart=true;}
    else if(boxes(2)+boxes(6)=="xx"&&boxes(4)==" "){std::cout<<"Program's turn (o) ...n";boxes(4)="o";AI_is_smart=true;} 
    else if(boxes(4)+boxes(6)=="xx"&&boxes(2)==" "){std::cout<<"Program's turn (o) ...n";boxes(2)="o";AI_is_smart=true;}
    else{AI_is_smart=false;}
}
    
//AI moves randomly else sequentially
void program_move_random(){
    srand (time(NULL));
    move = rand()%9;
    if(AI_is_smart==false){
        std::cout<<"Program's turn (o) ...n";
        if (boxes(move)!="x"&&boxes(move)!="o") {boxes(move)="o";}
        else{   if(boxes(0)==" ") { ; boxes(0)="o";}
                else if(boxes(0)!=" "){ int x=1;
                    if(boxes(x)==" ") {;boxes(x)="o";}
                    else if(boxes(x)!=" "){ int x=2;
                        if(boxes(x)==" ") {;boxes(x)="o";}
                        else if(boxes(x)!=" "){  int x=3;
                            if(boxes(x)==" ") {;boxes(x)="o";}
                            else if(boxes(x)!=" "){ int x=4; 
                                if(boxes(x)==" ") {;boxes(x)="o";}
                                else if(boxes(x)!=" "){ int x=5;
                                    if(boxes(x)==" ") {;boxes(x)="o";}
                                    else if(boxes(x)!=" "){ int x=6;
                                        if(boxes(x)==" ") {;boxes(x)="o";}
                                        else if(boxes(x)!=" "){  int x=7;       
                                            if(boxes(x)==" ") {;boxes(x)="o";}
                                            else if(boxes(x)!=" "){  int x=8;
                                                if(boxes(x)==" ") {;boxes(x)="o";}
                                                else if(boxes(x)!=" "){std::cout<<" ";
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        
    }


    else if(AI_is_smart==false&&game_over==true){std::cout<<" ";
    }
}
           
//Player moves when vs Program 
void player_move(){
    if(game_over==false){std::cin>>move;
        if (boxes(move)=="o"){std::cout<<"Don't Cheat! You lose a turn...n";}
        else if (boxes(move)=="x"){std::cout<<"You already own that square! Please try again...n";
            std::cout<<"Your Turn (x) ...n";
            std::cin>>move;   
            if (boxes(move)=="x"){std::cout<<"Don't delay the game! You lose a turn...n";}
            else if (boxes(move)=="o"){std::cout<<"Don't Cheat! You lose a turn...n";}
            else {boxes(move)="x";}
        }
        else {boxes(move)="x";}
    }
}
            
//Player 1 moves in pvp
void player1_move(){
    if(game_over==false){
        std::cin>>move;
        if (boxes(move)=="o"){std::cout<<"Don't Cheat! Player x loses a turn...n";}
        else if (boxes(move)=="x"){std::cout<<"You already own that square! Player x please try again...n";
            std::cout<<"Player 1's turn (x)...n";
            std::cin>>move;   
            if (boxes(move)=="x") {std::cout<<"Don't delay the game! Player x loses a turn...n";}
            else if (boxes(move)=="o") {std::cout<<"Don't Cheat! Player x loses a turn...n";}
            else {boxes(move)="x";}
        }
        else {boxes(move)="x";}
    }
}
    
//Player 2 moves in pvp
void player2_move(){
    if(game_over==false){
        std::cin>>move;
        if (boxes(move)=="x"){std::cout<<"Don't Cheat! Player o loses a turn...n";}
        else if (boxes(move)=="o"){std::cout<<"You already own that square! Player o please try again...n";
            std::cout<<"Player 1's turn (o)...n";
            std::cin>>move;   
            if (boxes(move)=="o") {std::cout<<"Don't delay the game! Player o loses a turn...n";}
            else if (boxes(move)=="x") {std::cout<<"Don't Cheat! Player o loses a turn...n";}
            else {boxes(move)="o";}
        }
        else {boxes(move)="o";}
    }
}

int main() {
    std::cout<<"Tic-tac-toen";
    std::cout<<" ___ ___ ___ "<<'n';
    std::cout<<"| 0 | 1 | 2 |"<<'n';
    std::cout<<" ___ ___ ___ "<<'n';
    std::cout<<"| 3 | 4 | 5 |"<<'n';
    std::cout<<" ___ ___ ___ "<<'n';
    std::cout<<"| 6 | 7 | 8 |"<<'n';
    std::cout<<" ___ ___ ___ "<<"nn";
    std::cout<<"Player vs Program (Player moves first)... Press 1.n";
    std::cout<<"Player vs Program (Program moves first)... Press 2.n";
    std::cout<<"Player vs Player... Press 3.n";
    std::cin>>order;

    /**********************************
    1. Player vs Program (Player moves first) 
    **********************************/
    if (order==1) {std::cout<<"nSelected: Player vs Program (Player moves first)...n";
    
        for(game_over=false; game_over==false&&turn<8;){ 
            
            if(game_over==false){
            std::cout<<"nTurn #"<<turn<<"n";
        
            std::cout<<"Player's turn (x)...n";
            player_move();
            gameboard();
            game_over_conditions();
        
            AI_type();
            program_move_random();
            gameboard();
            game_over_conditions();
        
            std::cout<<"n_______________________nn";
            turn++;}
        }
    }
        
    /**********************************
    2. Player vs Program (Program moves first)
    **********************************/
    else if (order==2) {std::cout<<"Selected: Player vs Program (Program moves first)...nn";

        for(game_over=false; game_over==false&&turn<8;){ 
            
            if(game_over==false){
            std::cout<<"nTurn #"<<turn<<"n";
        
            AI_type();
            program_move_random();
            gameboard();
            game_over_conditions();
        
            std::cout<<"Player's turn (x)...n";
            player_move();
            gameboard();
            game_over_conditions();

            std::cout<<"n_______________________nn";
            turn++;}
        }
    }
        
    /**********************************
    3. Player vs Player
    **********************************/
    else if (order==3) {std::cout<<"Selected: Player vs Player...nn";
        for(game_over=false; game_over==false&&turn<8;){
            if(game_over==false){
            
            std::cout<<"Player 1's turn (x) ...n";
            player1_move();
            gameboard();
            game_over_conditions();
        
            std::cout<<"Player 2's turn (x) ...n";
            player2_move();
            gameboard();
            game_over_conditions();}
        }
    }
}
```