Write a JSON file with cubePosition Data to spawn a 10x10x10 cube - json

Here I'm trying to write a code that can write and create a JSON File for me with the data I provide like row, column and depth.
For example, I need to spawn a 10 x 10 x 10 cube. And I give this data in unity Inspector also in the code when I'm serializing it.
I tried achieving this in a for loop and writing the JSON file. But I'm not getting the output I wanted. I am expecting output where the cube locations are different and in place what happens instead is all the data or cube position in my data is the one before the number I give. that is if I gave my row, column, and depth to be 10. So my data is like x: 9, y: 9, z:9 for the whole 1000 elements.Better explained in image down below.I know I'm doing a mistake at some point just not able to figure out where. Thanks for the help in Advance
public class JSONWriter : MonoBehaviour
{
[SerializeField] int rows , columns, depth = 10;
[SerializeField] float padding;
public enum CubeType
{
white,
yellow,
blue,
red,
green
}
private readonly IReadOnlyDictionary<CubeType, Color> colors = new Dictionary<CubeType, Color>
{
{CubeType.white, Color.white},
{CubeType.yellow, Color.yellow},
{CubeType.blue, Color.blue},
{CubeType.red, Color.red},
{CubeType.green, Color.green}
};
[System.Serializable]
public class CubeData
{
public Vector3 cubePosition;
public CubeType Cube;
}
[System.Serializable]
public class CubeDataList
{
public CubeData[] cubeDatas;
}
public void outputJSON()
{
string strOutput = JsonUtility.ToJson(myCubeDataList);
File.WriteAllText(Application.dataPath + "/Resources/10x10x10.txt", strOutput);
}
//CubeData myCubeData = new CubeData();
public CubeDataList myCubeDataList = new CubeDataList();
void Start()
{
for (int x = 0; x < myCubeDataList.cubeDatas.Length; x++)
{
//Debug.Log(myCubeDataList.cubeDatas.Length);
for (int i = 0; i < depth; i++)
{
for (int j = 0; j < columns; j++)
{
for (int k = 0; k < rows; k++)
{
myCubeDataList.cubeDatas[x].cubePosition = new Vector3(i, j, k) * padding;
//myCubeDataList.cubeDatas[x].Cube = Random.Range(CubeType, 3f);
}
}
}
}
}
}

You do not want to go through all i, j, k for each and every element x!
What you are doing is basically overwriting each and every element with the values for i=9, j=9, k=9.
Instead of an array I would rather simply use a dynamic List like
[Serializable]
public class CubeDataList
{
public List<CubeData> cubeDatas;
}
and then dynamically add them via
myCubeDataList.cubeDatas = new List<CubeData>(i * j * k);
for (int i = 0; i < depth; i++)
{
for (int j = 0; j < columns; j++)
{
for (int k = 0; k < rows; k++)
{
var data = new CubeData();
data.cubePosition = new Vector3(i, j, k) * padding;
data.Cube = Random.Range(CubeType, 3f);
myCubeDataList.cubeDatas.Add(data);
}
}
}
Or if you really want to go with an array
for (int i = 0; i < depth; i++)
{
for (int j = 0; j < columns; j++)
{
for (int k = 0; k < rows; k++)
{
var data = new CubeData();
myCubeDataList.cubeDatas[x].cubePosition = new Vector3(i, j, k) * padding;
myCubeDataList.cubeDatas[x].Cube = Random.Range(CubeType, 3f);
x++;
}
}
}
Though, from your previous question I know you actually do not want to fill the cube completely!
You actually only want the external shape (like a wall) and leave the cube empty on the inside.
So what you actually want would probably rather be
myCubeDataList.cubeDatas = new List<CubeData>(i * j * k);
for (int i = 0; i < depth; i++)
{
for (int j = 0; j < columns; j++)
{
for (int k = 0; k < rows; k++)
{
if(i == 0 || i == depth - 1
|| j == 0 || j == depth - 1
|| k == 0 || k == depth - 1)
{
var data = new CubeData();
data.cubePosition = new Vector3(i, j, k) * padding;
// TODO random enum (see below)
myCubeDataList.cubeDatas.Add(data);
}
}
}
}
For the random enum vlaue see e.g. this answer and do
private Random random = new Random();
and then where it says // TODO insert
var values = Enum.GetValues(typeof(Bar));
data.Cube = (CubeType)values.GetValue(random.Next(values.Length));

