Convert a coordinate system into a board for a game - language-agnostic

I currently have code that prints out a coordinate system as shown below. The code asks the user to input dimensions and then prints out a coordinate system appropriately. The board below is a 5 x 5.
(0, 0) (1, 0) (2, 0) (3, 0) (4, 0)
(0, 1) (1, 1) (2, 1) (3, 1) (4, 1)
(0, 2) (1, 2) (2, 2) (3, 2) (4, 2)
(0, 3) (1, 3) (2, 3) (3, 3) (4, 3)
(0, 4) (1, 4) (2, 4) (3, 4) (4, 4)
I was wondering if anyone could give me a hand as to how to convert this into a board that looks like this:
X O X O X
O X O X O
X O X O X
O X O X O
X O X O X
So far I've tried making a list of strings and appending it the the coordinate system but haven't quite got the desired outcome. if anyone has any hints they would be much appreciated.

You could try checking if x+y is even, then printing the appropriate string. So, (1,1) would be X, and (1,4) would be O

You could make a count. if count = 0 print X if count = 1 print O and set count back to 0

I would make a BoardElement class, and a BoardElement[][]
class BoardElement {
String value;
BoardElement(String v) { value = v; }
public String toString() { return value; }
}
class Board {
BoardElement[][] board;
Board(int x, int y) { board = new BoardElement[x][y]; }
public String toString() {
StringBuilder sb = new StringBuilder();
for(int x = 0; x < board.length; x++) {
for(int y = 0; y < board[0].length; y++) {
sb.append(board[x][y]).append(" ");
}
sb.append(System.getProperty("line.separator"));
}
return sb.toString();
}
public void set(int x, int y, String v) { board[x][y].value = v; }
}
then to make your system you would go like this
public static void main(String[] args) {
Board b = new Board(5,5);
for(int x = 0; x < 5; x++) {
for(int y = 0; y < 5; y++) {
b.set(x,y,(x+y)%2==0?"X":"O");
}
}
System.out.println(b);
}
Your first system was more like
public static void main(String[] args) {
Board b = new Board(5,5);
for(int x = 0; x < 5; x++) {
for(int y = 0; y < 5; y++) {
b.set(x,y,"(" + x + "," + y + ")");
}
}
System.out.println(b);
}

Related

I want to calculate the occurrences of each number in aray in Dart

i have that needs me to make a function that counts the occurrences of each number in an array [2,5,6,6,8,4,2,5,2] and print it like this
2 -> 3 times
6 -> 2 times and so on
I did it before but it was to count the occurrences of one number not all of them so can anyone help ... Thanks in advance
to update this is the code I used to count the occurrences of one number
int countTwo(List<int> arr, int value) {
int counter = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] == value) {
counter++;
}
}
return counter;
}
void main() {
List<int> arr = [5, 6, 15, 2, 8, 2, 38, 2];
int x = countTwo(arr, 2);
print(x);
}
You can create a set from list to get unique int.
final data = [2, 5, 6, 6, 8, 4, 2, 5, 2];
final dataSet = data.toSet();
int counter(int number) {
final int counter = data.where((element) => element == number).length; //you can use for loop here too
return counter;
}
for (int i = 0; i < dataSet.length; i++) {
print(
"number ${dataSet.elementAt(i)} -> ${counter(dataSet.elementAt(i))} times");
}
And with your method just do
final data = [2, 5, 6, 6, 8, 4, 2, 5, 2];
final dataSet = data.toSet();
for (int i = 0; i < dataSet.length; i++) {
final checkNUmber = dataSet.elementAt(i);
print("number $checkNUmber-> ${countTwo(data, checkNUmber)} times");
}
Result
number 2 -> 3 times
number 5 -> 2 times
number 6 -> 2 times
number 8 -> 1 times
number 4 -> 1 times
I'd use a map to collect the count:
var count = <int, int>{};
for (var n in data) {
count[n] = (count[n] ?? 0) + 1;
}
After that, you have all the individual elements, and the number of times it occurred:
for (var n in count.keys) {
print("$n: ${count[n]} times");
}

