C - How to find a winner of a norts and crosses - c

I am currently making a tic tac toe game using C. I am making a function Check(char sign) that i can call after each player makes a move which will check for a winner. I need help as the tic tac toe game can be played on different sized boards (3 up to 12).
I made the following code which can be used to find the winner of a 3 x 3 game:
**//For Rows**
for(i=0; i<3; i++)/***sign is the player symbol e.g. 'X'OR'O'***/
if(board[i][0] == sign && board[i][0] == board[i][1] && board[i][1] == `
board[i][2]){`
printf("the winner is %c", sign );
return 1;
}
**//For Columns**
for(i=0; i<3; i++)/***sign is the player symbol e.g. 'X'OR'O'***/
if(board[0][i] == sign && board[0][i] == board[1][i] && board[1][i] ==
board[2][i]){
printf("the winner is %c", sign );
return 1;
}
**//For Diagnal 1 \**
if(board[0][0] == sign && board[0][0] == board[1][1] && board[1][1] ==
board[2][2]){
printf("the winner is %c", sign );
return 1;
}
**//For Diagnal 2 /**
if(board[0][2] == sign && board[0][2] == board[1][1] && board[1][1] ==
board[2][0]){
printf("the winner is %c", sign );
return 1;
}
However as I mentioned my game can be played on different board sizes which is chosen by user input at the beginining of the game. This size is stored in a vreriable "int Size". How would I alter the above code to work with any size board?
I know that i could create a list if statements each one containing code for a specific board size but this seems like the incorrect and least efficient way of doing so.
I hope someone can help. Any help will be greatly appreciated.
Thank you.

Note that the if statement for each of your 4 cases could be written using a loop; for example, the first one could be written as:
int win = (board[i][0] == sign); // assume a win until we find out otherwise
// loop over the pairs to compare until we find a mismatch or exhaust them all
for ( int j = 1; (win == 1) && (j < size); j++ )
if ( board[i][j-1] != board[i][j] )
win = 0;
if ( win ) {
printf("the winner is %c", board[i][0] );
return 1;
}
Change which 2 elements of board are being compared, and the initialization of win, for each of the other 3 cases.

You could have three function, one that iterates through rows, one that iterates through cols, and one that iterates through the diagonal pair.
/* If the sign player won, return 1. Else return 0. */
int rowWinnerCheck(int n, char sign, char board[n][n]){
for(int i = 0; i < n; i++){
int sameSign = 1;
for(int j = 0; j < n; j++){
char letter = board[i][j];
if(letter != sign){
sameSign = 0;
}
}
if(sameSign == 1){
return 1;
}
}
return 0;
}
colWinnerCheck would be similar to how rowWinnerCheck is implemented.
Verifying if a player won diagonally is also similar.
/* This function checks if a player won diagonally from the top-left to bottom-right*/
int diagonalWinnerCheck(int n, char sign, char board[n][n]){
for(int i = 0; i < n; i++){
int sameSign = 1;
char letter = board[i][i];
if(letter != sign){
return 0;
}
}
return 1;
}
Solution without loops
Here is a possible solution without loops, which I believe scales better for a larger n.
I'll leave the C out for you to complete, and I'll just explain the concept for determining the winner on an n x n board. The code you gave uses loops to compare the contents on the board. This solution doesn't depend on loops as it makes use of a mathematical representation to determine the winner.
Board Representation
We first need to have a representation for the board using a 2D array of integer of size n x n. We will also make everything zero in the board from the start.
int board[n][n];
memset(board, 0, sizeof(board[0][0]) * n * n);
We define the letters that are used, X and O, and assign them to be the constants, 1 and -1 respectively. Note: 1, -1 were choose arbitrarily, but for the solution to work, they need to be some integer k, -k.
We define four more items for the solution. Two integer arrays, one to represent the rows and one for the cols, and two integers for the two diagonals.
int rows[n] = {0};
int cols[n] = {0};
int leftDiag = 0;
int rightDiag = 0;
How it Works
Let's assume a new game was started on a 3x3 board. I play X, and you play O. I make my move on location (2,0). The program first checks the board location at (2,0) and sees if it's zero. If it is, set it to be X, else raise an error since that spot has been played already. The program also adds X to rows[2] and cols[0].
You play O at (1,1). First check if board[1][1] has been already played, if not, set it to be O. Add O to rows[1] and cols[1]. Here is a special case. When you player played O on the diagonal i.e. for a move (a,b) a == b or a == (n-b-1), add O to the appropriate diagonal variable. Since (1,1) belongs to both diagonal, add O to leftDiag and rightDiag.
We alternate turns until one of these conditions are met:
A location i in rows such that rows[i] == n * X. This means X
won by filling the ith row. A location j in rows such that
rows[j] == n * O. This means O won
A location i in cols such that cols[i] == n * X. This means X
won by filling the ith col. A location j in cols such that
cols[j] == n * O. This means O won
leftDiag == n * X or rightDiag == n * X, X won. leftDiag == n * O or rightDiag == n * O, O won.
n*n moves have been made, but the previous conditions were
never met. This mean the game ended in a tie.
Notice that at the end, we don't need to iterate through rows, cols, or diagonals to verify if someone won. If a row, col, or diagonal, sums up throughout the game to be n * Character, then that Character player won. This reduces the complexity of verifying a winner from O(n^2) to O(1). The trade off is just O(n) more space.

