Temp ArrayList to Master ArrayList with boolean && - processing

I'm looking to iterate through three lists(all the same length), get the values at the specified index, and compare them to a master list. And for the values that are not already in the master list, append the new values.
However, my boolean and statement never goes through.
FloatList master_X = new FloatList();
FloatList master_Y = new FloatList();
FloatList master_Z = new FloatList();
FloatList t_x = new FloatList();
FloatList t_y = new FloatList();
FloatList t_z = new FloatList();
FloatList checkedX = new FloatList();
FloatList checkedY = new FloatList();
FloatList checkedZ = new FloatList();
void tempToMaster(){
for(int i = 0; i < t_x.size();i++){
float x_t = (float)t_x.get(i);
float y_t = (float)t_y.get(i);
float z_t = (float)t_z.get(i);
for(int j = 0; j < master_X.size();j++){
float x_s = (float)master_X.get(j);
float y_s = (float)master_Y.get(j);
float z_s = (float)master_Z.get(j);
if ((x_t != x_s)&&(y_t != y_s)&&(z_t != z_s)){
print("helloWorld");
checkedX.append(x_t);
checkedY.append(y_t);
checkedZ.append(z_t);
}
}
}
for(int i = 0; i < checkedX.size();i++){
master_X.append(checkedX.get(i));
master_Y.append(checkedY.get(i));
master_Z.append(checkedZ.get(i));
}
checkedX.clear();
checkedY.clear();
checkedZ.clear();
t_x.clear();
t_y.clear();
t_z.clear();
}
should Print "Hello World" as well as append the values from the temp ArrayLists to the "checked" ArrayLists.
Boolean opperation never works.

I checked the code and it works, but you have to make sure the lists aren't empty.
This is because, when masterX is empty, masterX.size() is 0.
Therefore, the for loop doesn't even start, because 0 is not smaller than 0, and nothing gets added to the checked lists.
This code:
master_X.append(0);
master_Y.append(0);
master_Z.append(0);
t_x.append(1);
t_y.append(1);
t_z.append(1);
tempToMaster();
gives the expected result.
If you want it to work with empty master lists, first adding all temp lists to the checked lists and then removing all floats that are in a master list should work.
Edit: you also may want to look into hasValue() to check if a list contains a specific float.

Related

Best way to sort a list of lines for connectivity

I have a long list of lines in (possibly) random order. So basically:
struct Line
{
Vector StartPos;
Vector EndPos;
};
Now I'm looking for an efficient way to sort these lines so that they are sorted into spans. I.E. if line A's startpos matches Line B's endpos, it gets moved into the list immediately after line B. If nothing matches, it just goes to the end of the list to start a new span.
Right now I'm doing it brute force-- setting a flag variable if anything was changed, and if anything changed, sorting it again. This produces gigantically exponential iterations. Is there any faster way to optimize this so that I could conceivably keep the iterations down to listsize^listsize?
If you do not have lines that start or end at the same point maybe you can use dictionaries to reduce the look ups. Something like:
public class Line
{
public Point StartPos;
public Point EndPos;
public bool isUsed = false;
};
and then 1) create a dictionary with the key the endPos and the value the index of the element in you list, 2) for each element of the list follow the link using the dictionary. Something like:
List<List<Line>> result = new List<List<Line>>();
Dictionary<Point,int> dic= new Dictionary<Point,int>();
for (int kk = 0; kk < mylines.Count; kk++)
{
dic[mylines[kk].EndPos] = kk;
}
for (int kk = 0; kk < mylines.Count; kk++)
{
if (mylines[kk].isUsed == false)
{
var orderline= new List<Line>();
orderline.Add(mylines[kk]);
int mm = kk;
while (dic.ContainsKey(mylines[mm].EndPos))
{
mm = dic[mylines[mm].EndPos];
mylines[mm].isUsed = true;
orderline.Add(mylines[mm]);
}
result.Add(orderline);
}
}

CFSCRIPT - For loop increments the index wrong