C# How to count how many anagrams are in a given string

I have to calculate how many anagrams are in a given word.
I have tried using factorial, permutations and using the posibilities for each letter in the word.
This is what I have done.
static int DoAnagrams(string a, int x)
{
int anagrams = 1;
int result = 0;
x = a.Length;
for (int i = 0; i < x; i++)
{ anagrams *= (x - 1); result += anagrams; anagrams = 1; }
return result;
}
Example: for aabv I have to get 12; for aaab I have to get 4
As already stated in a comment there is a formula for calculating the number of different anagrams
#anagrams = n! / (c_1! * c_2! * ... * c_k!)
where n is the length of the word, k is the number of distinct characters and c_i is the count of how often a specific character occurs.
So first of all, you will need to calculate the faculty
int fac(int n) {
int f = 1;
for (int i = 2; i <=n; i++) f*=i;
return f;
}
and you will also need to count the characters in the word
Dictionary<char, int> countChars(string word){
var r = new Dictionary<char, int>();
foreach (char c in word) {
if (!r.ContainsKey(c)) r[c] = 0;
r[c]++;
}
return r;
}
Then the anagram count can be calculated as follows
int anagrams(string word) {
int ac = fac(word.Length);
var cc = countChars(word);
foreach (int ct in cc.Values)
ac /= fac(ct);
return ac;
}
Answer with Code
This is written in c#, so it may not apply to the language you desire, but you didn't specify a language.
This works by getting every possible permutation of the string, adding every copy found in the list to another list, then removing those copies from the original list. After that, the count of the original list is the amount of unique anagrams a string contains.
private static List<string> anagrams = new List<string>();
static void Main(string[] args)
{
string str = "AAAB";
char[] charArry = str.ToCharArray();
Permute(charArry, 0, str.Count() - 1);
List<string> copyList = new List<string>();
for(int i = 0; i < anagrams.Count - 1; i++)
{
List<string> anagramSublist = anagrams.GetRange(i + 1, anagrams.Count - 1 - i);
var perm = anagrams.ElementAt(i);
if (anagramSublist.Contains(perm))
{
copyList.Add(perm);
}
}
foreach(var copy in copyList)
{
anagrams.Remove(copy);
}
Console.WriteLine(anagrams.Count);
Console.ReadKey();
}
static void Permute(char[] arry, int i, int n)
{
int j;
if (i == n)
{
var temp = string.Empty;
foreach(var character in arry)
{
temp += character;
}
anagrams.Add(temp);
}
else
{
for (j = i; j <= n; j++)
{
Swap(ref arry[i], ref arry[j]);
Permute(arry, i + 1, n);
Swap(ref arry[i], ref arry[j]); //backtrack
}
}
}
static void Swap(ref char a, ref char b)
{
char tmp;
tmp = a;
a = b;
b = tmp;
}
Final Notes
I know this isn't the cleanest, nor best solution. This is simply one that carries the best across the 3 object oriented languages I know, that's also not too complex of a solution. Simple to understand, simple to change languages, so it's the answer I've decided to give.
EDIT
Here's the a new answer based on the comments of this answer.
static void Main(string[] args)
{
var str = "abaa";
var strAsArray = new string(str.ToCharArray());
var duplicateCount = 0;
List<char> dupedCharacters = new List<char>();
foreach(var character in strAsArray)
{
if(str.Count(f => (f == character)) > 1 && !dupedCharacters.Contains(character))
{
duplicateCount += str.Count(f => (f == character));
dupedCharacters.Add(character);
}
}
Console.WriteLine("The number of possible anagrams is: " + (factorial(str.Count()) / factorial(duplicateCount)));
Console.ReadLine();
int factorial(int num)
{
if(num <= 1)
return 1;
return num * factorial(num - 1);
}
}

