Better way for making an array for Connect 4? - c

I am having more trouble with these array as it seems I have limited understanding on building and utilizing an array. How should I pass a specific cell to an array? In this example I am trying to pass the chip value of a specific column that occupies row 8. How would you manipulate the value of a 2D array cell based on the location of the cell as shown below?
Below is the link to a compiler I have been using online, I also used a minimalist portion of the code to illustrate my overall goal. I am trying to push the
https://onlinegdb.com/mB1kiOtOBM
int row;
int col;
int array [row][col];
int const chip = 1;
while(left == 1)
{
row = 8;
for(int col = 8; 8 > col > 0; col ++)
{
chip = array [row][col];
}
}

How should I pass a specific cell to an array? In this example I am trying to pass the chip value of a specific column that occupies row 8.
If I'm understanding your question correctly, in this case the verb you want is assign instead of pass.
We usually say pass a thing to another when it comes to function calls. Say you define your function foo(int x) and you call it foo(2). You're passing the value 2 to the function.
So if you're trying to change one value in the array, you want something like array[7][0] = chip. This sets the first cell of 8th row to whatever value that chip holds. Note that arrays are 0-indexed in C.

Related

Fnd max float number in 2d array (whitout knowing the size of it) on C

I am trying to find a solution in a C programming
I have a 2d array, but i dont know its size
I can only access the array with a array view of [11][11]
The main idea is to find the peak of a mountain (max element)
So basically my 2d array is a map where each index is a float number, corresponding to the height of the mountain
I know i am out of the map when my float number is -1
That is what i was thinking to do, but i cant put it onto a code in a proper way
My solution is based on brute force approach
my basic idea was getting one 2d array formed by myview
what would give me a [11][11] array
then get a max value on that [11][11] array and store it.
next step i would generate another myview array using a loop.
i would apply same process here, to get a max value on that new array
then i would compare myfirst Max value with that second Max value
the value who have the biggest value would be stored on my max variable, with the location as well (point x and point y).
then i would run a loop again to create another myview array, and so on.
My plan to run on all possible [11][11]arrays is:
starting from running a loop for all the columns, but always keeping the rows 1-11
i know there is no more columns when all the values inside of my array [11][11] are -1.0
so when i find that array i would jump for next section of rows (12-23) for example
and again run for all columns.
i also could set a max value per set of a row (so at set of rows 1-11 the max value (peak) is 197.15 , then at set of rows 12-23 the max value (peak) is 397.15, for example)
i know will not be more rows when in my first set of columns i get the values inside of my array [11][11] -1.0000
so i would just need to get my biggest value on all set of rows, then i would get my solution.
You mean you have a two-dimensional array with two lines of eleven elements each, as you would get if you ran int array[11][11];? Then you can have two nested loops, one for (int i = 0; i < 2; i++) and for (int j = 0; j < 11; j++) nested inside each other to loop over the individual elements of the two lines. You have a buffer variable that holds the maximum so far. In your loop you compare each element you're looping over against the buffer variable, and the new element becomes the new buffer variable if it's bigger than the existing one:
void main(void) {
int array[11][11];
int buffer = 0;
for (int i = 0; i < 2; i++) {
for (int j = 0; 11 < 2; j++) {
if (array[i][j] > buffer) {buffer = array[i][j];}
}
}
}

Last cell in array that modified