Related

Adding Constraints in Google Apps Script Linear Optimization Service

I need to solve an assignment problem with Google Apps Script. The LinearOptimizationService seemed to be promising so what I tried is to port a corresponding example from the google or-tools .
Unfortunately, I couldn't find out a way how I set up the constraint that each worker is assigned to exactly one task.
The working code (without the constraint) is as follows:
function myFunction() {
// Create the variables
var engine = LinearOptimizationService.createEngine();
const costMatrix = [[7,5,4,8,3]
,[2,5,6,7,1]
,[2,8,9,5,2]
,[2,5,6,7,1]
,[2,8,1,5,9]]
const capacities = [1,1,1,1,1]
// initialize the decision variables
x = new Array(costMatrix.length);
for (let i=0; i<costMatrix.length; i++){
x[i] = new Array(costMatrix[0].length);
for (let j=0; j<costMatrix[0].length; j++){
x[i][j] = engine.addVariable(`x${i}${j}`, 0, 1, LinearOptimizationService.VariableType.INTEGER);
}
}
// Each worker is assigned to at most one task.
for (let i = 0; i < costMatrix.length; ++i) {
constraint = engine.addConstraint(0, 1);
for (let j = 0; j < costMatrix[0].length; ++j) {
constraint.setCoefficient(`x${i}${j}`, 1);
}
}
// Each task is assigned to exactly one worker.
for (let j = 0; j < costMatrix[0].length; ++j) {
constraint = engine.addConstraint(1, 1);
for (let i = 0; i < costMatrix.length; ++i) {
constraint.setCoefficient(`x${i}${j}`, 1);
}
}
for (let i = 0; i < costMatrix.length; ++i) {
for (let j = 0; j < costMatrix[0].length; ++j) {
engine.setObjectiveCoefficient(`x${i}${j}`, costMatrix[i][j]);
}
}
engine.setMinimization()
// Solve the linear program
var solution = engine.solve(30);
if (!solution.isValid()) {
throw 'No solution ' + solution.getStatus();
}
Logger.log('ObjectiveValue: ' + solution.getObjectiveValue());
for (let i=0; i<costMatrix.length; i++){
for (let j=0; j<costMatrix[0].length; j++){
Logger.log(`Value of: x${i}${j} ` + solution.getVariableValue(`x${i}${j}`));
}
}
}
Any help is appreciated.
Thanks

ActionScript How to access child Sprites

I have the following problem. Would appreciate if someone takes the pains to answer it.
Problem Description: I have a top level Sprite "TopLevel",
there is a Sprite under it "allRoutes",
there is child Sprite under it "Routes" and
there is another child under it "Route".
I want to access each level in a loop. I have tried doing it in ActionScript but not with success.
Here is the probable code (it is not compiled successfully):
package
{
import flash.display.Sprite;
public class TopLevel extends Sprite {
public function TopLevel() {
var allRoutes:Sprite = new Sprite();
for (i = 0; i < 3; i++) {
var routes:Sprite = new Sprite();
for (j = 0; j < 4; j++) {
var route:Sprite = new Sprite();
route.name = "Route:" + i + ", " j;
routes.addChild(route);
}
routes.name = "Routes:" + i;
allRoutes.name = "AllRoutes";
allRoutes.addChild(routes);
}
addChild(allRoutes);
trace (allRoutes.name);
for (i = 0; i < allRoutes.numChildren; i++) {
trace(allRoutes.getChildAt(i).name);
for (j = 0; j < allRoutes.getChildAt(i).numChildren; j++) {
trace(allRoutes.getChildAt(i).getChildAt(j).name);
}
}
}
}
}
I am expecting the following result:
AllRoutes
Routes-1
Route-1, 1
Route-1, 2
Route-1, 3
Route-1, 4
Routes-2
Route-2, 1
Route-2, 2
Route-2, 3
Route-2, 4
so on..
Hope you get the picture.
Thank you very much in advance.
thanks and regards
rr23850
Globally your code is fine, except some little things :
You forgot to declare i and j variables :
var i:int, j:int;
You forgot the concatenation operator before j in this line :
route.name = "Route:" + i + ", " + j;
If your are compiling with the strict mode, these instructions will fire errors :
allRoutes.getChildAt(i).numChildren
and
allRoutes.getChildAt(i).getChildAt(j).name
which can be in that case :
for (j = 0; j < Sprite(allRoutes.getChildAt(i)).numChildren; j++)
{
trace(Sprite(allRoutes.getChildAt(i)).getChildAt(j).name);
}
...
And as your for loops are starting by 0, you will get something like this :
AllRoutes
Routes:0
Route:0, 0
Route:0, 1
Route:0, 2
Route:0, 3
Routes:1
Route:1, 0
Route:1, 1
...
Hope that can help.

