How to get the elements of an array in B4A? - basic4android

I have this code but it seems that the "randomChar" is unused variable.
Dim validchars(3) As String
Dim i As Int
validchars(0) ="+"
validchars(1) ="-"
validchars(2) ="*"
Dim idx As Int = Rnd(0, validchars.Length)
Dim randomChar As String = validchars(idx)

Hi Do you mean you are getting a compiler warning?
If so and your code works then ignore it otherwise you could try
setting the valid chars as one string and then substring2 the one you ant to reference.

Array index starts from zero (0) so if the random ie idx generates 3 technically it should be 2 in your array so with your current code, it will give error since 3 will not exist.
valid chars and their Array indexes
(+ index is 0, - index is 1, * index is 2)
Fix subtract 1 from the idx, and also start the Rnd from 1
Dim idx As Int = Rnd(1, validchars.Length)
Dim randomChar As String = validchars(idx - 1)
in this case if the idx(ie Random Generated number is 3, with the minus 1 it will equal 2 which is * and likewise if idx is 1 - 1 will be zero which is +

You will get a compiler warning (unused variable 'randomChar'), which you can ignore.
Rnd(min,max) goes from min (inclusive) to max (exclusive), so
Dim Int idx = Rnd(0,validchars.Length)
the idx will go from 0 to (validchars.length-1). The following array access will always be valid. Your code will never crash.

Related

Why do we have to write -1 after .count in this Swift code?

In the following Swift code:
self.numbers[2] = Int.random(in: 0...self.symbols.count-1)
Why do we have to write -1?
I don't understand the code.
When you are using A...B, that range includes B in it. See ...(_:_:) docs. So if you say -
Int.random(in: 0...self.symbols.count-1)
It means range starts at 0 and ends at symbols.count-1 including both.
Say an array has 2 elements, it's count is 2, but valid indices are 0, 1 (2 is not a valid index), so you are just making sure that it is restricted to valid index values.
Other way to write the same would be - A..<B, in this range, B is not included. See ..<(_:_:) docs. Following is same as above.
Int.random(in: 0..<self.symbols.count)
You are using ClosedRange here. It is a range which includes both start and end value of the range. You can also used simple Range, which is open so to say. It only includes start value and not the final value.
Lets take an example.
let a = 1 ... 10 // includes all values from 1 to 10
let b = 1 ..< 10 // includes values from 1 to 9
So, basically what you are writing here,
self.numbers[2] = Int.random(in: 0 ... self.symbols.count - 1)
is equivalent to open range using,
self.numbers[2] = Int.random(in: 0 ..< self.symbols.count)
such that you dont need to add -1 to it.
Int.random can take both ClosedRange and Range, here and here.
Here are your code:
self.numbers[2] = Int.random(in: 0...self.symbols.count-1)
It says: your third item in numbers array will be assigned by the random item of symbols array
But how to get the random item of symbols array? You'll get it by its index.
The indexes of an array starting from 0, so, for the last element of array, its index will be the array length - 1, for example, with [1,2,3], the last element's index will be 2.
Here, you used Closed Range, it will include the last element, so if you don't minus count by one, the last index will be 3 (because array.count will return the length of the array), which is produce out of index error

count number of elements with a specific value in a field of a structure in Matlab

I have a structure myS with several fields, including myField, which in turns includes several other fields such as BB. I need to count how many time *'R_value' appears in BB.
I have tried:
sum(myS.myField.BB = 'R_value')
and this:
count = 0;
for i = 1:numel(myS.myField)
number_of_element = numel(myS.myField(i).BB)=='R_value'
count = count+number_of_element;
end
but it doesn't work. Any suggestion?
If you are just checking if BB is that literal string, then your loop is just:
count = 0;
for i = 1:numel(myS.myField)
count = count+strcmp(myS.myField(i).BB,'R_value')
end
numel counts how many elements are. Zero is an element. so is False. Just sum the array.
count = 0;
for i = 1:numel(myS.myField)
number_of_element = sum(myS.myField(i).BB==R_value)
count = count+number_of_element;
end
Also note you had the parenthesis wrong, so you where counting how many BB where in total, then comparing that number to R_value. I am assuming R_value is a number.
e.g.:
myS.myField(1).BB=[1 2 3 4 1 1 1]
myS.myField(2).BB=[4 5 65 1]
R_value=1

Assigning a value to the pointer to an object

class Distance
{
public:
int a;
};
int main()
{
Distance d1; //declaring object
char *p=(char *)&d1;
*p=1;
printf("\n %d ",d1.a);
return 0;
}
This is my code.
When I am passing the value of 'a' to be like 256,512 , I am getting 257,513 respectively but for values like 1000 i get 769 and for values like 16,128,100 I am getting 1.
First I thought it might be related to powers of 2 being incremented by 1 due to changes in their binary representation. But adding 1 to binary representation of 1000 won't give me 769.
Please help me to understand this code.
*p = 1 sets the last byte(char) to 000000001
As you're type casting int to char,
binary for (int)1000 is (binary)0000001111101000
you're assigning (int)1 for last 8 bits i,e (binary)0000001100000001 which is 769.
Using 256512 worked because last 8 bit that you change are all zeros i.e (int)256512 is (binary)111110101000000000 so making last bit as 1 gives you (binary)111110101000000001 which is (int)256513
And I think(not sure) you get 1 for 16,128,100 because this integer is well out of int range and thus not assigned and a is set to 0 as class object is created. and thus setting last bit to 1 makes a = 1

How to convert string to integer in JES

I am trying to do an assignment in JES a student jython program. I need to convert our student number taken as a string input variable to pass through our function i.e.
def assignment(stringID) and convert it into integers. The exact instructions are:
Step 1
Define an array called id which will store your 7 digit number as integers (the numbers you set in the array does not matter, it will be over written with your student number in the next step).
Step 2 Your student number has been passed in to your function as a String. You must separate the digits and assign them to your array id. This can do this manually line by line or using a loop. You will need to type cast each character from stringID to an integer before storing it in id.
I have tried so many different ways using the int and float functions but I am really stuck.
Thanks in advance!
>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545
I had to do some jython scripting for a websphere server. It must be a really old version of python it didn't have the ** operator or the len() function. I had to use an exception to find the end of a string.
Anyways I hope this saves someone else some time
def pow(x, y):
total = 1;
if (y > 0):
rng = y
else:
rng = -1 * y
print ("range", rng)
for itt in range (rng):
total *= x
if (y < 0):
total = 1.0 / float(total)
return total
#This will return an int if the percision restricts it from parsing decimal places
def parseNum(string, percision):
decIndex = string.index(".")
total = 0
print("decIndex: ", decIndex)
index = 0
string = string[0:decIndex] + string[decIndex + 1:]
try:
while string[index]:
if (ord(string[index]) >= ord("0") and ord(string[index]) <= ord("9")):
times = pow(10, decIndex - index - 1)
val = ord(string[index]) - ord("0")
print(times, " X ", val)
if (times < percision):
break
total += times * val
index += 1
except:
print "broke out"
return total
Warning! - make sure the string is a number. The function will not fail but you will get strange and almost assuredly, useless output.

how can I count the number of set bits in a uint in specman?

I want to count the number of set bits in a uint in Specman:
var x: uint;
gen x;
var x_set_bits: uint;
x_set_bits = ?;
What's the best way to do this?
One way I've seen is:
x_set_bits = pack(NULL, x).count(it == 1);
pack(NULL, x) converts x to a list of bits.
count acts on the list and counts all the elements for which the condition holds. In this case the condition is that the element equals 1, which comes out to the number of set bits.
I don't know Specman, but another way I've seen this done looks a bit cheesy, but tends to be efficient: Keep a 256-element array; each element of the array consists of the number of bits corresponding to that value. For example (pseudocode):
bit_count = [0, 1, 1, 2, 1, ...]
Thus, bit_count2 == 1, because the value 2, in binary, has a single "1" bit. Simiarly, bit_count[255] == 8.
Then, break the uint into bytes, use the byte values to index into the bit_count array, and add the results. Pseudocode:
total = 0
for byte in list_of_bytes
total = total + bit_count[byte]
EDIT
This issue shows up in the book Beautiful Code, in the chapter by Henry S. Warren. Also, Matt Howells shows a C-language implementation that efficiently calculates a bit count. See this answer.