Torus in libgdx without object

How do you create a torus in libgdx ? Modelbuilder doesn't support it.
I have to create a torus in code, and cant load any objects.
With libGDX to create custom Models you'd use the MeshBuilder.
Via the MeshBuilder.vertex(...) method you can add a vertex with the necessary information, one by one. Basically you'll need two nested loops and look up the necessary formulas for the torus here.
You have to wrap it in MeshBuilder.begin(...) and MeshBuilder.end().
MeshBuilder.end() will return a Mesh, which you can then pass to ModelBuilder.fromMesh(mesh) to get the Model you need.
Find resolution, how create torus in libgdx. May will be helpfull.
private void createTorus (int glMaterial, float X, float Y, float Z, float widthR,
float height, int divisionsU, int divisionsV, float r, float g, float b, float a) {
ModelBuilder modelBuilder = new ModelBuilder();
modelBuilder.begin();
MeshPartBuilder builder = modelBuilder.part("torus", glMaterial, Usage.Position |
Usage.Normal, new Material(ColorAttribute.createDiffuse(r, g, b, a)));
builder.setColor(Color.LIGHT_GRAY);
VertexInfo curr1 = vertTmp3.set(null, null, null, null);
curr1.hasUV = curr1.hasPosition = curr1.hasNormal = true;
VertexInfo curr2 = vertTmp4.set(null, null, null, null);
curr2.hasUV = curr2.hasPosition = curr2.hasNormal = true;
short i1, i2, i3 = 0, i4 = 0;
int i, j, k;
double s, t, twopi;
twopi = 2 * Math.PI;
for (i = 0; i < divisionsV; i++) {
for (j = 0; j <= divisionsU; j++) {
for (k = 1; k >= 0; k--) {
s = (i + k) % divisionsV + 0.5;
t = j % divisionsU;
curr1.position.set(
(float) ((widthR+height*Math.cos(s * twopi / divisionsV))*Math.cos(t * twopi / divisionsU)),
(float) ((widthR+height*Math.cos(s*twopi/divisionsV))*Math.sin(t * twopi / divisionsU)),
(float) (height * Math.sin(s * twopi / divisionsV)));
curr1.normal.set(curr1.position).nor();
k--;
s = (i + k) % divisionsV + 0.5;
curr2.position.set(
(float) ((widthR+height*Math.cos(s * twopi / divisionsV))*Math.cos(t * twopi / divisionsU)),
(float) ((widthR+height*Math.cos(s*twopi/divisionsV))*Math.sin(t * twopi / divisionsU)),
(float) (height * Math.sin(s * twopi / divisionsV)));
curr2.normal.set(curr1.normal);
//curr2.uv.set((float) s, 0);
i1 = builder.vertex(curr1);
i2 = builder.vertex(curr2);
builder.rect(i4, i2, i1, i3);
i4 = i2;
i3 = i1;
}
}
}
torus_Model = modelBuilder.end();
torus_Instances = new ModelInstance(torus_Model);
}

Upper Triangular matrix

