ArgumentNullException: Argument cannot be null c#(Unity) - c#

Here is my code :
string playerwinnopairboth = "P ";
IEnumerator WinLog_big_road()
{
string[] historyvalue = { };
historyvalue = tzPlayInfo.Instance.HistoryValue;
/*-------------------------------*/
NetworkManager.instance.WebSocketServer.OnCallBack_SC_WEBSOCKET_BcGametableHistory += CallBack_CS_WEBSOCKET_BcGametableHistory;
/*-------------------------------*/
DeleteChildrens(pos_big_road);
yield return new WaitForEndOfFrame();
for (int i = 0; i < rh.Const._HISTORY_COUNT_CARD_ * rh.Const._HISTORY_DECK_; i++)
{
int x = i % rh.Const._HISTORY_COUNT_CARD_;
int y = i / rh.Const._HISTORY_COUNT_CARD_;
float xl = 2.0f;
float yl = -5.0f;
GameObject o = Instantiate(prefab_big_road) as GameObject;
o.transform.SetParent(pos_big_road);
o.transform.localScale = Vector3.one;
o.transform.localPosition = new Vector3(x * xl, y * yl, 0f);
if (historyvalue.Contains(playerwinnopairboth))
{
//o.GetComponent<UISprite>().spriteName = "layout_player_bigline-01";
//NGUITools.SetActive(o, true);
Debug.Log("PLAYER WIN, NO PAIR , NO PAIR");
}
}
private void CallBack_CS_WEBSOCKET_BcGametableHistory(bool success, Int32 gametable_no, Int32 year, Int32 month, Int32 day, Int32 shoe_no, bc_gametable_history_list list)
{
string s1 = "";
for (int i = 0; i < tzPlayInfo.Instance.bc_gametable_history_list.Count; i++)
{
s1 += tzPlayInfo.Instance.bc_gametable_history_list[i].r;
s1 += ",";
}
tzPlayInfo.Instance.HistoryValue = s1.ToString().Split(',');
}
my tzPlayInfo values is like this:
private string[] historyvalue;
public string[] HistoryValue
{
get { return historyvalue; }
set { historyvalue = value; }
}
The Error is pointing me out here
if (historyvalue.Contains(playerwinnopairboth))
{
//o.GetComponent<UISprite>().spriteName = "layout_player_bigline-01";
//NGUITools.SetActive(o, true);
Debug.Log("PLAYER WIN, NO PAIR , NO PAIR");
}
I don't know why it's giving me a null value . Could someone point out what i am doing wrong here. Thank you in advance for those who will help me...

Related

Collision response for AABB moving towards a center

This is a physics problem
So I have a group of rectangles I am trying to movie towards a point. I wanted to prevent them from getting into each other so I developed a custom physics engine that detect rectangle collision.
my problem here is that I can’t seem to get the wanted behaviour at all.
Here is what I have :
my current state
Here is what I Need:
The state I need
And Here is my current code:
private void RunScript(int iterations, List<Rectangle3d> spaces, Polyline boundary, List<int> lineStartIndices, List<int> lineEndIndices, List<int> viewIndex, List<int> orientationIndex, List<Point3d> cardinals, double moveDistance, double collisionDistance, double approximationMultiplier, double orientationMultiplier, List<double> spaceProximityMultipliers, List<double> spaceOrientationMultipliers, bool iterationMode, bool start, bool reset, ref object Vectors, ref object A, ref object B, ref object C)
{
List<Line> collisionDisplay = new List<Line>();
List<Line> collisionDisplay2 = new List<Line>();
if(iterationMode)
{
tempSpaces = spaces;
//--------------------------------------------------------------------
//iterate is start button is set to true
//--------------------------------------------------------------------
for(int i = 0; i < iterations;i++)
// Parallel.For(0, iterations, i =>
{
var collision = new RectangleCollider(moveDistance, collisionDistance,
approximationMultiplier, orientationMultiplier, boundary, tempSpaces);
collision.MoveRectangles();
collision.ApplyMove();
tempSpaces = collision.ResultingSpacesArr.ToList();
}
}
else
{
//--------------------------------------------------------------------
//reset loop on switch press
//--------------------------------------------------------------------
if(reset || counter == 0)
{
tempSpaces = spaces;
velocity = moveDistance;
counter = 0;
}
//--------------------------------------------------------------------
//iterate is start button is set to true
//--------------------------------------------------------------------
if(start)
{
GrasshopperDocument.ScheduleSolution(10, ScheduleSolutionCallback);
//loop logic if start is true
var collision = new RectangleCollider(velocity, collisionDistance,
approximationMultiplier, orientationMultiplier, boundary, tempSpaces);
collision.MoveRectangles();
collision.CollideRectangles();
collision.ApplyMove();
tempSpaces = collision.ResultingSpacesArr.ToList();
velocity = collision.MoveDistance;
counter++;
//output
Vectors = collision.MovementVectors;
}
}
//--------------------------------------------------------------------
//output
//--------------------------------------------------------------------
//gh conversion
var ghRects = new List<GH_Rectangle>();
for(int i = 0; i < tempSpaces.Count; i++)
ghRects.Add(new GH_Rectangle(tempSpaces[i]));
var ghCollisionDisplay = new List<GH_Line>();
for(int i = 0; i < collisionDisplay.Count; i++)
ghCollisionDisplay.Add(new GH_Line(collisionDisplay[i]));
var ghCollisionDisplay2 = new List<GH_Line>();
for(int i = 0; i < collisionDisplay2.Count; i++)
ghCollisionDisplay2.Add(new GH_Line(collisionDisplay2[i]));
A = ghRects;
B = ghCollisionDisplay;
C = ghCollisionDisplay2;
//display no of iterations on console
Print("Iterations: " + (counter).ToString());
Print("velocity: " + (velocity).ToString());
}
// <Custom additional code>
//params
List<Rectangle3d> tempSpaces = new List<Rectangle3d>();
double velocity;
int counter;
//iteration logic
public void ScheduleSolutionCallback(GH_Document doc)
{
this.Component.ExpireSolution(false);
}
//--------------------------------------------------------------------
//Collision class
//--------------------------------------------------------------------
public class RectangleCollider
{
public double MoveDistance;
public double CollisionDistance;
public double ApproximationMultiplier;
public double OrientationMultiplier;
public Polyline Boundary;
public Point3d Center;
public List<Rectangle3d> Spaces;
public Rectangle3d[] ResultingSpacesArr;
public Vector3d[] MovementVectors;
public bool IsColliding = false;
public RectangleCollider(double moveDistance, double collisionDistance,
double approximationMultiplier, double orientationMultiplier,
Polyline boundary, List<Rectangle3d> spaces)
{
MoveDistance = moveDistance;
CollisionDistance = collisionDistance;
ApproximationMultiplier = approximationMultiplier;
OrientationMultiplier = orientationMultiplier;
Boundary = boundary;
Spaces = spaces;
Center = boundary.CenterPoint();
MovementVectors = new Vector3d[spaces.Count];
}
//Move Points
public void MoveRectangles()
{
for(int i = 0; i < Spaces.Count; i++)
{
if(Spaces[i].Center.DistanceTo(Center) > 1 && !IsColliding)
{
Vector3d translationVector = Center - Spaces[i].Center;
if(Math.Abs(Center.X - Spaces[i].Center.X) > Math.Abs(Center.Y - Spaces[i].Center.Y))
{
var xVector = new Vector3d(translationVector.X, 0, 0);
xVector.Unitize();
MovementVectors[i] += xVector * 0.5;
}
else
{
var yVector = new Vector3d(0, translationVector.Y, 0);
yVector.Unitize();
MovementVectors[i] += yVector * 0.5;
}
}
}
}
//collide rectangles
public void CollideRectangles()
{
Parallel.For(0, Spaces.Count, i =>
{
for(int j = 0; j < Spaces.Count; j++)
{
if(i != j)
{
var rect1MinX = Spaces[i].Corner(0).X;
var rect1MaxX = Spaces[i].Corner(2).X;
var rect1MinY = Spaces[i].Corner(0).Y;
var rect1MaxY = Spaces[i].Corner(2).Y;
var rect1Center = Spaces[i].Center;
var rect2MinX = Spaces[j].Corner(0).X;
var rect2MaxX = Spaces[j].Corner(2).X;
var rect2MinY = Spaces[j].Corner(0).Y;
var rect2MaxY = Spaces[j].Corner(2).Y;
var rect2Center = Spaces[j].Center;
if((rect1MinX < rect2MaxX && rect1MaxX > rect2MinX) &&
(rect1MinY < rect2MaxY && rect1MaxY > rect2MinY))
{
//stop if they collide
IsColliding = true;
//if they collide in x
if ( rect1MinX < rect2MaxX && rect1MaxX > rect2MinX )
{
MovementVectors[j].X += -MovementVectors[j].X;
}
//if they collide in y
if ( rect1MinY < rect2MaxY && rect1MaxY > rect2MinY )
{
MovementVectors[j].Y += -MovementVectors[j].Y;
}
}
else {
IsColliding = false;
}
}
}
}
);
}
//apply move
public void ApplyMove()
{
var spacesArr = Spaces.ToArray();
for(int i = 0; i < Spaces.Count; i++)
{
var move = Transform.Translation(MovementVectors[i]);
spacesArr[i].Transform(move);
}
ResultingSpacesArr = spacesArr;
}
}
// </Custom additional code>
}
please tell me anything you know. As have been stuck in this for months and researched it so much on many engines but didn’t find the right answer(or didn’t have enough understanding)
thank you in advance.

