2D Array item swap randomly
I have an enum:
public enum Player
{
X, O, NOBODY
}
And I have this array filled with player items randomly:
Player [size][size] p;
Example matrix:
[ X, NOBODY, NOBODY ]
[ NOBODY, O, O ]
[ X, X, NOBODY ]
I would like to swap an X or O element with a NOBODY element randomly, how can I do that?
Example:
[ NOBODY, NOBODY, NOBODY ]
[ NOBODY, O, O ]
[ X, X, X ]
1 answer

One straightforward approach would be to select a random X/O cell as well as a random NOBODY cell, and then swap their values:
// method inside class containing the array public void swapValues() { Random rand = new Random(); int xoPos; int nobodyPos; do { xoPos = rand.nextInt(size*size); Player p = p[xoPos / size][xoPos % size]; } while (Player.NOBODY.equals(p)); do { nobodyPos = rand.nextInt(size*size); Player p = p[nobodyPos / size][nobodyPos % size]; } while (!Player.NOBODY.equals(p)); p[nobodyPos / size][nobodyPos % size] = p[xoPos / size][xoPos % size]; p[xoPos / size][xoPos % size] = Player.NOBODY; }
The strategy here is to generate a single random number between 0 and one minus the total number of cells in the 2D board. Then, we use integer division and modulus to figure out to what 2D coordinates that single value corresponds.
See also questions close to this topic