i want to create upper triangular matrix with cuda
In the upper triangular matrix, the elements located
ed below the diagonal are zeros. This function should assign
the given value to the other elements.
but below code assigns all values as 0 why?
__global__ void initUpperTrinagleGPU(int *devMatrix, int numR, int numC, int value) {
int x = blockDim.x*blockIdx.x + threadIdx.x;
int y = blockDim.y*blockIdx.y + threadIdx.y;
int offset = y * numC + x;
if(numC <= numR) {
devMatrix[offset] = 0;
}
else
devMatrix[offset] = value;
}
This condition is wrong if(numC <= numR), it is true if there are less or equal cols than rows.
This might work, but it's just out of my head, not tested:
if(x >= y) {
devMatrix[offset] = 0;
}
else {
devMatrix[offset] = value;
}
note, that you should wrap this into another condition like:
if(y < numR && x < numC) { ...

How to simplify this loop?

Considering an array a[i], i=0,1,...,g, where g could be any given number, and a[0]=1.
for a[1]=a[0]+1 to 1 do
for a[2]=a[1]+1 to 3 do
for a[3]=a[2]+1 to 5 do
...
for a[g]=a[g-1]+1 to 2g-1 do
#print a[1],a[2],...a[g]#
The problem is that everytime we change the value of g, we need to modify the code, those loops above. This is not a good code.
Recursion is one way to solve this(although I was love to see an iterative solution).
!!! Warning, untested code below !!!
template<typename A, unsigned int Size>
void recurse(A (&arr)[Size],int level, int g)
{
if (level > g)
{
// I am at the bottom level, do stuff here
return;
}
for (arr[level] = arr[level-1]+1; arr[level] < 2 * level -1; arr[level]++)
{
recurse(copy,level+1,g);
}
}
Then call with recurse(arr,1,g);
Imagine you are representing numbers with an array of digits. For example, 682 would be [6,8,2].
If you wanted to count from 0 to 999 you could write:
for (int n[0] = 0; n[0] <= 9; ++n[0])
for (int n[1] = 0; n[1] <= 9; ++n[1])
for (int n[2] = 0; n[2] <= 9; ++n[2])
// Do something with three digit number n here
But when you want to count to 9999 you need an extra for loop.
Instead, you use the procedure for adding 1 to a number: increment the final digit, if it overflows move to the preceding digit and so on. Your loop is complete when the first digit overflows. This handles numbers with any number of digits.
You need an analogous procedure to "add 1" to your loop variables.
Increment the final "digit", that is a[g]. If it overflows (i.e. exceeds 2g-1) then move on to the next most-significant "digit" (a[g-1]) and repeat. A slight complication compared to doing this with numbers is that having gone back through the array as values overflow, you then need to go forward to reset the overflowed digits to their new base values (which depend on the values to the left).
The following C# code implements both methods and prints the arrays to the console.
static void Print(int[] a, int n, ref int count)
{
++count;
Console.Write("{0} ", count);
for (int i = 0; i <= n; ++i)
{
Console.Write("{0} ", a[i]);
}
Console.WriteLine();
}
private static void InitialiseRight(int[] a, int startIndex, int g)
{
for (int i = startIndex; i <= g; ++i)
a[i] = a[i - 1] + 1;
}
static void Main(string[] args)
{
const int g = 5;
// Old method
int count = 0;
int[] a = new int[g + 1];
a[0] = 1;
for (a[1] = a[0] + 1; a[1] <= 2; ++a[1])
for (a[2] = a[1] + 1; a[2] <= 3; ++a[2])
for (a[3] = a[2] + 1; a[3] <= 5; ++a[3])
for (a[4] = a[3] + 1; a[4] <= 7; ++a[4])
for (a[5] = a[4] + 1; a[5] <= 9; ++a[5])
Print(a, g, ref count);
Console.WriteLine();
count = 0;
// New method
// Initialise array
a[0] = 1;
InitialiseRight(a, 1, g);
int index = g;
// Loop until all "digits" have overflowed
while (index != 0)
{
// Do processing here
Print(a, g, ref count);
// "Add one" to array
index = g;
bool carry = true;
while ((index > 0) && carry)
{
carry = false;
++a[index];
if (a[index] > 2 * index - 1)
{
--index;
carry = true;
}
}
// Re-initialise digits that overflowed.
if (index != g)
InitialiseRight(a, index + 1, g);
}
}
I'd say you don't want nested loops in the first place. Instead, you just want to call a suitable function, taking the current nesting level, the maximum nesting level (i.e. g), the start of the loop, and whatever if needs as context for the computation as arguments:
void process(int level, int g, int start, T& context) {
if (level != g) {
for (int a(start + 1), end(2 * level - 1); a < end; ++a) {
process(level + 1, g, a, context);
}
}
else {
computation goes here
}
}