How do I graph a-b=0?

Lets say a=x+y and b=2x-y and I want to plot a-b=0. I can manually rewrite this from (x+y)-(2x-y)=0 to y=.5x which makes it trivial to graph, but how do I rewrite it in code? Given x how do I calculate y if all I have is (x+y)-(2x-y)=0?
To be more specific, I am trying to graph the decision boundary of a neural network. I want to be able to change the layers and outputs at will, essentially changing the function I get as an output.
This is an example of an output I could get:
(x_1 w_2 + x_2 w_2 + b_1) w_7
+ (x_1 w_3 + x_2 w_4 + b_2) w_8
+ (x_1 w_5 + x_2 w_6 + b_3) w_9
+ b_4 (x_1 w_1 + x_2 w_2 + b_1) w_10
+ (x_1 w_3 + x_2 w_4 + b_2) w_11
+ (x_1 w_5 + x_2 w_6 + b_3) w_12
+ b_5
It's a 1 by 2 matrix and I know all values except x2 which is the y-axis. In order to draw the decision boundary I have to calculate a-b=0 where a and b both contain x and y. I can manually separate y to get y=... ,but that's not an option if the results in the output matrix change. How do I seperate/calculate the y?
I am using c# in Unity and passing the points on the graph into the LineRenderer.
Alright, I found the solution the same day of posting the question but had already been messing about for days. It turned out to be a math question after all.
Here's a link to the specific setup for the neural network using a linear activation: https://www.desmos.com/calculator/crmeebqnfb
I manually rewrote the matrix multiplication for this specific setup into a function and was looking for a way to do that for any size and number of invisible layers.
The solution I found is to separate the input matrix into x1 and x2 and separately do the matrix multiplication for them. The x1 value gets the biases added but the x2 doesn't and the first weight matrix has to be split in 2 so x1 can get multiplied with the first row and x2 with the second row.
If you then do the matrix multiplication from there you'll get two 2 matrices like this:
[firstx1answer secondx1answer] [firstx2answer secondx2answer]
And then you can put them into this function:
Edit for better clarification:
Maybe a bit confusing but here's my code. CreateDecisionBoundaryPoints is where this is implemented:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using System.IO;
using System;
[ExecuteAlways]
public class Controller : MonoBehaviour
{
public Transform LineRenderer;
public GameObject textPrefab;
public GameObject pointPrefab;
public Transform weightsUI;
public Transform biasesUI;
[Range(.001f, .1f)] public float delta;
public int numberOfHiddenLayers;
public bool debugWeightMatrices;
public bool debugBiasMatrices;
[HideInInspector] public string[] dataValues;
private void Start()
{
if (Application.isPlaying)
{
//read file
int numberOfLines;
dataValues = ReadData("D:\\Documents\\Unity Projects\\Learning Machine Learning\\Assets\\Data.csv", out numberOfLines);
int numOfOutputNeurons = CreatePointsUI(numberOfLines, dataValues);
//create layerSizes for example [2,3,2]
int[] layerSizes = new int[numberOfHiddenLayers + 2];
layerSizes[0] = (dataValues.Length / numberOfLines) - 1;
layerSizes[numberOfHiddenLayers + 1] = numOfOutputNeurons;
for (int i = 0; i < numberOfHiddenLayers; i++)
{
layerSizes[i+1] = Mathf.Max((dataValues.Length / numberOfLines) - 1, numOfOutputNeurons) + 1;
}
//create the actual matrices
List<float[,]> weights = new List<float[,]>();
List<float[]> biases = new List<float[]>();
MakeTheMatrices(layerSizes, out weights, out biases);
//fill weights with random values
RandomlyFillMatrices(weights);
//print matrices to make sure they're the right size and filled randomly
if (debugWeightMatrices)
Debug.Log(PrintMatrices(weights, "Weight Matrices"));
if (debugBiasMatrices)
Debug.Log(PrintMatrices(biases, "Bias Matrices"));
LineRenderer.GetComponent<DrawDecisionBoundary>().DrawLine(CreateDecisionBoundaryPoints(weights, biases, delta));
}
}
public struct OutputNeuronsAndColours
{
public string value;
public Color color;
public OutputNeuronsAndColours(string value, Color color)
{
this.value = value;
this.color = color;
}
}
public void DoTheWeightsStufUI(int weights)
{
int cwn = 0;
List<Transform> ws = new List<Transform>();
foreach (Transform child in weightsUI)
{
cwn++;
ws.Add(child);
}
int wta = weights - cwn;
for (int i = wta; i < 0; i++)
{
cwn--;
DestroyImmediate(ws[cwn].gameObject);
ws.RemoveAt(cwn);
}
for (int i = wta; i > 0; i--)
{
cwn++;
GameObject weight = Instantiate(textPrefab, weightsUI);
weight.GetComponentInChildren<TMP_Text>().SetText("W" + cwn.ToString());
}
}
public void DoTheBiasesStufUI(int biases)
{
int cbn = 0;
List<Transform> bs = new List<Transform>();
foreach (Transform child in biasesUI)
{
cbn++;
bs.Add(child);
}
int bta = biases - cbn;
for (int i = bta; i < 0; i++)
{
cbn--;
DestroyImmediate(bs[cbn].gameObject);
bs.RemoveAt(cbn);
}
for (int i = bta; i > 0; i--)
{
cbn++;
GameObject bias = Instantiate(textPrefab, biasesUI);
bias.GetComponentInChildren<TMP_Text>().SetText("B" + cbn.ToString());
}
}
string[] ReadData(string path, out int numberOfLines)
{
List<string> data_values = new List<string>();
StreamReader strReader = new StreamReader(path);
bool endOfFile = false;
int numOfLines = 0;
while (!endOfFile)
{
string data_string = strReader.ReadLine();
if (data_string == null)
{
endOfFile = true;
break;
}
else
numOfLines += 1;
data_values.AddRange(data_string.Split(','));
}
numberOfLines = numOfLines;
return data_values.ToArray();
}
int CreatePointsUI(int numberOfLines, string[] dataValues)
{
string[] possibleOutputs = new string[numberOfLines];
for (int i = 0; i < numberOfLines; i++)
{
possibleOutputs[i] = dataValues[(i * (dataValues.Length / numberOfLines)) + ((dataValues.Length / numberOfLines) - 1)];
}
List<OutputNeuronsAndColours> outputNeurons = new List<OutputNeuronsAndColours>(possibleOutputs.Length);
for (int i = 0; i < possibleOutputs.Length; i++)
{
bool contains = false;
for (int x = 0; x < outputNeurons.Count; x++)
{
if (possibleOutputs[i] == outputNeurons[x].value)
contains = true;
}
if (!contains)
outputNeurons.Add(new OutputNeuronsAndColours(possibleOutputs[i], new Color(UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f), UnityEngine.Random.Range(0f, 1f))));
}
for (int i = 0; i < numberOfLines; i++)
{
GameObject point = Instantiate(pointPrefab);
point.transform.position = new Vector2(float.Parse(dataValues[i * (dataValues.Length / numberOfLines)]), float.Parse(dataValues[(i * (dataValues.Length / numberOfLines)) + 1]));
foreach (OutputNeuronsAndColours value in outputNeurons)
{
if (value.value == dataValues[(i * (dataValues.Length / numberOfLines)) + ((dataValues.Length / numberOfLines) - 1)])
point.GetComponent<SpriteRenderer>().color = value.color;
}
}
return outputNeurons.Count;
}
public static void MakeTheMatrices(int[] layerSizes, out List<float[,]> weights, out List<float[]> biases)
{
List<float[,]> tempWeights = new List<float[,]>();
List<float[]> tempBiases = new List<float[]>();
for (int i = 0; i < layerSizes.Length - 1; i++)
{
tempWeights.Add(new float[layerSizes[i], layerSizes[i + 1]]);
}
for (int i = 1; i < layerSizes.Length; i++)
{
List<float> temp = new List<float>();
for (int x = 0; x < layerSizes[i]; x++)
temp.Add(0);
tempBiases.Add(temp.ToArray());
}
weights = tempWeights;
biases = tempBiases;
}
public static void RandomlyFillMatrices(List<float[,]> matrices)
{
foreach (float[,] matrix in matrices)
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int x = 0; x < matrix.GetLength(1); x++)
{
matrix[i, x] = UnityEngine.Random.Range(-3f, 3f);
}
}
}
}
public static string PrintMatrices(List<float[,]> matrices, string name = "Count")
{
string returnString = matrices.Count + " " + name;
foreach (float[,] matrix in matrices)
{
returnString += " (" + matrix.GetLength(0) + ", " + matrix.GetLength(1) + ")";
for (int i = 0; i < matrix.GetLength(0); i++)
{
string log = "";
if (i == 0)
log += "[";
else
log += " ";
for (int x = 0; x < matrix.GetLength(1); x++)
{
log += matrix[i, x];
if(x != matrix.GetLength(1) - 1)
log += " ";
}
if (i == matrix.GetLength(0) - 1)
log += "]";
Debug.Log(log);
}
}
return returnString;
}
public static string PrintMatrices(List<float[]> matrices, string name = "Count")
{
string returnString = matrices.Count + " " + name;
foreach (float[] matrix in matrices)
{
returnString += " (" + matrix.Length + ")";
string log = "[";
for (int i = 0; i < matrix.Length; i++)
{
log += matrix[i];
if (i != matrix.Length - 1)
log += " ";
}
log += "]";
Debug.Log(log);
}
return returnString;
}
private Vector3[] CreateDecisionBoundaryPoints(List<float[,]> weights, List<float[]> biases, float delta)
{
//check whether there are exactly 2 input neurons
if (weights[0].GetLength(0) != 2)
Debug.LogError("Not exactly 2 input neurons!");
//check whether there are exactly 2 output neurons
if (biases[biases.Count - 1].Length != 2)
Debug.LogError("Not exactly 2 output neurons!");
//create the values for the first layer
float[] weightsForFirstLayerX = new float[weights[0].GetLength(1)];
for (int i = 0; i < weights[0].GetLength(1); i++)
{
weightsForFirstLayerX[i] = weights[0][0, i];
}
float[] denominatorValuesFirstLayer = new float[weights[0].GetLength(1)];
for (int i = 0; i < weights[0].GetLength(1); i++)
{
denominatorValuesFirstLayer[i] = weights[0][1, i];
}
List<Vector3> pointsForGraph = new List<Vector3>();
//Calculate the y value(s) for each x with interval delta
for (float x = -.04f; x <= 1 + delta; x += delta)
{
float[] numeratorValuesFirstLayer = new float[weightsForFirstLayerX.Length];
for (int i = 0; i < weightsForFirstLayerX.Length; i++)
numeratorValuesFirstLayer[i] = x * weightsForFirstLayerX[i] + biases[0][i];
//get the row matrices for the decision boundary function
float[] numeratorResults = PassValuesThroughMatrices(numeratorValuesFirstLayer, weights, biases, true);
float[] denominatorResults = PassValuesThroughMatrices(denominatorValuesFirstLayer, weights, biases, false);
float y = (numeratorResults[1] - numeratorResults[0]) / (denominatorResults[0] - denominatorResults[1]);
pointsForGraph.Add(new Vector3(x, y, -1));
}
return pointsForGraph.ToArray();
}
private float[] PassValuesThroughMatrices(float[] values, List<float[,]> weights, List<float[]> biases, bool isNumerator)
{
float[] previousLayer = values;
//loop passing the previous layer values through the current layer: values = values * weights + biases
for (int i = 1; i < weights.Count; i++)
{
float[] temp = new float[weights[i].GetLength(1)];
//loop through the colums in the weight matrix
for (int v = 0; v < weights[i].GetLength(1); v++)
{
float value = 0;
//loop through the rows in the weight matrix
for (int b = 0; b < weights[i].GetLength(0); b++)
value += previousLayer[b] * weights[i][b, v];
if (isNumerator)
value += biases[i][v];
temp[v] = value;
}
previousLayer = temp;
}
//return the last itteration of values
return previousLayer;
}
}