Related

Random walk in a 10X10 array

Write a C program that generates a random walk across a 10x10 array. Initially, the array will contain only dot characters. The program must randomly “walk” from element to element, always going up, down, left, or right by one step. The elements visited by the program will be labeled with the letters A through Z, in the order visited.
It doesn't take the walk to an element that has already a letter assigned (blocked element).If all four directions are blocked, the program must terminate.
I wrote the code for the above question but sometimes the output is just blank, it is just showing a black screen.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
char visited = 'A';
char a[10][10];
// assigning value '.' to array elements
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
a[i][j] = '.';
// the initial is set for the player.
int playeri, playerj;
srand(time(0));
// assigning numbers between 0-9
playeri = rand() % 10; playerj = rand() % 10;
a[playeri][playerj] = visited++;
int move;
// now to move the player
while (visited <= 'Z') {
// to generate numbers between 1-4
move = rand() % 4 + 1;
// to move up
if (move == 1) {
if (a[playeri - 1][playerj] == '.' && playeri != 0) {
playeri = playeri - 1;
a[playeri][playerj] = visited++;
}
}
// to move down
else if (move == 2) {
if (a[playeri + 1][playerj] == '.' && playeri != 9) {
playeri = playeri + 1;
a[playeri][playerj] = visited++;
}
}
// to move right
else if (move == 3) {
if (a[playeri][playerj + 1] == '.' && playerj != 9) {
playerj = playerj + 1;
a[playeri][playerj] = visited++;
}
}
// to move left
else if (move == 4) {
if (a[playeri][playerj - 1] == '.' && playerj != 0) {
playerj = playerj - 1;
a[playeri][playerj] = visited++;
}
}
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
printf("%c", a[i][j]);
}
printf("\n");
}
}
My guess is that the program is stuck in an infinte loop, if so, how do I solve this problem?
Your program has undefined behavior if you access array a out of bounds. This can happen when the random direction is impossible because you reached the borders of the 10x10 array. To avoid this change the order of the conditions to check the index first, e.g.
if (playeri != 0 && a[playeri - 1][playerj] == '.') {
In some cases you probably end up in a position that has no adjacent positions with a dot, so there is no way to continue. As visited does not get incremented in this case, your loop will not terminate.
An additional check that there is at least one direction not blocked will fix the endless loop, but is not an optimal solution.
Your implementation that generates a random direction and then checks if this direction is possible may need several attempts when more fields get blocked.
Although it is very unlikely you might even get random numbers that denote blocked ways for a long time.
To implement the requirement to terminate the program when all directions are blocked and to improve the behavior when many directions are blocked, I suggest to change the algorithm.
Proposed algorithm:
check all 4 directions if it is possible to walk, put all possible directions into an array of at most 4 elements and count the possible directions as n. (Example: if up, down and left are possible, the array will contain up, down, left, (invalid). The count will be n = 3.)
if n == 0 (all blocked) terminate loop
get a random number from 0 to n - 1 (Example: 0..2)
select the direction from the array (Example: random number 1 will select down)
move in the selected direction (it has been checked before that it is possible)

Counting number of primes within a given range of long int using C

Well, there are lots of such questions available in SO as well as other forums. However, none of these helped.
I wrote a program in "C" to find number of primes within a range. The range i in long int. I am using Sieve of Eratosthenes" algorithm. I am using an array of long ints to store all the numbers from 1 till the limit. I could not think of a better approach to achieve without using an array. The code works fine, till 10000000. But after that, it runs out of memory and exits. Below is my code.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef unsigned long uint_32;
int main() {
uint_32 i, N, *list, cross=0, j=4, k, primes_cnt = 0;
clock_t start, end;
double exec_time;
system("cls");
printf("Enter N\n");
scanf("%lu", &N);
list = (uint_32 *) malloc( (N+1) * sizeof(uint_32));
start = clock();
for(i=0; i<=N+1; i++) {
list[i] = i;
}
for(i=0; cross<=N/2; i++) {
if(i == 0)
cross = 2;
else if(i == 1)
cross = 3;
else {
for(j=cross+1; j<=N; j++) {
if(list[j] != 0){
cross = list[j];
break;
}
}
}
for(k=cross*2; k<=N; k+=cross) {
if(k <= N)
list[k] = 0;
}
}
for(i=2; i<=N; i++) {
if(list[i] == 0)
continue;
else
primes_cnt++;
}
printf("%lu", primes_cnt);
end = clock();
exec_time = (double) (end-start);
printf("\n%f", exec_time);
return 0;
}
I am stuck and can't think of a better way to achieve this. Any help will be hugely appreciated. Thanks.
Edit:
My aim is to generate and print all prime numbers below the range. As printing consumed a lot of time, I thought of getting the first step right.
There are other algorithm that does not require you to generate prime number up to N to count number of prime below N. The easiest algorithm to implement is Legendre Prime Counting. The algorithm requires you to generate only sqrt(N) prime to determine the number of prime below N.
The idea behind the algorithm is that
pi(n) = phi(n, sqrt(n)) + pi(sqrt(n)) - 1
where
pi(n) = number of prime below N
phi(n, m) = number of number below N that is not divisible by any prime below m.
That's mean phi(n, sqrt(n)) = number of prime between sqrt(n) to n. For how to calculate the phi, you can go to the following link (Feasible implementation of a Prime Counting Function)
The reason why it is more efficient is because it is easiest to compute phi(n, m) than to compute pi(n). Let say that I want to compute phi(100, 3) means that how many number below or equal to 100 that does not divisible by 2 and 3. You can do as following. phi(100, 3) = 100 - 100/2 - 100/3 + 100/6.
Your code uses about 32 times as much memory as it needs. Note that since you initialized list[i] = i the assignment cross = list[j] can be replaced with cross = j, making it possible to replace list with a bit vector.
However, this is not enough to bring the range to 264, because your implementation would require 261 bytes (2 exbibytes) of memory, so you need to optimize some more.
The next thing to notice is that you do not need to go up to N/2 when "crossing" the numbers: √N is sufficient (you should be able to prove this by thinking about the result of dividing a composite number by its divisors above √N). This brings memory requirements within your reach, because your "crossing" primes would fit in about 4 GB of memory.
Once you have an array of crossing primes, you can build a partial sieve for any range without keeping in memory all ranges that precede it. This is called the Segmented sieve. You can find details on it, along with a simple implementation, on the page of primesieve generator. Another advantage of this approach is that you can parallelize it, bringing the time down even further.
You can tweak the algorithm a bit to calculate the prime numbers in chunks.
Load a part of the array (as much as fits the memory), and in addition hold a list of all known prime numbers.
Whenever you load a chunk, first go through the already known prime numbers, and similar to the regular sieve, set all non primes as such.
Then, go over the array again, mark whatever you can, and add to the list the new prime numbers found.
When done, you'll have a list containing all your prime numbers.
I could see that the approach you are using is the basic implementation of Eratosthenes, that first stick out all the 2's multiple and then 3's multiple and so on.
But I have a better solution to the question. Actually, there is question on spoj PRINT. Please go through it and do check the constraints it follows. Below is my code snippet for this problem:
#include<stdio.h>
#include<math.h>
#include<cstdlib>
int num[46500] = {0},prime[5000],prime_index = -1;
int main() {
/* First, calculate the prime up-to the sqrt(N) (preferably greater than, but near to
sqrt(N) */
prime[++prime_index] = 2; int i,j,k;
for(i=3; i<216; i += 2) {
if(num[i] == 0) {
prime[++prime_index] = i;
for(j = i*i, k = 2*i; j<=46500; j += k) {
num[j] = 1;
}
}
}
for(; i<=46500; i+= 2) {
if(num[i] == 0) {
prime[++prime_index] = i;
}
}
int t; // Stands for number of test cases
scanf("%i",&t);
while(t--) {
bool arr[1000005] = {0}; int m,n,j,k;
scanf("%i%i",&m,&n);
if(m == 1)
m++;
if(m == 2 && m <= n) {
printf("2\n");
}
int sqt = sqrt(n) + 1;
for(i=0; i<=prime_index; i++) {
if(prime[i] > sqt) {
sqt = i;
break;
}
}
for(; m<=n && m <= prime[prime_index]; m++) {
if(m&1 && num[m] == 0) {
printf("%i\n",m);
}
}
if(m%2 == 0) {
m++;
}
for(i=1; i<=sqt; i++) {
j = (m%prime[i]) ? (m + prime[i] - m%prime[i]) : (m);
for(k=j; k<=n; k += prime[i]) {
arr[k-m] = 1;
}
}
for(i=0; i<=n-m; i += 2) {
if(!arr[i]) {
printf("%i\n",m+i);
}
}
printf("\n");
}
return 0;
}
I hope you got the point:
And, as you mentioned that your program is working fine up-to 10^7 but above it fails, it must be because you must be running out of the memory.
NOTE: I'm sharing my code only for knowledge purpose. Please, don't copy and paste it, until you get the point.

How can I reduce the runtime?

Here is a link to the problem I'm trying to solve: http://acm.timus.ru/problem.aspx?space=1&num=1086
Here is my approach:
#include <stdio.h>
#include <math.h>
int main()
{
int n, i, m, p;
scanf("%d", &n);
for(i = 0; i < n; i++)
{
scanf("%d", &m);
p = find_prime(m);
printf("%d\n", p);
}
return 0;
}
int find_prime(int a)
{
int i, p = 1, t, prime[15000], j;
prime[0] = 2;
for(i = 0; i < a; )
{
if(p == 2)
{
p++;
}else
{
p = p + 1;
}
t = 0;
for(j = 0; prime[j] <= sqrt(p); j++)
{
if(p%prime[j] == 0 && p != 2)
{
t = 1;
break;
}
}
if(t != 1)
{
i++;
prime[i] = p;
}
}
return p;
}
I know the algorithm is fine and it produces the correct answer. But I always get "Time Limit Exceeded". I can't get the runtime download to 2 seconds. It's always equal to 2.031 seconds. I have tried few other approaches, for example, I iterated through all the numbers until I found the mth prime number, I tried skipping the even integers greater than 2 but I still get 2.031 seconds.
What should I do?
Your buffer for prime numbers doesn't need to be a local variable that's recalculated every time.
You can try to memoize by storing the buffer in the global scope and using a global counter to keep track of how many primes you have already calculated until now and which number was the maximum number requested.
If the next number that's requested from you is smaller than the previous maximum, you should fall back to the corresponding pre-calculated number. If the next number is larger than the previous maximum, make it the new maximum - and also try to start calculating from where you last left off.
Remove
if(p == 2)
{
p++;
}else
{
p = p + 1;
}
and replace it with
p++
as I understand it,
the problem is to find the next prime greater that the sum of all the prior input numbers.
That means there are certain expectations.
1) the sum of the prior input numbers is available in find_prime().
2) for simplification, the last found prime number is available in find_prime().
Neither of these expectations are implemented.
Then there is that 60 thousand byte array on the stack in find_prime().
Suggest moving that to a file global position and including a 'static' modifier.
move the prior sum of inputs to a file global location, so it is always available.
for overall speed,
calculate all the primes in the array as a first thing, thereby filling the array with prime values. then
1) add new input to sum,
2) index into array using sum.
3) return value found in array.