How to get spring context or bean statically in tests?
I know i can
@Autowire
spring context or any bean in my test classes. But is there any way to get the currently used context statically?@SpringBootTest class MyTest { @Autowire var applicationContext: ApplicationContext? // that's NOT what i want @Test fun myTest() { val result = HelperClass.staticFunction() } }
and then:
class HelperClass { static public MyObject staticFunction( { return Some_spring_or_junit_static_class. getCurrentSpringContextOrBean(nameOfBean) } }
spring caches its contexs while running multiple tests. but is there any way to actually get the one currently used statically?

View and save avif image and save in internal storage
Is it possible to show avif images in android app? And also save it in the storage.
Please help me

Print an array in tester class
I am trying to return the array of students in a tester class for the Course class but I keep getting a .class expected error. I've tried to do
students[].TestCourse
but that doesn't work either.public class Course { private String courseName; private String[] students = new String[4]; private int numberOfStudents; public Course(String courseName) { this.courseName = courseName; } public void addStudent(String student) { if (numberOfStudents == students.length) { String [] copy = new String [students.length*2]; System.arraycopy(students,0,copy,0,students.length); students = copy; } students[numberOfStudents] = student; numberOfStudents++; } public String[] getStudents() { return students; } public void dropStudent(String student) { for (int i=0;i<students.length;i++) { if (students[i]==student) { students[i] = null; } for (i=i;i<students.length1;i++) { students[i] = students[i+1]; } } } } public class TestCourse { public static void main() { Course compScience = new Course("Computer Science"); compScience.addStudent("Jack"); compScience.addStudent("Dean"); compScience.addStudent("Leon"); compScience.dropStudent("Dean"); System.out.println("The students currently in this course are "+ students[]); } }

Deleting a row from an array
I'm working on an assignment in which an array called
lifeforms
will be created with 4 columns calledxvalues
(x),yvalues
(y) ,colours
(c) respectively and the fourth is used elsewhere in the original program.I want that if the x and y values of two rows coincide, then based on their color code (c), one of them would be deleted from the main
lifeforms
array (a "0" c value beats "1", a "1" c value beats "2" and a "2" c value beats "0").The original array looks like:
[[12 15 2 0] [65 23 0 0] [24 66 2 0] [65 23 1 0] [24 66 0 0]]
The problem is that when I try to run the following program I do not get the required array at the end. The expected output array would look like:
[[12 15 2 0] [65 23 0 0] [24 66 2 0]]
I have given an extract from the main program below (please note that the given array is just an example array. In the main program the array size could include up to 500+ rows, each column with random values! So please answer in accordance with that!)
import numpy as np #Array lifeforms = np.array([[12,15,2,0],[65,23,0,0],[24,66,2,0],[65,23,1,0],[24,66,0,0]]) #Original Array print(lifeforms) #Lists to store x, y and c values xvalues = [] yvalues = [] colours = [] #Any removed row is added into this list removed = [] #Code to delete a row for l1 in lifeforms: for l2 in lifeforms: if l1[0] == l2[0]: if l2[1] == l2[1]: if l1[2] == 1 and l2[2] == 0: removed.append(l1) if l1[2] == 0 and l2[2] == 2: removed.append(l1) if l1[2] == 2 and l2[2] == 1: removed.append(l1) for i in removed: lifeforms = np.delete(lifeforms,i,axis=0) for l in lifeforms: xvalues.append(l[0]) yvalues.append(l[1]) colours.append(l[2]) #Update the original Array for i in removed: print(removed) print() print("x\n", xvalues) print("y\n", yvalues) print("colours\n", colours) print() #Updated Array print(lifeforms)

Incrementing value with a ForEach loop to apply on each element
looking for help with arrays and increments.
I have a function which applies the same style to each new element in an array as you can see below.
function SnakeBodyLeft(){ StorePositions.forEach(BodySnake => { BodySnake.style.gridRowStart = (Initial_y + y); BodySnake.style.gridColumnStart = (Initial_x + x)+1 ; }); }; // this results in StorePositions[0] = BodySnake.style.gridColumnStart = (Initial_x + x)+1 StorePositions[1] = BodySnake.style.gridColumnStart = (Initial_x + x)+1 StorePositions[2] = BodySnake.style.gridColumnStart = (Initial_x + x)+1 And so on...
I want to write a function that does what is shown above , but increments the value +1 for Each new element and keep the initial value for the first elements. The result would be somethink like :
StorePositions[0] = BodySnake.style.gridColumnStart = (Initial_x + x)+1 StorePositions[1] = BodySnake.style.gridColumnStart = (Initial_x + x)+2 StorePositions[2] = BodySnake.style.gridColumnStart = (Initial_x + x)+3 StorePositions[3] = BodySnake.style.gridColumnStart = (Initial_x + x)+4 And so on....
I have tried to make 1 a variable called i and increment it. But when I do this , the increment of i is applied to all elements in the array and not just the new elements.
let i = 1++; function SnakeBodyLeft(){ StorePositions.forEach(BodySnake=> { BodySnake.style.gridRowStart = (Initial_y + y); BodySnake.style.gridColumnStart = (Initial_x + x) + i ; }); }; //this results in the incremented value being applied to all elements , not just the new ones . StorePositions[0] = BodySnake.style.gridColumnStart = (Initial_x + x)+1 StorePositions[1] = BodySnake.style.gridColumnStart = (Initial_x + x)+1 StorePositions[2] = BodySnake.style.gridColumnStart = (Initial_x + x)+1 or StorePositions[0] = BodySnake.style.gridColumnStart = (Initial_x + x)+2 StorePositions[1] = BodySnake.style.gridColumnStart = (Initial_x + x)+2 StorePositions[2] = BodySnake.style.gridColumnStart = (Initial_x + x)+2
Basically , as the index grows(0,1,2,3...) , so should the value i in each new element in the index.(0,1,2,3...).
But Iam kinda stuck ! Anyone can help ?

How to get the length of a variable size array of structs?
I'm breaking my head trying to sort out this problem, and I have not been able to sort it out. Given I have a struct:
struct person { String name, String city, int age }
I am reading a list of people from a certain file provided externally, and populating an array of this struct. This is done via a function, lets say
person * readFromFile(filename);
This function has the logic to read the file, create a variable size array of structs (adapted to the number of persons in the file), and return said array.
However, when I try to assign that outcome to a pointer, I'm not getting the elements of the array:
... person * myPeople; myPeople = readFromFile("/people.txt"); int n= ;// different things Ive tried here Serial.println("n is" + n); for(int i=0; i<n; i++) { Serial.println(myPeople.name + " (" + String(myPeople.age) + "), "+myPeople.city }
I've tried several things to get the number of elements once the array is populated after researching how to do it, to know:
int n = sizeof(myPeople)/sizeof(myPeople[0]); int n = sizeof myPeople / sizeof *myPeople; int n = sizeof(myPeople) / sizeof(person); int n = (&myPeople)[1]  myPeople;
But to no avail: I have 5 elements in the file, but n does never show the expected value (and of course the for loop breaks).
Can I get some assistance? what am I be doing wrong?
Thanks

Swap an ArrayList in Java
Im trying to generete a method how be able to swap the elements of a arraylist, let me explain with this example:
The ArrayList is the folowing:
input = [[1, 1, 1, 4, 1], [1, 2, 2, 3, 1], [1, 3, 3, 4, 1]]
The output suposed to be the folowing:
First iteration: [[1, 2, 2, 3, 1], [1, 3, 3, 4, 1],[1, 1, 1, 4, 1]]
Secod iteration: [[1, 3, 3, 4, 1], [1, 1, 1, 4, 1], [1, 2, 2, 3, 1]]
Third iteration: [[1, 1, 1, 4, 1], [1, 2, 2, 3, 1], [1, 3, 3, 4, 1]]
The number of maximun Swap is: input.size()*(input.size()1) / 2;
Thanks in advance

C++ Swap the places of 2 letters
My current code
void swapper(char* ptr) { if (*(ptr +1)) { char temp = *ptr; *ptr = *(ptr + 1); *(ptr + 1) = temp; swapper(ptr+1 ); } } int main() { string mytext; printf("Type ur text: \n"); cin >> mytext; char gowno[256]; sprintf(gowno, mytext.c_str()); swapper(gowno); printf("\n%s \n", gowno); main(); }
This should swap the characters of my string, like "string" it should be "tsirgn" But it instead outputs "trings" what am I doing wrong?

Python list swap only working on some iterations
I'm having trouble with a swapping problem in Python  I want to sort a list of integers by iterating through it and swapping any value that is out of place with the value that should be in that place. I know the input will be an unsorted list of consecutive integers starting from 1, e.g. [4, 3, 1, 2]
sorted = [4, 3, 1, 2] swapCount = 0 for i in range(len(sorted)): if sorted[i] != i + 1: print(f"Before swap {i + 1}: {sorted}") sorted[i], sorted[sorted.index(i + 1)] = sorted[sorted.index(i + 1)], sorted[i] swapCount += 1 print(f"After swap {i + 1}: {sorted}") print(swapCount)
# Before swap 1: [4, 3, 1, 2] # After swap 1: [4, 3, 1, 2] # Before swap 2: [4, 3, 1, 2] # After swap 2: [4, 3, 1, 2] # Before swap 3: [4, 3, 1, 2] # After swap 3: [4, 1, 3, 2] # Before swap 4: [4, 1, 3, 2] # After swap 4: [2, 1, 3, 4] # 4
So in my loop, the swap doesn't work (or works in some special cases), while the same syntax works outside a loop:
sorted = [4, 3, 1, 2, 5] print(sorted) sorted[0], sorted[2] = sorted[2], sorted[0] print(sorted)
# [4, 3, 1, 2, 5] # [1, 3, 4, 2, 5]
Can anyone help me understand what's going wrong in the loop?