How to add a texture to the prefab in unity

I have unity script which will instantiate objects during the runtime. I need to add a texture to my prefab. I went through some solutions and i couldnt find a proper solution. my code is
using UnityEngine;
using System.Collections;
#if UNITY_EDITOR
using UnityEditor;
#endif
public class createWalls : MonoBehaviour {
bool creating;
public GameObject start;
public GameObject end;
int k=0;
int count = 0;
public TextAsset TextFile;
public GameObject wallPrehab;
GameObject wall;
public Collider coll;
public Camera c1;
public Camera c2;
public Manager mgr;
/*
*even we though it get as x,y values when modeling convert it's y value as z
*/
Vector3[] coordinatesX = null;
Vector3[] coordinatesY = null;
public Texture texture;
/*
* Use this for initialization
*/
void Start () {
readTextFileLines();
Vector3 start = new Vector3();
Vector3 end = new Vector3();
for (int i = 0; i < coordinatesX.Length; i++)
{
k = i + 1;
if (k != coordinatesX.Length)
{
if(coordinatesX[i].x == coordinatesX[k].x){
start = coordinatesX[i];
end = coordinatesX[k];
setStart(start);
setEnd(end);
adjust();
}
}
}
for(int j = 0; j < coordinatesY.Length; j++){
k = j + 1;
if (k != coordinatesY.Length)
{
if(coordinatesY[j].z == coordinatesY[k].z){
start = coordinatesY[j];
end = coordinatesY[k];
setStart(start);
setEnd(end);
adjust();
}
}
}
}
// Update is called once per frame
void Update () {
//getinput();
}
/*
* getting the mouse clicked position coordinate
*/
int number=0;
void setStart(Vector3 x){
creating = true;
start.transform.position = x;
wall = Instantiate (wallPrehab, start.transform.position, Quaternion.identity)as GameObject;
wall.GetComponent<WallScript>().mgr=mgr;
wall.gameObject.name = number.ToString ();
number++;
}
/*
* getting the mouse click over position coordinate
*/
void setEnd(Vector3 y){
end.transform.position = y;
}
/*
* invoking the wall building method
*/
void adjust(){
adjustWall ();
}
/*
* build the wall in between start point and the end point
*/
void adjustWall(){
start.transform.LookAt (end.transform.position);
end.transform.LookAt (start.transform.position);
float distance = Vector3.Distance (start.transform.position, end.transform.position);
wall.transform.position = start.transform.position + distance / 2 * start.transform.forward;
wall.transform.rotation = start.transform.rotation;
wall.transform.localScale = new Vector3 (wall.transform.localScale.x, wall.transform.localScale.y, distance);
}
/*
* Reading from the text file
*/
void readTextFileLines()
{
int count = 0;
string splits = TextFile.text.TrimStart ('[');
string[] split = TextFile.text.Split (')');
string split_1 = null;
string split_2 = null;
string split_3 = null;
int pos = 0;
int lengthOfString = 0;
int valX, valZ, valX1, valZ1 = 0;
/*
* Getting the count of the coordinates in the array
*/
foreach (string x in split) {
count++;
}
string[] stringArr = new string[count];
int[] xSortX = new int[count];
int[] xSortZ = new int[count];
int[] ySortX = new int[count];
int[] ySortZ = new int[count];
/*
* Splitting the coordinates as x,y and store in an array
*/
foreach (string coord in split) {
split_1 = coord;
split_1 = split_1.Trim ('[');
split_1 = split_1.Trim ('(');
split_1 = split_1.Trim (',');
split_1 = split_1.Trim (' ');
split_1 = split_1.Trim ('(');
split_1 = split_1.TrimEnd (']');
stringArr [pos] = split_1;
pos++;
}
//Debug.Log("Array Length " + stringArr.Length);
/*
* extracting simalar x coordinates
*/
//Debug.Log("");
//Debug.Log("-----------------extracting simalar x coordinates----------------");
//Debug.Log("");
int indexX = 0;
int loopRunX = 0;
for (int a = 0; a < stringArr.Length - 1; a = indexX) {
split_2 = stringArr [a];
lengthOfString = split_2.Length;
valX = int.Parse (split_2.Substring (0, split_2.IndexOf (',')));
valZ = int.Parse (split_2.Substring (split_2.IndexOf (' '), (lengthOfString - split_2.IndexOf (' '))));
for (int x1 = indexX; x1 < stringArr.Length - 1; x1++) {
split_3 = stringArr [x1];
lengthOfString = split_3.Length;
valX1 = int.Parse (split_3.Substring (0, split_3.IndexOf (',')));
valZ1 = int.Parse (split_3.Substring (split_3.IndexOf (' '), (lengthOfString - split_3.IndexOf (' '))));
//Check for the simillar x in the text file we provide
if (valX == valX1) {
xSortX [indexX] = valX1;
xSortZ [indexX] = valZ1;
//Debug.Log("X is " + valX + " and the coordinates which have simillar x ==> (" + valX1 + ", " + valZ1 + "). Index is " + x1);
//Debug.Log("xSortX["+indexX+"] is :"+xSortX[indexX]);
//Debug.Log("xSortZ["+indexX+"] is :"+xSortZ[indexX]);
indexX++;
} else {
break;
}
}
loopRunX++;
//indexX = indexX + countx;
//Debug.Log("Next Index to check onwards : " + indexX);
//Debug.Log("Looping Count : " + loopRunX);
//Debug.Log("");
}
coordinatesX = new Vector3[count];
/*
* Adding the x and z coorinates values to Vector3 array to build the object in coordinates x
*/
for (int x =0; x<count; x++) {
Vector3 createVArray = new Vector3 (xSortX [x], 0, xSortZ [x]);
coordinatesX [x] = createVArray;
//Debug.Log("Coordinates X :"+coordinatesX[x]);
}
/*
* extracting simalar x coordinates
*/
//Debug.Log("");
//Debug.Log("-----------------extracting simalar Y coordinates----------------");
//Debug.Log("");
int[] checker = new int[count];
bool eq = false;
int indexY = 0;
loopRunX = 0;
for (int a = 0; a < stringArr.Length - 1; a++) {
split_2 = stringArr [a];
lengthOfString = split_2.Length;
valX = int.Parse (split_2.Substring (0, split_2.IndexOf (',')));
valZ = int.Parse (split_2.Substring (split_2.IndexOf (' '), (lengthOfString - split_2.IndexOf (' '))));
foreach (int check in checker) {
if (check == valZ) {
eq = false;
break;
} else {
eq = true;
}
}
if (eq) {
checker [a] = valZ;
for (int x1 = a; x1 < stringArr.Length - 1; x1++) {
split_3 = stringArr [x1];
lengthOfString = split_3.Length;
valX1 = int.Parse (split_3.Substring (0, split_3.IndexOf (',')));
valZ1 = int.Parse (split_3.Substring (split_3.IndexOf (' '), (lengthOfString - split_3.IndexOf (' '))));
//Check for the simillar x in the text file we provide
if (valZ == valZ1) {
ySortX [indexY] = valX1;
ySortZ [indexY] = valZ1;
//Debug.Log("Y is " + valZ + " and the coordinates which have simillar z ==> (" + valX1 + ", " + valZ1 + "). Index is " + x1);
//Debug.Log("ySortX["+indexY+"] is :"+ySortX[indexY]);
//Debug.Log("ySortZ["+indexY+"] is :"+ySortZ[indexY]);
indexY++;
}
}
loopRunX++;
}
//Debug.Log("");
}
coordinatesY = new Vector3[count];
/*
* Adding the x and z coorinates values to Vector3 array to build the object in coordinates x
*/
for (int x =0; x<count; x++) {
Vector3 createVArray = new Vector3 (ySortX [x], 0, ySortZ [x]);
coordinatesY [x] = createVArray;
//Debug.Log("Coordinates Y :"+coordinatesY[x]);
}
}
I need to add this texture to my gameObject prefab

Cosine similarity calculation issue

I am having issues in calculation of cosine similarity between 2 strings.
I calculate the binary vector format of each string using a function. It gives out binary vectors which are in the form of, say, (1,1,1,1,1,0,0,0,0).
public static Tuple<int[],int[]> sentence_to_vector(String[] word_array1, String[] word_array2)
{
String[] unique_word_array1 = word_array1.Distinct().ToArray();
String[] unique_word_array2 = word_array2.Distinct().ToArray();
String[] list_all_words = unique_word_array1.Concat(unique_word_array2).ToArray();
String[] list_all_words_unique = list_all_words.Distinct().ToArray();
int count_all_unique_words = list_all_words_unique.Length;
int[] sentence1_vector = new int[count_all_unique_words];
int[] sentence2_vector = new int[count_all_unique_words];
for (int i = 0; i < count_all_unique_words; i++)
{
if (Array.IndexOf(unique_word_array1, list_all_words_unique[i]) >= 0)
{
sentence1_vector[i] = 1;
}
else
{
sentence1_vector[i] = 0;
}
}
for (int i = 0; i < count_all_unique_words; i++)
{
if (Array.IndexOf(word_array2, list_all_words_unique[i]) >= 0)
{
sentence2_vector[i] = 1;
}
else
{
sentence2_vector[i] = 0;
}
}
return Tuple.Create(sentence1_vector, sentence2_vector);;
}
After I calculate the vector representation, I go for cosine similarity calculation.
The code is attached herewith:
public static float get_cosine_similarity(int[] sentence1_vector, int[] sentence2_vector)
{
int vector_length = sentence1_vector.Length;
int i = 0;
float numerator = 0, denominator = 0;
int temp1 = 0, temp2 = 0;
double square_root1 = 0, square_root2 = 0;
for (i = 0; i < vector_length; i++)
{
numerator += sentence1_vector[i] * sentence2_vector[i];
temp1 += sentence1_vector[i] * sentence1_vector[i];
temp2 += sentence2_vector[i] * sentence2_vector[i];
}
//TextWriter tw = new StreamWriter("E://testpdf/date2.txt");
square_root1 = Math.Sqrt(temp1);
square_root2 = Math.Sqrt(temp2);
denominator = (float)(square_root1 * square_root2);
if (denominator != 0){
return (float)(numerator / denominator);
//return (float)(numerator);
}
else{
return 0;
}
}
I checked out a site where in I can specify 2 strings and find the cosine similarity between them. The site is attached herewith:
http://cs.uef.fi/~zhao/Link/Similarity_strings.html
function implementationCosin(){
var string1 = document.DPAform.str1.value;
var s1 = stringBlankCheck(string1);
var string2 = document.DPAform.str2.value;
var s2 = stringBlankCheck(string2);
if (s1.length < 1) {
alert("Please input the string1.");
return;
}
if (s2.length < 1) {
alert("Please input the string2.");
return;
}
document.DPAform.displayArea2.value = "";
var sDT = new Date();
// var begin = new Date().getTime();
var cosin_similarity_value = consinSimilarity(s1, s2);
document.DPAform.displayArea2.value += 'Cosin_Similarity(' + s1 + ',' + s2 + ')=' + cosin_similarity_value + '%\n';
var eDT = new Date();
var timediff = sDT.dateDiff("ms", eDT);
// var timediff = (new Date().getTime() - begin);
document.DPAform.displayArea2.value += "The total escaped time is: " + timediff + " (ms).\n";
}
Even if 2 sentences are 0% similar, my codes says that there is some amount of similarity between them.

Conversion of Binary fractions to Decimal in C# GUI

How do you convert binary fractions to decimal in c#? eg: 1101.101 is supposed to be 13.625, I get 1.25 which is way off. I seem to get errors when I put a fractional binary number, no problems on whole Binary numbers. I can show my code if needed.
Code:
double tempans = 0;
double answer = 0;
string finAns;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string[] temp = new string[5];
string strHldr = textBox1.Text;
bool isFractional = strHldr.Contains('.');
double val1 = 0;
double val2 = 0;
if (!isFractional)
finAns = ComputePart(strHldr);
else
{
string wholeP = WholePart(strHldr);
string deciP = DecimalPart(strHldr);
val1 = double.Parse(ComputePart(wholeP));
val2 = double.Parse(ComputeDeci(deciP));
finAns = (val2 + val2).ToString();
}
textBox1.Text = finAns;
}
private string ComputePart(string strHldr)
{
double length1 = strHldr.Length - 1;
for (int i = 0; i < strHldr.Length; i++)
{
if (strHldr[i] == '1')
{
tempans = Math.Pow(2, length1);
answer += tempans;
}
length1 -= 1;
}
length1 = 0;
return answer.ToString();
}
private string ComputeDeci(string number)
{
double ans = 0;
double counter = 1;
double finalAns = 0;
for (int i = 0; i < number.Length; i++)
{
ans = counter * 0.5;
counter = ans;
if (number[i] == '1')
{
finalAns += counter;
}
}
return finalAns.ToString();
}
private string DecimalPart(string number)
{
int numCut = number.IndexOf('.');
return number.Substring(numCut + 1);
}
private string WholePart(string number)
{
return ((int)Math.Floor(double.Parse(number))).ToString();
}
}
}
It's just a typo in your code:
finAns = (val2 + val2).ToString();
should be
finAns = (val1 + val2).ToString();
Note that val2 was added to val2 rather than val1 being added to val2.

Categories

Resources