I always have to close Unity through Task-Manager if I call this function through a button, what is wrong with my code? I know there are is a lot of processing required for this code but the process never finishes:
public void SudokuLösen()
{
for(int p = 1; p < 81; p++)
{
if(PositionWert[p] != 0){
for(int z = 1; z < 9; z++)
{
if(PositionWert[p] == z)
{
int Reihe = 0;
int Spalte = 0;
int Platz = 0;
for(int m = 0; m < 8; m++)
{
for(int r = 1; r < 9; r++)
{
if(p - m * 9 == r)
{
Reihe = r;
}
}
}
for(int s = 0; s < 9; s++)
{
if(p == Reihe * 9 - 9 + s )
{
s = Spalte;
}
}
for(int g = -8; g < 8; g++)
{
if((Spalte + g > 0) && (Spalte + g < 10))
{
Blockiert[(p + z * 81 - 81) + g] = true;
}
if((Reihe + g > 0) && (Reihe + g < 10))
{
Blockiert[(p + z * 81 - 81) + g * 9] = true;
}
}
for(int vx = 1; vx < 3; vx++)
{
if((Spalte == 0 + vx) || (Spalte == 3 + vx) || (Spalte == 6 + vx))
{
Platz += vx;
}
if((Reihe == 0 + vx) || (Reihe == 3 + vx) || (Reihe == 6 + vx))
{
Platz += (3 * vx - 3);
}
}
for(int q = 1; q < 4; q++)
{
Blockiert[(p + z * 81 - 81) + Quadrat[Platz * 4 - 4 + q]] = true;
}
}
}
}
}
}
}
the Arrays are defined like this:
public static bool[] Blockiert = new bool[730];
public static int[] PositionWert = new int[82];
private int[] Quadrat = {0, 10, 11, 19, 20, 8, 10, 17, 19, 7, 8, 16, 17, -8, -7, 10, 11, -10, -8, 8, 10, -11, -10, 7, 8, -17, -16, -8, -7, -19, -17, -10, -8, -20, -19, -11, -10};
I thought that it might just be because my computer would just take forever to call this function so I waited a long time and saw that Unity nearly used 15% of my CPU so it didn't really do much and the function processing just doesn't finish.
Does anyone know what is wrong or what I should change?
A freeze usually means you have a never ending loop somewhere.
All your loops are finite and there is nothing that should take longer than a couple of milliseconds - except one!
You have
for(int s = 0; s < 9; s++)
{
if(p == Reihe * 9 - 9 + s)
{
s = Spalte;
}
}
where you reassign s = 0 since Spalte was never assigned differently. So you restart the loop and if this condition is met once then it will definitely be met in a future iteration as well since none of the other parameters change within that loop => never ending loop.
Judging from the rest of your code it should probably rather be
Spalte = s;
Related
I was solving a CodeWars task and faced a problem.
In it you are given the array of numbers, which length is a multiple of 4, you need to visualise it as a (x1^2 + x2^2) * (x3^2 + x4^2) .... * (xn^2 + xn+1^2).
Calculate the result of this and find 2 numbers, which squares in sum, gives the result of initial sequance.
For example, you are given an array of ( 2, 1, 3, 4):
(2^2 + 1^2) * (3^2 + 4^2) = 125;
2 numbers, which squares in sum will give 125, is 2 and 11 because 4 + 121 = 125;
I wrote the code and it works with most of examples, but when i use big arrays such as
(3, 9, 8, 4, 6, 8, 7, 8, 4, 8, 5, 6, 6, 4, 4, 5) in result i receive (0,0);
I can't get the problem, help me pls and if u can use simplified english cause i am from Russia.
Here is my code:
using System;
using System.Numerics;
using System.Collections.Generic;
public class ProdSeq
{
public static BigInteger[] solve(int[] arr)
{
bool simplified = false;
var result = new BigInteger[2];
var index = 0;
BigInteger sequenceSum = 1;
for (int i = 0; i < arr.Length - 1; i+=2)
sequenceSum *= arr[i] * arr[i] + arr[i + 1] * arr[i + 1];
if (sequenceSum >= 1000000)
{
sequenceSum /= 10000;
simplified = true;
}
var list = new List<BigInteger>();
for (BigInteger i = 0; i <= (BigInteger)Math.Sqrt((double)sequenceSum + 1); i++)
list.Add(BigInteger.Multiply(i, i));
for (int i = 0; i < list.Count; i++)
{
var second = sequenceSum - list[i];
index = list.BinarySearch(second);
if (index > -1)
{
if (simplified)
{
result[0] = (BigInteger)(Math.Sqrt((double)list[i]) * 100);
result[1] = (BigInteger)(Math.Sqrt((double)list[index]) * 100);
break;
}
result[0] = (BigInteger)(Math.Sqrt((double)list[i]));
result[1] = (BigInteger)(Math.Sqrt((double)list[index]));
break;
}
}
Console.WriteLine($"A: {result[0]} B: {result[1]}");
return result;
}
}
it seems your error is coming from this line:
for (int i = 0; i <= (int)Math.Sqrt((double)sequenceSum + 1); i++)
list.Add(BigInteger.Multiply(i , i));
you have to use Biginteger.Multiply method
result = 302400 and 29092800 (lot of solutions i think)
I've puzzled over this not usual task for a days to figure out an appropriate algorithm. Let's say I have 2D array:
int[][] jagged = new int[4][];
jagged[0] = new int[4] { 1, 2, 3, 4 };
jagged[1] = new int[4] { 5, 6, 7, 8 };
jagged[2] = new int[4] { 9, 10, 11, 12 };
jagged[3] = new int[4] { 13, 14, 15, 16 };
How can I rotate this matrix in counter-clockwise direction to be like the following?
1 2 3 4 2 3 4 8 3 4 8 12
5 6 7 8 --> 1 7 11 12 --> 2 11 10 16
9 10 11 12 5 6 10 16 1 7 6 15
13 14 15 16 9 13 14 15 5 9 13 14
2D array can have various dimensions. I mean 2x3, or 3x4.
I've tried to use the following algorithm, but it rotates just to 90 degrees:
int [,] newArray = new int[4,4];
for (int i=3;i>=0;--i)
{
for (int j=0;j<4;++j)
{
newArray[j,3-i] = array[i,j];
}
}
If I change increments, then it does give me nothing. Maybe is there another solution?
Assuming each "square" of an array rotates independently.
You could use the following code snippet:
const int ArraySize = 4;
int[,] array =
{
{ 2, 3, 4, 8 },
{ 1, 7, 11, 12 },
{ 5, 6, 10, 16 },
{ 9, 13, 14, 15 }
};
for (int r = (ArraySize - 1) / 2; r >= 0; r--)
{
int start = r;
int end = ArraySize - r - 1;
int saveTopLeft = array[start, start];
// Top
for (int i = start; i <= end - 1; i++)
array[start, i] = array[start, i + 1];
// Right
for (int i = start; i <= end - 1; i++)
array[i, end] = array[i + 1, end];
// Bottom
for (int i = end; i >= start + 1; i--)
array[end, i] = array[end, i - 1];
// Left
for (int i = end; i >= start + 2; i--)
array[i, start] = array[i - 1, start];
// Saved element
array[start + 1, start] = saveTopLeft;
}
I know this question is answered but I wanted to do it for a general matrix of nxm. It takes into account the corner cases where the matrix has only one column or row.
public static void Rotate(int[,] matrix)
{
// Specific cases when matrix has one only row or column
if (matrix.GetLength(0) == 1 || matrix.GetLength(1) == 1)
RotateOneRowOrColumn(matrix);
else
{
int min = Math.Min(matrix.GetLength(0), matrix.GetLength(1)),
b = min / 2, r = min % 2;
for (int d = 0; d < b + r; d++)
{
int bkp = matrix[d, d];
ShiftRow(matrix, d, d, matrix.GetLength(1) - d - 1, true);
ShiftColumn(matrix, matrix.GetLength(1) - d - 1, d, matrix.GetLength(0) - d - 1, false);
ShiftRow(matrix, matrix.GetLength(0) - d - 1, d, matrix.GetLength(1) - d - 1, false);
ShiftColumn(matrix, d, d + 1, matrix.GetLength(0) - d - 1, true);
if (matrix.GetLength(0) - 2 * d - 1 >= 1)
matrix[d + 1, d] = bkp;
}
}
}
private static void RotateOneRowOrColumn(int[,] matrix)
{
bool isRow = matrix.GetLength(0) == 1;
int s = 0, e = (isRow ? matrix.GetLength(1) : matrix.GetLength(0)) - 1;
while (s < e)
{
if (isRow)
Swap(matrix, 0, s, 0, e);
else
Swap(matrix, s, 0, e, 0);
s++; e--;
}
}
public static void Swap(int[,] matrix, int from_x, int from_y, int to_x, int to_y)
{
//It doesn't verifies whether the indices are correct or not
int bkp = matrix[to_x, to_y];
matrix[to_x, to_y] = matrix[from_x, from_y];
matrix[from_x, from_y] = bkp;
}
public static void ShiftColumn(int[,] matrix, int col, int start, int end, bool down)
{
for (int i = down ? end - 1 : start + 1; (down && i >= start) || (!down && i <= end); i += down ? -1 : 1)
{ matrix[i + (down ? 1 : -1), col] = matrix[i, col]; }
}
public static void ShiftRow(int[,] matrix, int row, int start, int end, bool left)
{
for (int j = left ? start + 1 : end - 1; (left && j <= end) || (!left && j >= start); j += (left ? 1 : -1))
{ matrix[row, j + (left ? -1 : 1)] = matrix[row, j]; }
}
The prompt is to find the maximal sequence of consecutive equal elements in an array. I don't know what I'm doing wrong but I can't get the right result to show up. :/ Maybe the problem is in the way I iterate with the second loop?
class Class2
{
static void Main(string[] args)
{
int pos=0, bestpos=0, bestlen = 0;
int len = 1;
int[] vargu = { 2, 2, 3, 4, 5, 5, 5, 6, 9, 9, 9, 9 };
for(int i = 0; i < vargu.Length-1; i++)
{
if (vargu[i] == vargu[i++])
{
len++;
if (len > bestlen)
{
bestlen = len;
bestpos = pos;
}
}
else
{
len = 1;
pos = i++;
}
}
for(int k = bestpos; k <= bestlen; k++)
{
Console.Write("{0}", vargu[k]);
}
Console.ReadLine();
}
}
3 problems.
if (vargu[i] == vargu[i++])
dont use ++ with i, it means increment the actual value of i, and you are looping i. Use "i+1" instead.
pos = i++;
same problem here. the array wont get traversed by each index due to this line.
for(int k = bestpos; k <= bestlen; k++)
k < bestlen + bestpos, because bestpos = 8, and bestlen = 4, so loop run condition fails.
int pos = 0, bestpos = 0, bestlen = 0;
int len = 1;
int[] vargu = { 2, 2, 3, 4, 5, 5, 5, 6, 9, 9, 9, 9 };
for (int i = 0; i < vargu.Length - 1; i++)
{
if (vargu[i] == vargu[i+1])
{
len++;
if (len > bestlen)
{
bestlen = len;
bestpos = pos;
}
}
else
{
len = 1;
pos = i+1;
}
}
for (int k = bestpos; k < bestlen + bestpos; k++)
{
Console.Write("{0} ", vargu[k]);
}
Console.ReadLine();
You're using i++ in the loop body when you mean i + 1.
Note that i++ has the side effect of increasing i by 1. Leave the incrementation of i solely in for (int i = 0; i < vargu.Length - 1; i++).
Your problem is 2-fold.
First i++ increments the variable i which shifts the index forward. Something that you don't want. You need to use i+1 if you want to access the consecutive element
Second, when you print in the second loop your array the end-index is wrong. You start at bestpos but you want to end at bestpos + bestlen! Since you measure the length of the sequence and don't save the final index.
This should give you the expected result:
int pos = 0, bestpos = 0, bestlen = 0;
int len = 1;
int[] vargu = { 2, 2, 3, 4, 5, 5, 5, 6, 9, 9, 9, 9 };
for (int i = 0; i < vargu.Length - 1; i++)
{
if (vargu[i] == vargu[i+1])
{
len++;
if (len > bestlen)
{
bestlen = len;
bestpos = pos;
}
}
else
{
len = 1;
pos = i+1;
}
}
for (int k = bestpos; k <= bestpos+bestlen; k++)
{
Console.Write("{0}", vargu[k]);
}
Console.ReadLine();
I would suggest making a structure to hold results :
struct ResultItem
{
public int start;
public int end;
public int value;
}
And then just iterate and compare when signs are changing :
int[] vargu = { 2, 2, 3, 4, 5, 5, 5, 6, 9, 9, 9, 9 };
List<ResultItem> _result = new List<ResultItem>();
ResultItem current = new ResultItem{ value = vargu[0], start = 0, end = 1 };
for (int i = 1; i < vargu.Length; i++)
{
if (vargu [i] != current.value)
{
current.end = i;
_result.Add( current );
current = new ResultItem { value = vargu[i], start = i, end = i };
}
Console.WriteLine(current.value + " " + current.start + " " + current.end);
}
current.end = vargu.Length;
_result.Add(current);
Then you can dump the result as such :
foreach(ResultItem value in _result)
{
Console.WriteLine("integer {0} was placed {1} times in a row", value.value, value.end - value.start);
}
which should result in something like :
integer 2 was placed 2 times in a row
integer 3 was placed 1 times in a row
integer 4 was placed 1 times in a row
integer 5 was placed 3 times in a row
integer 6 was placed 1 times in a row
integer 9 was placed 4 times in a row
Then to find the longest sequence you can use Linq : _result.Max(r => r.end - r.start);
I've been working on the same problem myself. I tried using Mong Zhu's code above and it almost worked so I tweaked two things and it seemed to work.
Change (vargu[i] == vargu[i+1]) to (vargu[i] + 1 == vargu[i+1])
And pos = i + 1; to pos = i; and it seemed to work. My first post. I hope it's okay.
int[] arr = { 1, 2, 3, 5, 4, 3, 3, 4, 5, 6, 5, 4, 5, 6, 7, 8, 7, 5, 6, 9, 8, 7, 0 };
int pos = 0, bestPos = 0, bestLen = 0;
int len = 1;
for(int i = 0; i < arr.Length -1; i++)
{
if(arr[i] + 1 == arr[i + 1])
{
len++;
if(len > bestLen)
{
bestLen = len;
bestPos = pos;
}
}
else
{
len = 1;
pos = i ;
}
}
for( int k = bestPos; k <= bestLen + bestPos; k++)
{
Console.Write("{0}", arr[k]);
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int finalbestsum = 0;
int bestsum = 0;
int bestcount = 0;
int count = 0;
int consval = 0;
int? consval1 = null;
string bestvalue = null;
string bestvalue1 = null;
Console.WriteLine("Enter number of columns for the array");
int col = int.Parse(Console.ReadLine());
Console.WriteLine("Enter number of rows for the array");
int row = int.Parse(Console.ReadLine());
int[,] twodimen = new int[row, col];
for (int index = 0; index < twodimen.GetLength(0); index++ )
{
for (int index1 = 0; index1 < twodimen.GetLength(1); index1++)
{
Console.WriteLine("Enter twodimen {0} {1} value",index, index1);
twodimen[index, index1] = int.Parse(Console.ReadLine());
}
}
for (int index = 0; index < twodimen.GetLength(0); index++ )
{
for (int index1 = 0; index1 < twodimen.GetLength(1)-1; index1++)
{
consval = twodimen[index,index1];
if (consval == twodimen[index, index1 + 1])
{
consval1 = twodimen[index,index1+1];
//Console.Write("{0}" + " ", consval);
bestvalue = bestvalue + Convert.ToString(" " + consval + " ");
count++;
bestsum = bestsum + consval;
}
else if (consval1 != null)
{
//Console.Write(consval1);
count++;
bestvalue = bestvalue + Convert.ToString(" " + consval1 + " ");
bestsum = bestsum + Convert.ToInt16(consval1);
Console.WriteLine();
if (bestcount < count)
{
bestvalue1 = bestvalue;
bestcount = count;
finalbestsum = bestsum;
}
else if (bestcount == count && finalbestsum < bestsum)
{
bestvalue1 = bestvalue;
bestcount = count;
finalbestsum = bestsum;
}
bestvalue = null;
count = 0;
bestsum = 0;
consval1 = null;
}
if (consval == twodimen[index, index1 + 1] && index1 == (twodimen.GetLength(1)-2))
{
bestvalue = bestvalue + Convert.ToString(" " + consval1 + " ");
//Console.Write(consval1);
bestsum = bestsum + Convert.ToInt16(consval1);
count++;
consval1 = null;
if (bestcount < count)
{
bestcount = count;
bestvalue1 = bestvalue;
finalbestsum = bestsum;
}
else if (bestcount == count && finalbestsum < bestsum)
{
bestvalue1 = bestvalue;
bestcount = count;
finalbestsum = bestsum;
}
}
}
bestvalue = null;
count = 0;
bestsum = 0;
Console.WriteLine();
//Console.WriteLine(bestcount);
}
Console.WriteLine(bestvalue1);
Console.ReadLine();
}
}
}
I make this code to print array if the number of array is
{
1, 2, 3, 4, 5,
6, 7, 8, 9,
10,11,12,13,
14,15,16,17,
18,19,20,21,
22,23,24,25
}
the out put of this code is
1,2,6,3,7,11,4,6,12,16,5,9,13,17,21,10,14,18,21,15,19,23,20,24,25
I want to make change in this my code to be the out put begging from
21 16 22 11 17 23 6 12 18 24 1 7 13 19 25 2 8 14 203 9 15 4 10 5
and this my Code
int [,] p = new int [5,5];
int sum = 1;
for (int i = 1; i <= 5; i++)
{
for (int j = 1; j <= 5; j++)
{
p[i, j] = sum;
richTextBox1.Text += p[i, j].ToString();
sum++;
}
}
int C;
int R=1;
for (int i = 1; i <= 5; i++)
{
C = i;
for (int r = 1; r <= i; r++)
{
Output = Output + p[r, C];
C--;
}
}
richTextBox2.Text += Output.ToString();
for (int i = 2; i >= 5; i++)
{
R = i;
for (C = 5; C >= i; C--)
{
Output = Output + p[R, C];
R++;
}
}
richTextBox2.Text += Output.ToString();
This is more fiddly than you might think!
You want to traverse the diagonals of this matrix:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
starting at the bottom left and traversing each diagonal as depicted in this very badly-drawn diagram:
I've written a helper method called DiagonalIndices() that for a given maximum index (in the case of your 5x5 matrix, it will be 4) will produce a sequence of (row,col) indices in the correct order to traverse all the diagonals.
Note that the input array MUST be square - I'm assuming that is the case for your data! It clearly is for a 5x5 matrix.
The output of the following program is
21 16 22 11 17 23 6 12 18 24 1 7 13 19 25 2 8 14 20 3 9 15 4 10 5
Here's the code:
using System;
using System.Collections.Generic;
namespace ConsoleApplication4
{
public sealed class Index
{
public Index(int row, int col)
{
Row = row;
Col = col;
}
public readonly int Row;
public readonly int Col;
}
public static class Program
{
private static void Main()
{
int [,] p = new int[5, 5];
for (int i = 0, n = 1; i < 5; ++i)
for (int j = 0; j < 5; ++j, ++n)
p[i, j] = n;
// This is the bit you will use in your program.
// Replace the Console.WriteLine() with your custom code
// that uses p[index.Row, index.Col]
int maxIndex = p.GetUpperBound(1);
foreach (var index in DiagonalIndices(maxIndex))
Console.Write(p[index.Row, index.Col] + " ");
Console.WriteLine();
}
public static IEnumerable<Index> DiagonalIndices(int maxIndex)
{
for (int i = 0; i <= maxIndex; ++i)
for (int j = 0; j <= i; ++j)
yield return new Index(maxIndex-i+j, j);
for (int i = 0; i < maxIndex; ++i)
for (int j = 0; j < maxIndex-i; ++j)
yield return new Index(j, i+j+1);
}
}
}
This is a more efficient of printing only the diagonal values in a positive direction in a matrix.
int [,] p = new int [5,5]
{
{1, 2, 3, 4,5},
{6, 7, 8, 9},
{10,11,12,13},
{14,15,16,17},
{18,19,20,21},
{22,23,24,25}
};
for (int i = 4, j = 4; i >= 0 && j > = 0; i--, j--)
{
Console.Writeline(p[ i, j ]);
}
I have written a recursive quicksort algorithm in c# using Visual Studio. What seems weird is ,when the input which is the collection of number that will be sorted,is lower than 9500 in array it gives the result in both best,worse,and avarage case. However, when the input is greater than 9500 it throws a stackoverflow exception. I know there were another question that is nearly same as my question in site but I did the condition also which can recursive.
public int[] quick(int [] myarray,int p,int r)
{
int q;
if (p < r)
{
q = partition(myarray, p, r);
quick(myarray, p, q - 1);
quick(myarray, q + 1, r);
}
return myarray;
}
public int partition(int [] myarray, int left, int right)
{
int i = left - 1;
int tmp = 0;
int pivot = myarray[right];
for (int j = left; j < right; j++)
{
if (myarray[j] < pivot)
{
i = i + 1;
tmp = myarray[i];
myarray[i] = myarray[j];
myarray[j] = tmp;
}
}
tmp = myarray[i + 1];
myarray[i + 1] = myarray[right];
myarray[right] = tmp;
return i + 1;
}
static void Main(string[] args)
{
Stopwatch mwatch = new Stopwatch();
Program quickprogram = new Program();
int[] mydizi = new int[9000];
//int counter = 9000;
//initialization of quick array
for (int i = 0; i < mydizi.Length; i++)
{
mydizi[i] = i + 1;
}
int[] result = new int[9000]; //return array
//time is starting
mwatch.Start();
//algorithm is called
result = quickprogram.quick(mydizi,0,mydizi.Length-1);
//result is returned from quickprogram
for (long j = 0; j < result.Length;j++)
{
Console.Write(result[j] + ",");
}
mwatch.Stop();
//time is up
//Printing the time that show how it takes
Console.Write("Ms:" + mwatch.Elapsed.Milliseconds + " S:" + mwatch.Elapsed.Seconds + " Mn:" + mwatch.Elapsed.Minutes + " Hr:" + mwatch.Elapsed.Hours);
Console.ReadLine();
}
You do a worst-case quicksort. The array is already sorted and you try to sort it again.
Next, your partition() code indeed looks strange:
int i = left - 1; // i = left-1
int pivot = myarray[right];
for (int j = left; j < right; j++) // j = left
{
if (myarray[j] < pivot)
{
i = i + 1; // now i = left-1+1 = left = j
tmp = myarray[i];
myarray[i] = myarray[j];
myarray[j] = tmp;
// congratulations!
// you successfully exchanged a value with itself!
}
In the end result, you call quick() recursively with these arguments (with array size = 9):
quick( 0, 8)
> quick( 0, 7)
>> quick( 0, 6)
>>> quick( 0, 5)
>>>> quick( 0, 4)
>>>>> quick( 0, 3)
>>>>>> quick( 0, 2)
>>>>>>> quick( 0, 1)
>>>>>>>> quick( 0, 0)
>>>>>>>> quick( 2, 1)
>>>>>>> quick( 3, 2)
>>>>>> quick( 4, 3)
>>>>> quick( 5, 4)
>>>> quick( 6, 5)
>>> quick( 7, 6)
>> quick( 8, 7)
> quick( 9, 8)
You see that doing this with 9000 elements will easily reach a recursion level of 9000 nested calls.