Extra 0 in starting of the output of decimal to binary code conversion

I seem to have a problem in the output of my code (A decimal to binary conversion code). If I enter a number, for example 12, it'll output 01100. I just want it to output 1100 (without the 0 in the very first). Is there something that I may have missed?
Thank you in advance! Here is my code below :
import java.util.*;
public class DtoB{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = in.nextInt();
int i;
int j;
int[] binary = new int[10];
if ( number > 0 ){
for (i = 0; number != 0; i++){
binary[i] = number % 2;
number /= 2;
}
for ( j = i; j >= 0; j-- ){
System.out.print(binary[j]);
}
System.out.print(" is the binary conversion of your integer.");
} else {
System.out.print("Error: You have not entered a positive integer.");
}
}
}
Initialize j with i-1
for ( j = i-1; j >= 0; j-- ){
System.out.print(binary[j]);
}

Adding indexes in array

I am adding two matrices (or possibly many) in ActionScript 3.0.
Now my problem is how can I add indexes in array that is something like this?
array1[1,2,3,4] + array2[2,4,5,6] = answer[3,6,8,10]
This function adds up all the arrays that are passed to it:
function sumOfArrays(...args):Array
{
var sum:Array = [];
var arrays:Array = [];
var longestArrayLength:uint = 0;
for (var i:int = 0, n:int = args.length; i < n; i++)
{
if (args[i] is Array)
{
arrays.push(args[i]);
longestArrayLength = args[i].length > longestArrayLength ? args[i].length : longestArrayLength;
}
}
for (var j:int = 0; j < longestArrayLength; j++)
{
sum[j] = 0;
for (i = 0; i < n; i++)
{
sum[j] += isNaN(arrays[i][j]) ? 0 : arrays[i][j];
}
}
return sum;
}
It can be used like this:
var sum:Array = sumOfArrays(array1, array2);
That's not possible. Arrays only allows access via one index. You'd have to write a method on your own for this. But be aware of the fact, that null would be referenced on answer at, 0, 1, 2, 4, 5 and so on.

How would you calculate all possible permutations of 0 through N iteratively?