Is there any way to find out which cell in an array is the last cell that modified? (e.g. change its value)
In any compile-based languages.
For example assume we defined array1 with n cells. Now value of array1[2] changed to 1, after that value of array1[7] will change to 1, I want a solution to find out the 7th cell as last cell that modified.
Just don't access the array directly, write to it in a function/method and keep track as it changes. In C# there are properties/indexers which wrap the call X = 2 in a method for you.
Neither of these seem like particularly great solutions, but they will both accomplish what you want in C++:
int indexToChange, lastIndexChanged;
int array1 [10];
indexToChange = 2;
array1[indexToChange] = 1;
lastIndexChanged = indexToChange;
indexToChange = 7;
array1[indexToChange] = 1;
lastIndexChanged = indexToChange;
Then at any point array1[lastIndexChanged] would be the most recently updated. But this is annoying since it requires 3 commands for every array update. Instead, you could wrap it into a function:
void changeArray(int array[], int length, int indexToChange, int newVal){
array[indexToChange] = newVal;
lastIndexChanged=indexToChange;
}
Which would then require all your array updates to look like this (assuming lastIndexChanged was declared globally and array1 has size 10):
changeArray(array1, 10, 2, 1);
changeArray(array1, 10, 7, 1);
Then, to update the most recently changed element to 0:
changeArray(array1, 10, lastIndexChanged, 0);
However, both of these examples will only work for a single array in a program, which does not seem particularly useful to me.
Only other idea I have involves creating an array of tuples (or something similar) and using the 2nd element of the tuple as one of the following:
A bool flag indicating if the element was the last one changed
An int flag indicating the "age" of the element
However, both of those methods require accessing every element of the array for every single array update.
For (1), with each update you would have to make sure to find the previously last updated element and set it's flag to false as you set the flag of the element you were updating to true.
For (2), with each array update you would increment the "age" flag of every element, but set the "age" of the element you updated to 0. This has the advantage of enabling you to also find the nth last updated element.
In either case, if your original array is an array of ints, you may be able to implement this with a 2-dimensional array with two rows. So, if array1 is size n, you would have int array1[2][n], giving you an array like this (for n=4, assuming all cells initialized to 0):
[0][0][0][0]
[0][0][0][0]
where you would use the top row for your values and your bottom row for flags. Thus, an array update would look something like this:
For "bool" flags (just using 0 and 1 to simulate a bool value):
array1[0][2] = 1; //set value of element 2 to 1
array1[1][getLastUpdated()]=false; //resetting the previous "last updated" flag
array1[1][2] = true;
For "age" flags:
array1[0][2] = 1; //set value of element 2 to 1
for (int i=0; i<array1Length; i++){
array1[1][i]++; //increment ages of every element
}
array1[1][2] = 0; //reset age of the element you just updated
Then, to find the most recently updated element, you would search for array[1][n] to be true or 0, respectively.

C - How can I sort and print an array in a method but have the prior unsorted array not be affected