I might have been found a bug in ColdFusion 2016.
I have two functions. The first one has a loop which iterates from 1 to n and pushes the return value of the second function which is also an array into an array. I noticed that;
index value is 1,
calling function and pushing the value into the array,
and index value is the end value of the loop.
Is this a bug?
<cfscript>
public array function fnc1(required array p1, required array p2, required numeric pSize, required numeric qSize, required numeric dSize){
iterationNum = pSize/2;
point = randRange(1, qSize-1);
for(i = 1; i <= iterationNum; i++){
writeOutput(i); // prints: 1
pop[i] = fnc2(p1[i], p2[i], point);
writeOutput(i); // prints: iterationNum value
writeDump(var = pop[i], label = "pop-"&i);
}
writeDump(var = pop, label="pop");
}
public array function fnc2(required array p1, required array p2, required numeric point){
n = arrayLen(p1);
concatArr = arrayNew(1);
for(i = 1; i <= point; i++){
concatArr[i] = p1[i];
}
for(i = point + 1; i <= n; i++){
concatArr[i] = p2[i];
}
writeDump(var=concatArr, label="Concated Array");
return concatArr;
}
</cfscript>
The default scope of a variable inside of a cfc is not function only. But rather it is cfc wide. This is often problematic.
Similarly, the default scope of a variable outside of a cfc is request wide. This is often useful.
Two approaches
There are two approaches to limit the scope of a variable inside of a cfc. One is to use the keyword var, the other is the use local.
It is a long story as to how they are different. The sample solution below uses var throughout. If you want to know more about var vs local., click here: Scoping: Local vs Var
<cfscript>
public array function fnc1(required array p1, required array p2, required numeric pSize, required numeric qSize, required numeric dSize){
var iterationNum = pSize/2;
var point = randRange(1, qSize-1);
for(var i = 1; i <= iterationNum; i++){
writeOutput(i); // prints: 1
pop[i] = fnc2(p1[i], p2[i], point);
writeOutput(i); // prints: iterationNum value
writeDump(var = pop[i], label = "pop-"&i);
}
writeDump(var = pop, label="pop");
}
public array function fnc2(required array p1, required array p2, required numeric point){
var n = arrayLen(p1);
var concatArr = arrayNew(1);
for(var i = 1; i <= point; i++){
concatArr[i] = p1[i];
}
for(var ii = point + 1; ii <= n; ii++){
concatArr[ii] = p2[ii];
}
writeDump(var=concatArr, label="Concated Array");
return concatArr;
}
</cfscript>

How to add settings to snake game(Processing)?

Im trying to add settings to a snake game made in processing. I want to have something like easy, normal and hard or something along the lines of that and change the speed and maybe size of the grid. If anyone coudl explain how to id greatly appreciate it!
ArrayList<Integer> x = new ArrayList<Integer>(), y = new ArrayList<Integer>();
int w = 30, h = 30, bs = 20, dir = 2, applex = 12, appley = 10;
int[] dx = {0,0,1,-1}, dy = {1,-1,0,0};
boolean gameover = false;
void setup() {
size(600,600);
x.add(5);
y.add(5);
}
void draw() {
background(255);
for(int i = 0 ; i < w; i++) line(i*bs, 0, i*bs, height); //Vertical line for grid
for(int i = 0 ; i < h; i++) line(0, i*bs, width, i*bs); //Horizontal line for grid
for(int i = 0 ; i < x.size(); i++) {
fill (0,255,0);
rect(x.get(i)*bs, y.get(i)*bs, bs, bs);
}
if(!gameover) {
fill(255,0,0);
rect(applex*bs, appley*bs, bs, bs);
if(frameCount%5==0) {
x.add(0,x.get(0) + dx[dir]);
y.add(0,y.get(0) + dy[dir]);
if(x.get(0) < 0 || y.get(0) < 0 || x.get(0) >= w || y.get(0) >= h) gameover = true;
for(int i = 1; i < x.size(); i++) if(x.get(0) == x.get(i) && y.get(0) == y.get(i)) gameover = true;
if(x.get(0)==applex && y.get(0)==appley) {
applex = (int)random(0,w);
appley = (int)random(0,h);
}else {
x.remove(x.size()-1);
y.remove(y.size()-1);
}
}
} else {
fill(0);
textSize(30);
text("GAME OVER. Press Space to Play Again", 20, height/2);
if(keyPressed && key == ' ') {
x.clear(); //Clear array list
y.clear(); //Clear array list
x.add(5);
y.add(5);
gameover = false;
}
}
if (keyPressed == true) {
int newdir = key=='s' ? 0 : (key=='w' ? 1 : (key=='d' ? 2 : (key=='a' ? 3 : -1)));
if(newdir != -1 && (x.size() <= 1 || !(x.get(1) ==x.get(0) + dx[newdir] && y.get (1) == y.get(0) + dy[newdir]))) dir = newdir;
}
}
You need to break your problem down into smaller steps:
Step one: Can you store the difficulty in a variable? This might be an int that keeps track of a level, or a boolean that switches between easy and hard. Just hardcode the value of that variable for now.
Step two: Can you write your code so it changes behavior based on the difficulty level? Use the variable you created in step one. You might use an if statement to check the difficulty level, or maybe the speed increases over time. It's completely up to you. Start out with a hard-coded value. Change the value to see different behaviors.
Step three: Can you programatically change that value? Maybe this requires a settings screen where the user chooses the difficulty, or maybe it gets more difficult over time. But you have to do the first two steps before you can start this step.
If you get stuck on a specific step, then post an MCVE and we'll go from there.

