I'm trying to pick a random element from an array with exceptions.
For example let's say I have a boolean array with length 10, 2 of these are set to true at a random index. How can I select a random false boolean and set it to true?
I hope this isn't too vague, English isn't my first language.
There are a ton of ways to do this. Two main approaches that occur to me:
You could use a while loop that picked a random index until it found one that was false:
boolean[] array = {false, true, false};
int index = int(random(array.length));
while(array[index]){
index = int(random(array.length));
}
Or you could create a new array (or ArrayList) from just the indexes that are false, then randomly pick from that array:
boolean[] array = {false, true, false};
ArrayList<Integer> indexes = new ArrayList<Integer>();
for(int i = 0; i < array.length; i++){
if(!array[i]){
indexes.add(i);
}
}
int index = indexes.get(int(random(indexes.size())));
Note that you've tagged your question with the processing tag, so I'm using Processing syntax here. But these approaches are valid in a general sense as well.
Related
So, what I am trying to do is a three in a row game, and so far I have managed to make it work, but I am struggling a bit when it comes to getting a winner, since I need to check that all the elements of either a row, a column or a diagonal are the same.
So far I have managed to get it to kinda work by using a boolean, a counter and a for loop. Here is an example of how my code looks
//Code to check the rows horizontally
public void checkH(){
int cont1 = 0;
Boolean winner1 = false;
for(int i=0;i<size;i++){
if(a[0][i]==1 || a[1][i]==1 || a[2][i]==1){
cont1++;
if(cont1==3){
winner1 = true;
}
So, as y'all can see what I am doing in that code is telling the program that if the array in either one of the rows is equal to one and if that same case happens when it goes through all the positions in the row, then the counter is going to add plus one, and once the counter hits 3, the boolean will be true and there will be a winner, but here is the catch: if, for example, the 2D array looks like this:
int a[][] = {{1,0,0},
{1,1,0},
{0,0,0}};
then the counter is still hitting three, even though they are not aligned. I know I havent specified that kind of condition in the program, but that's what I am struggling with. What I would like to do is to be able to make that condition with loops, so that I dont have to fill the whole thing with if statements.
Any leads you guys could give me on this would be highly appreciated. Thanks in advance!
If you are finding it difficult to search for a solution/tutorial on the web, notice that the three in a row game is also called tic-tac-toe. So, if you search for "tic tac toe algorithm" you will find several examples on how to solve it, as it is a somewhat usual interview question. Here is a reference for the reader’s convenience.
Now, for the desire to use for loops instead of chained ifs (or an if with multiple logical comparisons), it is a question about row-wise, column-wise and diagonal-wise traversal of a matrix. Here is a reference for the row and column traversals, and here is another reference for the diagonal traversal.
Specific to your question, below is a pseudo-code showing the check for column and row using for and the cell values to have a small number of if statements. But please notice this is just an example, as there are many interesting ways to solve a tic-tac-toe game that you may want to take a look, from traversing trees to using a string and regex.
public bool checkRow() {
int i, j;
int count = 0;
// accessing element row wise
for (i = 0; i < MAX; i++) {
for (j = 0; j < MAX; j++) {
// Considering we were checking for 1
// And array can have 0 or 1
// You can add the cell value and avoid an if
count += arr[i][j];
// if you go with arr[j][i] you will be traversing the columns and not the rows.
}
// if all cells in the row are 1, we have a winner
if(count == MAX)
return true;
}
return false
}
so I have this question in C:
Given an array that only contains 0's and 1's (Example: [1,1,0,0,0,0,1,0,1,0,1,1]).
I need to find the start of a "ring interval" and the finish of the same "ring interval" (there could be many rings like that, we'll have to store the start and finish of each one in a matrix of 2 columns)
"Silence" is when at least two 0's are next to each other. (in the given array, the sub array [0,0,0,0] is silent.
"Ring interval" is when Silence doesn't occur. (example in the given array, the sub array [1,1] (first 2 values), and the sub array [1,0,1,0,1,1] (the end of the array)).
So we'll have to store [0,1] in the first row of the matrix.
then [6,11]. since the second sub array starts at the 6th index and ends at the 11th.
I can't seem to describe it any better, it's in a different language and quite a bit more complicated than this.. i hope you understand!
Examples:
Array = [0,0,0,0,1,0,1,1,1,0,0,0,1,0,0]
Matrix would be : [4,8] [12,12]
Array = [1,0,0,1,1]
Matrix would be : [0,0] [3,4]
Thank you!
I have a simple algorithm for this that you can quite easily translate to C with a bit of research. You could also translate it to basically any other language as well:
Step 1) create two boolean values. One will be true if there is currently a "silence", the other will be true if the last value seen was a zero. Both of these should be true. If we do not assume that there are infinite zeros before the first element of the array, then there will be problems if the first number in the array is zero.
Step 2) loop over the array and check against one of 2 conditions: a) If you see a 1, set silence to false, previousZero to false. If this 1 breaks a silence, store this value as it is the beginning of your next range. b) If the value is zero and there is not a silence, set previousZero to true. If previousZero was already true, you have reached a silence, so set silence to true and store your beginning position and end position in your output array. Your end position in this situation would be the current position -2 to account for the zeros you just examined
Step 3) once you've looped through the entire array, you need to make sure you didn't end on a valid range. if silence is false, you know you ended on a valid range. store this range in your output array by using the begin value you stored in your loop and the end of the array as the end value.
This algorithm runs in linear time. Here is some pseudo-code to get you started on your implementation in C or whatever you choose.
findRing(Array arr)
bool silence = true, previousZero = true;
int currentBegin = 0, currentEnd = 0;
for( int i = 0; i<arr.length; i++) {
if(arr[i] == 1)
if(silence == true)
currentBegin = i;
silence = false;
previousZero = false;
else if(arr[i] == 0 && silence == false)
if(previousZero)
silence = true;
currentEnd = 1-2;
addToOutput(currentBegin, currentEnd);
else
previousZero = true;
}
if(silence == false)
currentEnd = arr.length - 1;
addToOutput(currentBegin, currentEnd);
I implemented this pseudo-code in C++ and got the same outputs you provided in your examples. It should be easy to implement in C or Matlab as you mentioned and runs in O(n) time.
I was asked question in interview ,write an algorithm to find middle element of array when you don't know size of array.
Is it cheating to count the elements yourself?
Java:
Object [] mysteriousArray = getMysteriousArray();
int count = 0;
for (Object value: mysteriousArray) {
count++;
}
Object middle = mysteriousArray[count/2];
For Java:
int[] array = new int[/*mystery value*/];
The statement array[(int)((array.length-1)/2)] will return the middle value, rounding down.
I have an array of N elements containing only two distinct keys, true and false. I am trying to write an O(N) algorithm to rearrange the list so that all false elements precede the true elements. A specific requirement for this algorithm is that I can only traverse the array once (meaning I can NOT make two traversals over the array; once to count the number of true/false's and another time to assign values into the array). I am also not allowed to create an external temporary array.
Originally I wanted to use counting sort, but realized I could not do this since the requirement for this assignment is that I cannot create an external/temporary array.
Then, since there are only two possible values, I wanted to iterate through once and count them. Then Iterate through a second time and set the ordering (do the sort). However, I cannot do this either because I am only allowed to do one iteration.
So I am on my own trying to implement an algorithm that will iterate only once through the array and sort at the same time. So far what I have come up with is below (this is just an idea written more or less as pseudocode)
array = T T T T F F F F
int len = length of array.
counter = 0
For item in array
counter += 1
If counter <= len/2
if T change to F
else
if F change to T
Right as I completed this, I realized that this only works when all the T values are on one side of the array, and all the F values are on the other.
My question is, can somebody tell me which O(n) sorting algorithm I can use to sort through each item in the array and arrange it so that all of the false elements precede the true?
You can try the idea of the quick sort: walk through the array from the start and the end at the same time, and swap elements that have incorrect order. I.e. if you found true in the left half of the array, swap it with false in the right half.
Cause you have only 2 different values it's enough the single pass.
Example:
bool[] array = ...;
int low = 0;
int high = array.Length - 1;
do
{
while (array[low] == false)
low++;
while (array[high] == true)
high--;
if (low <= high)
{
bool temp = array[low];
array[low] = array[high];
array[high] = temp;
}
}
while (low < high);
This gives you exactly single pass, i.e. O(N).
Keep an index (lastFalseIdx) where to insert a False element. So, initially it is 0. Traverse the array from left to right, and if False found, swap it with element at lastFalseIdx, and increment the index.
Python (almost pseudo-code):
arr = [True, True, False, False, False, True]
print arr
lastFalseIdx = 0
for idx, val in enumerate(arr):
if val == False:
arr[lastFalseIdx], arr[idx] = arr[idx], arr[lastFalseIdx] # swap elements
lastFalseIdx = lastFalseIdx + 1
print arr
Demo
Here is a partial solution that constructs the correct output in a separate array. You can infer an inline implementations by observing what happens when you initialize output = input instead.
#!/usr/bin/python
input = [False, True, False, False, True, True, False, True, False]
def sort2(input):
i_false = 0
i_true = len(input) - 1
output = [None] * len(input)
for (i, val) in enumerate(input):
if val:
output[i_true] = True
i_true -= 1
else:
output[i_false] = False
i_false += 1
return output
print sort2(input)
After a single forward pass through the array, you have the desired output.
Concisely:
swap = 0
for index in range(len(list)):
if list[index] != true:
list[index], list[swap] = list[swap], list[index]
swap += 1
hope the below answer helps.
internal void ArrangeBooleanArray()
{
bool[] inputArray = {false, true, true, false};
int arrayLength = inputArray.Length;
bool[] outputArray = new bool[arrayLength];
int trueCount = 0;
int falseCount = 0;
foreach (var item in inputArray)
{
if (item == true)
{
trueCount++;
outputArray[arrayLength - trueCount] = item;
}
else
{
outputArray[falseCount] = item;
falseCount++;
}
}
}
This is NOT about min/max values!
I use Array with all kinds of indices like 0, 1, 2, 1000, -1, -100. Yes, negative indices (I like this feature and I'm thankful for it.). The problem is I need them to be negative otherwise I would have to move all items. Now I wonder how can I retrieve the min index like -100. Most elements between min and max index would be undefined.
var a: Array = new Array();
a[-100] = "hello";
a.forEach(...); // starts with 0
Is there a simple way to get min index ?
No, there is no simple way to get the minimum index of the negative keys. You would have to loop through all the keys, convert them to numbers, and get the lowest.
The reason for that is that you are using the array both as an array and as an object. The array only has items with positive indexes, when you assign anything to it using a negative index, it's instead added as a property to the array object, not as an item in the array.
The forEach method loops through the items in the array, so it will only access the positive indexes. The data that you added using negative indexes are not array items, they are properties of the array object. So, it's not a bug that the forEach method starts from index 0.
If you want to loop through everything that you stored in the array, you can loop through its properties, then you will get both the object properties and array items:
for (i in a) {
// Here i is the key, and a[i] is the value
}
It's true that you can have negative indices in AS3 Arrays. The problem (and it's quite a serious one) is that none of the Array methods recognise the negative indices - they only recognise whole numbers.
For example:
var my_array:Array = new Array();
var my_array[-100] = "hello";
trace(my_array[-100]) // hello
trace(my_array.length) // 0
trace(my_array) // [empty]
So standard iteration through the array can only be done with absolute references to the index. Or by treating the array as an Object when looping:
var lowest:int = -100000 /* some deep number */
for(var i in a){
if(int(i) < lowest){
lowest = int(i);
}
}