I need to calculate permutations iteratively. The method signature looks like:
int[][] permute(int n)
For n = 3 for example, the return value would be:
[[0,1,2],
[0,2,1],
[1,0,2],
[1,2,0],
[2,0,1],
[2,1,0]]
How would you go about doing this iteratively in the most efficient way possible? I can do this recursively, but I'm interested in seeing lots of alternate ways to doing it iteratively.
see QuickPerm algorithm, it's iterative : http://www.quickperm.org/
Edit:
Rewritten in Ruby for clarity:
def permute_map(n)
results = []
a, p = (0...n).to_a, [0] * n
i, j = 0, 0
i = 1
results << yield(a)
while i < n
if p[i] < i
j = i % 2 * p[i] # If i is odd, then j = p[i], else j = 0
a[j], a[i] = a[i], a[j] # Swap
results << yield(a)
p[i] += 1
i = 1
else
p[i] = 0
i += 1
end
end
return results
end
The algorithm for stepping from one permutation to the next is very similar to elementary school addition - when an overflow occurs, "carry the one".
Here's an implementation I wrote in C:
#include <stdio.h>
//Convenience macro. Its function should be obvious.
#define swap(a,b) do { \
typeof(a) __tmp = (a); \
(a) = (b); \
(b) = __tmp; \
} while(0)
void perm_start(unsigned int n[], unsigned int count) {
unsigned int i;
for (i=0; i<count; i++)
n[i] = i;
}
//Returns 0 on wraparound
int perm_next(unsigned int n[], unsigned int count) {
unsigned int tail, i, j;
if (count <= 1)
return 0;
/* Find all terms at the end that are in reverse order.
Example: 0 3 (5 4 2 1) (i becomes 2) */
for (i=count-1; i>0 && n[i-1] >= n[i]; i--);
tail = i;
if (tail > 0) {
/* Find the last item from the tail set greater than
the last item from the head set, and swap them.
Example: 0 3* (5 4* 2 1)
Becomes: 0 4* (5 3* 2 1) */
for (j=count-1; j>tail && n[j] <= n[tail-1]; j--);
swap(n[tail-1], n[j]);
}
/* Reverse the tail set's order */
for (i=tail, j=count-1; i<j; i++, j--)
swap(n[i], n[j]);
/* If the entire list was in reverse order, tail will be zero. */
return (tail != 0);
}
int main(void)
{
#define N 3
unsigned int perm[N];
perm_start(perm, N);
do {
int i;
for (i = 0; i < N; i++)
printf("%d ", perm[i]);
printf("\n");
} while (perm_next(perm, N));
return 0;
}
Is using 1.9's Array#permutation an option?
>> a = [0,1,2].permutation(3).to_a
=> [[0, 1, 2], [0, 2, 1], [1, 0, 2], [1, 2, 0], [2, 0, 1], [2, 1, 0]]
Below is my generics version of the next permutation algorithm in C# closely resembling the STL's next_permutation function (but it doesn't reverse the collection if it is the max possible permutation already, like the C++ version does)
In theory it should work with any IList<> of IComparables.
static bool NextPermutation<T>(IList<T> a) where T: IComparable
{
if (a.Count < 2) return false;
var k = a.Count-2;
while (k >= 0 && a[k].CompareTo( a[k+1]) >=0) k--;
if(k<0)return false;
var l = a.Count - 1;
while (l > k && a[l].CompareTo(a[k]) <= 0) l--;
var tmp = a[k];
a[k] = a[l];
a[l] = tmp;
var i = k + 1;
var j = a.Count - 1;
while(i<j)
{
tmp = a[i];
a[i] = a[j];
a[j] = tmp;
i++;
j--;
}
return true;
}
And the demo/test code:
var src = "1234".ToCharArray();
do
{
Console.WriteLine(src);
}
while (NextPermutation(src));
I also came across the QuickPerm algorithm referenced in another answer. I wanted to share this answer in addition, because I saw some immediate changes one can make to write it shorter. For example, if the index array "p" is initialized slightly differently, it saves having to return the first permutation before the loop. Also, all those while-loops and if's took up a lot more room.
void permute(char* s, size_t l) {
int* p = new int[l];
for (int i = 0; i < l; i++) p[i] = i;
for (size_t i = 0; i < l; printf("%s\n", s)) {
std::swap(s[i], s[i % 2 * --p[i]]);
for (i = 1; p[i] == 0; i++) p[i] = i;
}
}
I found Joey Adams' version to be the most readable, but I couldn't port it directly to C# because of how C# handles the scoping of for-loop variables. Hence, this is a slightly tweaked version of his code:
/// <summary>
/// Performs an in-place permutation of <paramref name="values"/>, and returns if there
/// are any more permutations remaining.
/// </summary>
private static bool NextPermutation(int[] values)
{
if (values.Length == 0)
throw new ArgumentException("Cannot permutate an empty collection.");
//Find all terms at the end that are in reverse order.
// Example: 0 3 (5 4 2 1) (i becomes 2)
int tail = values.Length - 1;
while(tail > 0 && values[tail - 1] >= values[tail])
tail--;
if (tail > 0)
{
//Find the last item from the tail set greater than the last item from the head
//set, and swap them.
// Example: 0 3* (5 4* 2 1)
// Becomes: 0 4* (5 3* 2 1)
int index = values.Length - 1;
while (index > tail && values[index] <= values[tail - 1])
index--;
Swap(ref values[tail - 1], ref values[index]);
}
//Reverse the tail set's order.
int limit = (values.Length - tail) / 2;
for (int index = 0; index < limit; index++)
Swap(ref values[tail + index], ref values[values.Length - 1 - index]);
//If the entire list was in reverse order, tail will be zero.
return (tail != 0);
}
private static void Swap<T>(ref T left, ref T right)
{
T temp = left;
left = right;
right = temp;
}
Here's an implementation in C#, as an extension method:
public static IEnumerable<List<T>> Permute<T>(this IList<T> items)
{
var indexes = Enumerable.Range(0, items.Count).ToArray();
yield return indexes.Select(idx => items[idx]).ToList();
var weights = new int[items.Count];
var idxUpper = 1;
while (idxUpper < items.Count)
{
if (weights[idxUpper] < idxUpper)
{
var idxLower = idxUpper % 2 * weights[idxUpper];
var tmp = indexes[idxLower];
indexes[idxLower] = indexes[idxUpper];
indexes[idxUpper] = tmp;
yield return indexes.Select(idx => items[idx]).ToList();
weights[idxUpper]++;
idxUpper = 1;
}
else
{
weights[idxUpper] = 0;
idxUpper++;
}
}
}
And a unit test:
[TestMethod]
public void Permute()
{
var ints = new[] { 1, 2, 3 };
var orderings = ints.Permute().ToList();
Assert.AreEqual(6, orderings.Count);
AssertUtil.SequencesAreEqual(new[] { 1, 2, 3 }, orderings[0]);
AssertUtil.SequencesAreEqual(new[] { 2, 1, 3 }, orderings[1]);
AssertUtil.SequencesAreEqual(new[] { 3, 1, 2 }, orderings[2]);
AssertUtil.SequencesAreEqual(new[] { 1, 3, 2 }, orderings[3]);
AssertUtil.SequencesAreEqual(new[] { 2, 3, 1 }, orderings[4]);
AssertUtil.SequencesAreEqual(new[] { 3, 2, 1 }, orderings[5]);
}
The method AssertUtil.SequencesAreEqual is a custom test helper which can be recreated easily enough.
How about a recursive algorithm you can call iteratively? If you'd actually need that stuff as a list like that (you should clearly inline that rather than allocate a bunch of pointless memory). You could simply calculate the permutation on the fly, by its index.
Much like the permutation is carry-the-one addition re-reversing the tail (rather than reverting to 0), indexing the specific permutation value is finding the digits of a number in base n then n-1 then n-2... through each iteration.
public static <T> boolean permutation(List<T> values, int index) {
return permutation(values, values.size() - 1, index);
}
private static <T> boolean permutation(List<T> values, int n, int index) {
if ((index == 0) || (n == 0)) return (index == 0);
Collections.swap(values, n, n-(index % n));
return permutation(values,n-1,index/n);
}
The boolean returns whether your index value was out of bounds. Namely that it ran out of n values but still had remaining index left over.
And it can't get all the permutations for more than 12 objects.
12! < Integer.MAX_VALUE < 13!
-- But, it's so very very pretty. And if you do a lot of things wrong might be useful.
I have implemented the algorithm in Javascript.
var all = ["a", "b", "c"];
console.log(permute(all));
function permute(a){
var i=1,j, temp = "";
var p = [];
var n = a.length;
var output = [];
output.push(a.slice());
for(var b=0; b <= n; b++){
p[b] = b;
}
while (i < n){
p[i]--;
if(i%2 == 1){
j = p[i];
}
else{
j = 0;
}
temp = a[j];
a[j] = a[i];
a[i] = temp;
i=1;
while (p[i] === 0){
p[i] = i;
i++;
}
output.push(a.slice());
}
return output;
}
I've used the algorithms from here. The page contains a lot of useful information.
Edit: Sorry, those were recursive. uray posted the link to the iterative algorithm in his answer.
I've created a PHP example. Unless you really need to return all of the results, I would only create an iterative class like the following:
<?php
class Permutator implements Iterator
{
private $a, $n, $p, $i, $j, $k;
private $stop;
public function __construct(array $a)
{
$this->a = array_values($a);
$this->n = count($this->a);
}
public function current()
{
return $this->a;
}
public function next()
{
++$this->k;
while ($this->i < $this->n)
{
if ($this->p[$this->i] < $this->i)
{
$this->j = ($this->i % 2) * $this->p[$this->i];
$tmp = $this->a[$this->j];
$this->a[$this->j] = $this->a[$this->i];
$this->a[$this->i] = $tmp;
$this->p[$this->i]++;
$this->i = 1;
return;
}
$this->p[$this->i++] = 0;
}
$this->stop = true;
}
public function key()
{
return $this->k;
}
public function valid()
{
return !$this->stop;
}
public function rewind()
{
if ($this->n) $this->p = array_fill(0, $this->n, 0);
$this->stop = $this->n == 0;
$this->i = 1;
$this->j = 0;
$this->k = 0;
}
}
foreach (new Permutator(array(1,2,3,4,5)) as $permutation)
{
var_dump($permutation);
}
?>
Note that it treats every PHP array as an indexed array.