Algorithm ABBA(SRM 663, DIV 2, 500)

I am doing a problem from this blog
One day, Jamie noticed that many English words only use the letters A and B. Examples of such words include "AB" (short for abdominal), "BAA" (the noise a sheep makes), "AA" (a type of lava), and "ABBA" (a Swedish pop sensation).
Inspired by this observation, Jamie created a simple game. You are given two Strings: initial and target. The goal of the game is to find a sequence of valid moves that will change initial into target. There are two types of valid moves:
Add the letter A to the end of the string.
Reverse the string and then add the letter B to the end of the string.
Return "Possible" (quotes for clarity) if there is a sequence of valid moves that will change initial into target. Otherwise, return "Impossible".
My Questions:
My solution follows example steps: Firstly, reverse and append 'B', then append 'A'. I have no idea whether I need to use another order of the step(firstly, append 'A', then reverse and append 'B') at same time.
I got "ABBA" which should return "Possible", but "Impossible" was returned.
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(canContain("B","ABBA"));
}
public static String canContain(String Initial, String Target){
char[] target = new char[1000];
char[] initial1 = new char[1000];
int flag = 0;
boolean possible = false;
int InitialLength = Initial.length();
int TargetLength = Target.length();
System.out.println("Initial:");
int countInitial = -1;
for(char x : Initial.toCharArray()){
countInitial++;
if(x=='A')initial1[countInitial]='A';
if(x=='B')initial1[countInitial]='B';
System.out.print(x+"->"+initial1[countInitial]+" ");
}
int countTarget = -1;
System.out.println("\nTarget:");
for(char y : Target.toCharArray()){
countTarget++;
if(y=='A')target[countTarget]='A';
if(y=='B')target[countTarget]='B';
System.out.print(y+"->"+target[countTarget]+" ");
}
System.out.print("\n");
//Check Initial char[]
System.out.print("---------------");
System.out.print("\n");
for(int t1 = 0; t1 <= countInitial; t1++){
System.out.print(initial1[t1]+"-");
}
System.out.print("\n");
for(int t3 = 0; t3 <= countTarget; t3++){
System.out.print(target[t3]+"-");
}
while(countInitial != countTarget){
if(flag == 0 && Initial != Target){
System.out.println("\n_______A_______");
countInitial++;
System.out.println("countInitial = "+countInitial);
initial1[countInitial] = 'A';
System.out.println(initial1[countInitial]);
for(int t1 = 0; t1 <= countInitial; t1++){
System.out.print(initial1[t1]+"-");
}
flag = 1;
}else if(flag == 1 && Initial != Target){
System.out.println("\n_______R_+_B_______");
int ct = 0;
char[] temp = new char[1000];
for(int i = countInitial; i >= 0; i--){
System.out.println("countInitial = "+countInitial);
temp[ct] = initial1[i];
System.out.println("ct = "+ct);
ct++;
}
initial1 = temp;
countInitial++;
initial1[countInitial] = 'B';
for(int t1 = 0; t1 < countInitial; t1++){
System.out.print(initial1[t1]+"-");
}
flag = 0;
}
}
if(initial1.equals(target)){
return "Possible";
}else{
return "Impossible";
}
}
Your immediate problem is that you apply rules in the particular order. However it is not forbidden to use the same rule multiple times in a row. So to get the target string from the initial you need to inspect all possible sequences of rule applications. This is known as combinatorial explosion.
Problems like this is usually easier to solve working backwards. If the target string is xyzA it may only be obtained by rule 1 from xyz. If the target string is xyzB it may only be obtained by rule 2 from zyx. So in pseudocode,
while length(target) > length(initial)
remove the last letter from target
if removed letter is "B"
reverse target
if target == initial
print "Possible"
else
print "Impossible"
Of course, reversal doesn't have to be explicit.
Here's a solution which will run for a linear time O(n). The idea is that you start from the target string and try to revert the operations until you reach a string with the same length as the initial string. Then you compare these 2 strings. Here's the solution:
private static final char A = 'A';
private static final String POSSIBLE = "Possible";
private static final String IMPOSSIBLE = "Impossible";
public String canObtain(String initial, String target) {
if (initial == null ||
initial.trim().length() < 1 ||
initial.trim().length() > 999) {
return IMPOSSIBLE;
}
if (target == null ||
target.trim().length() < 2 ||
target.trim().length() > 1000) {
return IMPOSSIBLE;
}
return isPossible(initial, target) ? POSSIBLE : IMPOSSIBLE;
}
private boolean isPossible(String initial, String target) {
final StringBuilder sb = new StringBuilder(target);
while (initial.length() != sb.length()) {
char targetLastChar = sb.charAt(sb.length() - 1);
if (targetLastChar == A) {
unApplyA(sb);
} else {
unApplyRevB(sb);
}
}
return initial.equals(sb.toString());
}
private void unApplyA(StringBuilder sb) {
sb.deleteCharAt(sb.length() - 1);
}
private void unApplyRevB(StringBuilder sb) {
sb.deleteCharAt(sb.length() - 1);
sb.reverse();
}
A little late to the party but this is a concise solution in Python that runs in linear time:
class ABBA:
def canObtain(self, initial, target):
if initial == target:
return 'Possible'
if len(initial) == len(target):
return 'Impossible'
if target[-1] == 'A':
return self.canObtain(initial, target[:-1])
if target[-1] == 'B':
return self.canObtain(initial, target[:-1][::-1])