Updating my array board game

So I'm creating a game. It has a 5 by 5 board filled with characters a, b and c. I need to create a function where if the board detects the same letter next to each other, it disappears and the emptied cells are replaced with a new set of letters (a,b,c). So a bit like the candy crush game. I also need to display the number of moves that are made before the game ends. Here's where I am so far
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define MAX 10
//creates board and fills in the letters randomly
int board()
{
char grid[MAX][MAX];
char letter[3] = {'a', 'b', 'c'};
int i,j,row,col;
printf("Please enter your grid size: ");
scanf("%d %d", &row, &col);
if(row < 10 && col < 10){
for(i=0; i < MAX; i++){
for(j=0; j < MAX; j++){
grid[i][j] = letter[rand()%3];
}
}
for(i=0; i < MAX; i++){
for(j=0; j < MAX; j++){
printf("%c ", grid[i][j]);
}
printf("\n");
}
}
else{
printf("Board is too big\n");
board();
}
return 0;
}
//the count doesn't quite do what I need it to
int moveCount()
{
char s;
printf("Press s to start: ");
scanf("%c", &s);
if(s == 's' || s == 'S'){
int count;
int max = 10;
for(count=1; count < max; count++)
if(count == max){
-printf("No more moves can be made");
}
else{
printf("Number of moves made: %d\n", count);
}
}
else{
printf("That is not s\n");
moveCount();
}
}
//Trying to check to make sure that n board is always atleast three cells
int inputCheck(){
int n, m;
if(n == 3 || n > 3 && m == 1 || m > 1){
moveCount();
}
}
int main()
{
board();
inputCheck();
}
What's the best way to implement a function that checks if neighbouring cells are the same and then deletes them. I would imagine doing something like if(myArray[0][0] == 'a' && myArray[0][1] == 'a'{do something}...but i don't know if that's the best way or how I would loop that. Also how to correctly implement a count that displays the move made?
I realise this code has a lot of flaws but I'm quite new so go easy please. Thanks for any help or a push in the right direction.
A serious bug here:
int n, m;
if(n == 3 || n > 3 && m == 1 || m > 1){
n and m are used uninitialized.
And you need to #include <stdlib.h> for rand()
In answer to your actual question, something like this would work. This is rather sloppy, but it's my 5 min answer. I assume grid is the actual board, which exists only in your board() function at the moment, so I simply added that as a parameter. AKA You're going to have to make it fit your actual game.
inline int clamp (int v, int min, int max) {
return (v < min) ? min: (v > max) ? max: v;
}
void place (char ltr, int x, int y, char grid[MAX][MAX])
{
grid[y][x] = ltr; // TODO: put bounds checking around x & y
for (int i = clamp(y - 1, 0, MAX); i <= clamp (y + 1, 0, MAX); i++) {
for (int j = clamp(x - 1, 0, MAX); j <= clamp(x + 1, 0, MAX); j++) {
if (i != y || j != x && grid[i][j] == ltr) {
grid[i][j] = '\0'; // TODO: replace null char with desired one.
}
}
}
}
The board function is set up just fine.
As the previous answers said parameters are the best way to check a value if you are going to check them within a different function, if you wish to check them within your function a simple if command would do the trick.
I would not pass an entire array as a parameter, instead I would use a pointer to that specific cell. Then, upon a person choosing a cell they are given a memory address that you could then compare the information stored inside that memory address with the other they are comparing.
Quick Pointer Lesson
- * is used to create a pointer. For instance, char *ch = array; would point to the memory address of the entire array. And then through more research you will be able to go to a specific memory address in a 2-D array, such as your board, see what is at that location and compare it to the contents contained in another memory address within your 2-D array.
Why would you want to to this?
Since this is not Java, we can about memory management in C and using an entire array as a parameter is the easy but more memory costly way of doing it. Plus, pointers are a fundamental element within most programming languages and knowing them well will make you a much better programmer.
Happy Travels!!
Also this will also be easier to go through your board to say, this person chose this address at array[3][2], there are only four memory address they would be choosing from at that point. Which ever way they choose to go, the memory address will be there and you will be able to compare both with minimal system usage and a quick response.

function to perform bubble sort in C providing unstable results

I am participating in Harvard's opencourse ware and attempting the homework questions. I wrote (or tried to) write a program in C to sort an array using bubble sort implementation. After I finished it, I tested it with an array of size 5, then 6 then 3 etc. All worked. then, I tried to test it with an array of size 11, and then that's when it started bugging out. The program was written to stop getting numbers for the array after it hits the array size entered by the user. But, when I tested it with array size 11 it would continuously try to get more values from the user, past the size declared. It did that to me consistently for a couple days, then the third day I tried to initialize the array size variable to 0, then all of a sudden it would continue to have the same issues with an array size of 4 or more. I un-did the initialization and it continues to do the same thing for an array size of over 4. I cant figure out why the program would work for some array sizes and not others. I used main to get the array size and values from the keyboard, then I passed it to a function I wrote called sort. Note that this is not homework or anything I need to get credit, It is solely for learning. Any comments will be very much appreciated. Thanks.
/****************************************************************************
* helpers.c
*
* Computer Science 50
* Problem Set 3
*
* Helper functions for Problem Set 3.
***************************************************************************/
#include <cs50.h>
#include <stdio.h>
#include "helpers.h"
void
sort(int values[], int n);
int main(){
printf("Please enter the size of the array \n");
int num = GetInt();
int mystack[num];
for (int z=0; z < num; z++){
mystack[z] = GetInt();
}
sort(mystack, num);
}
/*
* Sorts array of n values.
*/
void
sort(int values[], int n)
{
// this is a bubble sort implementation
bool swapped = false; // initialize variable to check if swap was made
for (int i=0; i < (n-1);){ // loops through all array values
if (values[i + 1] > values [i]){ // checks the neighbor to see if it's bigger
i++; // if bigger do nothing except to move to the next value in the array
}
else{ // if neighbor is not bigger then out of order and needs sorting
int temp = values[i]; // store current array value in temp variable for swapping purposes
values[i] = values[i+1]; //swap with neighbor
values[i+1] = temp; // swap neighbor to current array value
swapped = true; // keep track that swap was made
i++;
}
// if we are at the end of array and swap was made then go back to beginning
// and start process again.
if((i == (n-1) && (swapped == true))){
i = 0;
swapped = false;
}
// if we are at the end and swap was not made then array must be in order so print it
if((i == (n-1) && (swapped == false))){
for (int y =0; y < n; y++){
printf("%d", values[y]);
}
// exit program
break;
}
} // end for
// return;
}
You can easily use 2 nested for loops :
int i, j, temp ;
for ( i = 0 ; i < n - 1 ; i++ )
{
for ( j = 0 ; j <= n - 2 - i ; j++ )
{
if ( arr[j] > arr[j + 1] )
{
temp = arr[j] ;
arr[j] = arr[j + 1] ;
arr[j + 1] = temp ;
}
}
}
also you should now it's a c++ code not a c, because c doesn't have something like :
int mystack[num];
and you should enter a number when you're creating an array and you can't use a variable (like "int num" in your code). This is in C, but in C++ you're doing right.
The first thing to do when debugging a problem like this is ensure that the computer is seeing the data you think it should be seeing. You do that by printing out the data as it is entered. You're having trouble with the inputs; print out what the computer is seeing:
static void dump_array(FILE *fp, const char *tag, const int *array, int size)
{
fprintf(fp, "Array %s (%d items)\n", tag, size);
for (int i = 0; i < size; i++)
fprintf(fp, " %d: %d\n", i, array[i]);
}
int main(void)
{
printf("Please enter the size of the array \n");
int num = GetInt();
printf("num = %d\n", num);
int mystack[num];
for (int z = 0; z < num; z++)
{
mystack[z] = GetInt();
printf("%d: %d\n", z, mystack[z]);
}
dump_array(stdout, "Before", mystack, num);
sort(mystack, num);
dump_array(stdout, "After", mystack, num);
}
This will give you direct indications of what is being entered as it is entered, which will probably help you recognize what is going wrong. Printing out inputs is a very basic debugging technique.
Also, stylistically, having a function that should be called sort_array_and_print() suggests that you do not have the correct division of labour; the sort code should sort, and a separate function (like the dump_array() function I showed) should be used for printing an array.
As it turns out the reason why it was doing this is because when comparing an array's neighbor to itself as in:
if (values[i + 1] > values [i])
The fact that I was just checking that it is greater than, without checking if it is '=' then it was causing it to behave undesirably. So if the array is for example [1, 1, 5, 2, 6, 8] then by 1 being next to a 1, my program did not account for this behavior and acted the way it did.

Resources