This is for a Deal or No Deal game.
So in my main function I'm calling my casesort method as such:
casesort(cases);
My method looks like this, I already realize it's not the most efficient sort but I'm going with what I know:
void casesort(float cases[10])
{
int i;
int j;
float tmp;
float zero = 0.00;
for (i = 0; i < 10; i++)
{
for (j = 0; j < 10; j++)
{
if (cases[i] < cases[j])
{
tmp = cases[i];
cases[i] = cases[j];
cases[j] = tmp;
}
}
}
//Print out box money amounts
printf("\n\nHidden Amounts: ");
for (i = 0; i < 10; i++)
{
if (cases[i] != zero)
printf("[$%.2f] ", cases[i]);
}
}
So when I get back to my main it turns out the array is sorted. I thought void would prevent the method returning a sorted array. I need to print out actual case numbers, I do this by just skipping over any case that is populated with a 0.00. But after the first round of case picks I get "5, 6, 7, 8, 9, 10" printing out back in my MAIN. I need it to print the cases according to what has been picked. I feel like it's a simple fix, its just that my knowledge of the specifics of C is still growing. Any ideas?
Return type void has nothing to do with prevention of array from being sorted. It just says that function does not return anything.
You see that the passed array itself is affected because an array decays to a pointer when passed to a function. Make a copy of the array and then pass it. That way you have the original list.
In C, arrays are passed by reference. i.e. they're passed as pointer to the first element. So when you pass cases into your function, you're actually giving it the original array to modify. Try creating a copy and sorting the copy rather than the actual array. Creating a copy wouldn't be bad as you have only 10 floats.
Instead of rolling your own sort, consider using qsort() or std::sort() if you are actually using c++
There are 2 obvious solutions. 1) Make a copy of the array and sort the copy (easy, waste some memory, likely not a problem these days). 2) Create a parallel array of integers and perform an index sort, i.e., instead of sorting thing original, you sort the index and then dereference the array using the index when you want the sorted version, otherwise by the raw unsorted array.
Well, make a local copy of you input and sort it. Something like this:
void casesort(float cases[10])
{
float localCases[10];
memcopy(localCases, cases, sizeof(cases));
...
Then use localCases to do your sorting.
If you don't want the array contents to be affected, then you'll have to create a copy of the array and pass that to your sorting routine (or create the copy within the routine itself).
Arrays Are Different™ in C; see my answer here for a more detailed explanation.

Copying a subset of an array into another array / array slicing in C

In C, is there any built-in array slicing mechanism?
Like in Matlab for example,
A(1:4)
would produce =
1 1 1 1
How can I achieve this in C?
I tried looking, but the closest I could find is this: http://cboard.cprogramming.com/c-programming/95772-how-do-array-subsets.html
subsetArray = &bigArray[someIndex]
But this does not exactly return the sliced array, instead pointer to the first element of the sliced array...
Many thanks
Doing that in std C is not possible. You have to do it yourself.
If you have a string, you can use string.h library who takes care of that, but for integers there's no library that I know.
Besides that, after having what you have, the point from where you want to start your subset, is actually easy to implement.
Assuming you know the size of your 'main' array and that is an integer array, you can do this:
subset = malloc((arraySize-i)*sizeof(int)); //Where i is the place you want to start your subset.
for(j=i;j<arraySize;j++)
subset[j] = originalArray[j];
Hope this helps.
Thanks everyone for pointing out that there is no such built-in mechanism in C.
I tried using what #Afonso Tsukamoto suggested but I realized I needed a solution for multi-dimensional array. So I ended up writing my own function. I will put it in here in case anyone else is looking for similar answer:
void GetSlicedMultiArray4Col(int A[][4], int mrow, int mcol, int B[1][4], int sliced_mrow)
{
int row, col;
sliced_mrow = sliced_mrow - 1; //cause in C, index starts from 0
for(row=0; row < mrow; row++)
{
for (col=0; col < mcol; col++)
{
if (row==sliced_mrow) B[0][col]=A[row][col];
}
}
}
So A is my input (original array) and B is my output (the sliced array).
I call the function like this:
GetSlicedMultiArray4Col(A, A_rows, A_cols, B, target_row);
For example:
int A[][4] = {{1,2,3,4},{1,1,1,1},{3,3,3,3}};
int A_rows = 3;
int A_cols = 4;
int B[1][4]; //my subset
int target_row = 1;
GetSlicedMultiArray4Col(A, A_rows, A_cols, B, target_row);
This will produce a result (multidimensional array B[1][4]) that in Matlab is equal to the result of A(target_row,1:4).
I am new to C so please correct me if I'm wrong or if this code can be made better... thanks again :)
In C,as far as I know, array name is just regarded as a const pointer. So you never know the size of the subset. And also you can assign a arrary to a new address. So you can simply use a pointer instead. But you should manage the size of the subset yourself.

passing a column out of a matrix to a function in c

I want to pass a particular column of the matrix that I have in my program to a function.
If I use the call <function_name>(<matrix_name>[][<index>]); as the call
then I get the error
error: expected expression before ‘]’
token
So please help me in finding the suitable way
Thanks
The syntax you used doesn't exist.
Matrices are stored in memory by row (or better, by the second dimension, to which you give the semantics of rows), so you cannot natively. You could copy all your column elements in a vector (a single dimension array) and pass it.
If you need to work only by column (and never by row) you could change the semantics you give to the first and to the second dimension: think of your matrix as matrix[row][column] instead of matrix[column][row].
Otherwise, if you need to do this often, look for a better data structure, instead of a simple array.
Because of the way addressing works, you can't simply pass the 'column' since, the 'column' values are actually stored in your 'rows'. This is why your compiler will not allow you to pass no value in your 'row' reference, ie: '[]'.
An easy solution would be to pass the entire matrix, and pass the column index as a seperate integer, and the number of rows. Your function can then iterate through every row to access all members of that column.
ie:
functionName(matrixType** matrixRef, int colIndex, int numRows)
{
for(int i=0; i< numRows; ++i)
matrixType value = matrixRef[i][colIndex]; //Do something
}
You are going to have to reformat the data. The column is not contiguous in memory. If for example you have an array:
arr[5][4]
Then trying to pass a 'column' would be like trying to pass every 5th element in the array. Think of it as one giant array.
There's a few things you need to keep in mind about C here.
I'm assuming your matrix is stored as a 2D array, like this:
float mat[4][4];
What you need to remember is that this is just 16 floats stored in memory consecutively; the fact that you can access mat[3][2] is just a shortcut that the compiler gives you. Unfortunately, it doesn't actually pass any of that metadata on to other function calls. Accessing mat[3][2] is actually a shortcut for:
mat[ (3*4 + 2) ]
When you pass this into a function, you need to specify the bounds of the matrix you're passing in, and then the column number:
void do_processing(float* mat, int columns, int rows, int column_idx)
Inside this function, you'll have to calculate the specific entries yourself, using the formula:
mat[ (column_idx * rows) + row_idx ]

Resources