Find all permutation of a string with certain position unchanged

Given a String of words, say "OhMy", keep the uppercase letter fixed(unchanged) but we can change the position of lower case letter. Output all possible permutation.
eg. given "OhMy" it should output [ "OhMy", "OyMh"]
Here is what I did:
public static List<String> Permutation(String s){
List<String> res = new ArrayList<String>();
if (s == null || s.length() == 0){
return res;
}
StringBuilder path = new StringBuilder(s);
List<Character> candidates = new ArrayList<Character>();
List<Integer> position = new ArrayList<Integer>();
for (int i = 0; i < s.length(); i++){
char c = s.charAt(i);
if (Character.isAlphabetic(c) && Character.isLowerCase(c)){
candidates.add(c);
position.add(i);
}
}
boolean[] occurred = new boolean[candidates.size()];
helper(res, path, candidates, position, 0);
return res;
}
public static void helper(List<String> res, StringBuilder path, List<Character> candidates, List<Integer> position, int index){
if (index == position.size()){
res.add(path.toString());
return ;
}
for (int i = index; i < position.size(); i++){
for (int j = 0; j < candidates.size(); j++){
path.setCharAt(position.get(i), candidates.get(j));
char c = candidates.remove(j);
helper(res, path, candidates, position, index+1);
candidates.add(j, c);
}
}
}
for input "Abc"
it will have result [Abc, Acb, Acc, Acb]
Essentially, the outer loop is iterating every possible position, inner loop tries every possible candidates at each possible position.
I don't know why it has duplicates li "Acc, Acb"
It seems like the main point of your implicit question is how to efficiently enumerate all permutations of a given set, which you can read about online (there are several methods). If you can enumerate all permutations of the indices of lower case letters, then it's pretty straightforward to do book keeping and merge each permutation of lower case letters with the original unchanged set of upper case letters, respecting the positions of the upper case letters, so you can output your strings. If you're having difficultly with that part, update your question and someone should be able to help you out.

Resources