Multi dimensional array assignment in verilog, without loop? - multidimensional-array

How can one assign a multi dimensional array if it is a wire, in a single line?
assign TO[W1:0][W2:0] = cntrl ? FROM1[W1:0][W2:0] : FROM2[W1:0][W2:0];
I get a syntax error if I use this.
Is there any other way other than using generate or for loops?

You need to be using SystemVerilog to make aggregate assignments to arrays.

To assign an unpacked arrays braces with tick '{ and } are used, provided all the values of the array should be assigned.
usage example
module top ( input i);
wire d [0:1][0:3];
wire a [0:1][0:3]='{ '{1,1,1,1}, '{1,1,1,1} };
wire b [0:1][0:3]='{ '{0,0,0,0}, '{0,0,0,0} };
assign d = i? (' { '{a[0][0],a[0][1],a[0][2],a[0][3]},'{b[1][0],b[1][1],b[1][2],b[1][3]}}):
(' { '{b[1][0],b[1][1],b[1][2],b[1][3]},'{a[0][0],a[0][1],a[0][2],a[0][3]}});
endmodule
Here wire a [0:1][0:3]='{ '{1,1,1,1}, '{1,1,1,1} }; and wire b [0:1][0:3]='{ '{0,0,0,0}, '{0,0,0,0} }; represents
// a[0][0] = 1 b[0][0] = 0
// a[0][1] = 1 b[0][1] = 0
// a[0][2] = 1 b[0][2] = 0
// a[0][3] = 1 b[0][3] = 0
// a[1][0] = 1 b[1][0] = 0
// a[1][1] = 1 b[1][1] = 0
// a[1][2] = 1 b[1][2] = 0
// a[1][3] = 1 b[1][3] = 0
Working example can be found in the eda-playground link

Two pure verilog solutions: (Assuming W1 and W2 are parameters, not variables)
// 'TO' must be a reg
integer i,j;
always #* begin
for(i=0; i<=W1; i=i+1) begin
for(j=0; j<=W2; j=j+1) begin
TO[i][j] = cntrl ? FROM1[i][j] : FROM2[i][j];
end
end
end
// 'TO' must be a wire
genvar i,j;
generate
for(i=0; i<=W1; i=i+1) begin
for(j=0; j<=W2; j=j+1) begin
assign TO[i][j] = cntrl ? FROM1[i][j] : FROM2[i][j];
end
end
endgenerate

Related

Recursive FIbonacci arm Assembly

Edit: I have removed my code as I do not want to get caught for cheating on my assignment. I will repost the code once my assignment has been submitted. I apologize for posting it on stack overflow, I just had no where else to go for help. Please respect my edit to remove the code. I have tried deleting it, but it will not let me as I need to request it.
[MIPS code I was trying to follow][1]
[C Code I was trying to follow][2]
I am trying to convert recursive fibonacci code into arm assembly but I am running into issues. When running my arm assembly, the final value of the sum is 5 when it should be 2. It seems as though my code loops but maybe one too many times. Any help would be much appreciated as I am new to this.
This is what your code is doing, and below is a test run.  This simply isn't a usual recursive fibonacci.
#include <stdio.h>
void f ( int );
int R2 = 0;
int main () {
for ( int i = 0; i < 10; i++ ) {
R2 = 0;
f ( i );
printf ( "f ( %d ) = %d\n", i, R2 );
}
}
void f ( int n ) {
if ( n == 0 ) { R2 += 0; return; }
if ( n == 1 ) { R2 += 1; return; }
f ( n-1 );
f ( n-2 );
R2 += n-1;
}
f ( 0 ) = 0
f ( 1 ) = 1
f ( 2 ) = 2
f ( 3 ) = 5
f ( 4 ) = 10
f ( 5 ) = 19
f ( 6 ) = 34
f ( 7 ) = 59
f ( 8 ) = 100
f ( 9 ) = 167
Either you started with a broken Fibonacci algorithm, or substantially changed it going to assembly.  I don't know how this can be fixed, except by following a working algorithm.
Note that in the C code the only addition is in the fib(n-1) + fib(n-2). In particular the special cases just do return 0; and return 1; respectively. Thus your else add 0/1 to sum lines are wrong. You should replace your additions with moves.
Also, you do MOV R1, R0 //copy fib(n-1) which is incorrect because the fib(n-1) has been returned in R2 not R0. That should be MOV R1, R2.
With these changes the code works, even if it is slightly non-standard.

++ is deprecated - "+= 1 is not solving the issue"

After updating Xcode to 7.3 I am having some warnings saying :
'++' is deprecated: it will be removed in Swift 3
The code where the warning appear is a function that merges two arrays:
arr4.append(arr1[i++])
I have tried changing it with :
arr4.append(arr1[i += 1])
but I get an error saying :
Cannot subscript a value of type '[[String]]' with an index of type
'()'
The full code is:
let arr1 = [["aaa","111"],["bbb","222"],["ccc","333"]]
let arr2 = [["ddd","444"],["eee","555"],["fff","666"]]
var arr4 = zip(arr1, arr2).reduce([]) { ( newArr, p:(Array<String>, Array<String>)) -> [[String]] in
var arr = newArr
arr.append(p.0)
arr.append(p.1)
return arr
}
var i = arr4.count / 2
while i < arr1.count {
arr4.append(arr1[i++]) // WARNING
}
while i < arr2.count {
arr4.append(arr2[i++]) // WARNING
}
print(arr4)
Use:
arr4.append(arr1[i])
i += 1
The motivation for the change is legibility — ensuring that steps are properly spelt out, reducing ambiguity. The result of the expression a += 1 is of type void — it does something, but doesn't evaluate to anything — which is expressed as the empty tuple, (), and cannot be used as an array index.
(Aside: += 1 also isn't a direct substitution for ++ in C.
int a = 3;
int b = a += 1;
NSLog(#"%d %d", a, b);
... will produce a different output than the equivalent b = a ++;.)
Code:
arr4.append(arr1[i])
i += 1
If you insist to do it in a single line. you can but it looks ugly:
arr4.append(arr1[(i += 1) - 1])
I not sure. test it.

Shuffle an array in Arduino software

I have a problem with Shuffling this array with Arduino software:
int questionNumberArray[10]={0,1,2,3,4,5,6,7,8,9};
Does anyone know a build in function or a way to shuffle the values in the array without any repeating?
The simplest way would be this little for loop:
int questionNumberArray[] = {0,1,2,3,4,5,6,7,8,9};
const size_t n = sizeof(questionNumberArray) / sizeof(questionNumberArray[0]);
for (size_t i = 0; i < n - 1; i++)
{
size_t j = random(0, n - i);
int t = questionNumberArray[i];
questionNumberArray[i] = questionNumberArray[j];
questionNumberArray[j] = t;
}
Let's break it line by line, shall we?
int questionNumberArray[] = {0,1,2,3,4,5,6,7,8,9};
You don't need to put number of cells if you initialize an array like that. Just leave the brackets empty like I did.
const size_t n = sizeof(questionNumberArray) / sizeof(questionNumberArray[0]);
I decided to store number of cells in n constant. Operator sizeof gives you number of bytes taken by your array and number of bytes taken by one cell. You divide first number by the second and you have size of your array.
for (size_t i = 0; i < n - 1; i++)
Please note, that range of the loop is n - 1. We don't want i to ever have value of last index.
size_t j = random(0, n - i);
We declare variable j that points to some random cell with index greater than i. That is why we never wanted i to have n - 1 value - because then j would be out of bound. We get random number with Arduino's random function: https://www.arduino.cc/en/Reference/Random
int t = questionNumberArray[i];
questionNumberArray[i] = questionNumberArray[j];
questionNumberArray[j] = t;
Simple swap of two values. It's possible to do it without temporary t variable, but the code is less readable then.
In my case the result was as follows:
questionNumberArray[0] = 0
questionNumberArray[1] = 9
questionNumberArray[2] = 7
questionNumberArray[3] = 4
questionNumberArray[4] = 6
questionNumberArray[5] = 5
questionNumberArray[6] = 1
questionNumberArray[7] = 8
questionNumberArray[8] = 2
questionNumberArray[9] = 3

Convert price values with decimals language neutral to an integer in ASP.NET

I want to convert decimal numbers (price values to be exact), which may:
a) contain 1 OR 2 decimals
b) have either a . or , as decimal separator
to an integer value in cents.
So:
3,5 becomes 350
3,50 becomes 350
3.5 becomes 350
3.50 becomes 350
1,000.34 becomes 100034
1.000,34 becomes 100034
Without building a function that does all these checks is there a way in ASP.NET to do this more quickly?
**UPDATE **
Thanks to Nicholas:
I now have this in VB.NET
Private Shared Function ConvertToPriceInCents(s As String) As Integer
If s Is Nothing Then
Throw New ArgumentNullException("s")
End If
If s = "" Then
Throw New ArgumentOutOfRangeException("s", "s must not be empty.")
End If
Dim priceInCents As Integer = 0
Dim scale As Integer = 1
Dim i As Integer = s.Length
' collect the fractional part; identify the decimal separator
While System.Threading.Interlocked.Decrement(i) >= 0
Dim n As Integer = Asc(s(i)) - Asc("0"c)
If n < 0 OrElse n > 9 Then
Exit While
End If
' bail out, we found the decimal separator
priceInCents += n * scale
scale *= 10
End While
Dim decimalSeparator As Char = s(i)
Dim groupSeparator As Char = If(decimalSeparator = "."c, ","c, "."c)
If scale <> 10 AndAlso scale <> 100 Then
Throw New FormatException("value must have 1 or 2 digits to the right of the decimal separator")
End If
If decimalSeparator <> ","c AndAlso decimalSeparator <> "."c Then
Throw New FormatException("Invalid decimal separator")
End If
' if we only found one digit to the right of the decimal separator,
' we need to normalize and scale up by a factor of 10 (so something like 3.5 represents 350 cents)
If scale = 10 Then
scale *= 10
priceInCents *= 10
End If
' get the integer portion of value
' we're being a little lax here and ignoring group separators regardless of position.
' It's a hard thing to do, especially when you consider that
' - group sizes vary across cultures, and
' - aren't necessarily uniform in size.
While System.Threading.Interlocked.Decrement(i) >= 0
Dim c As Char = s(i)
If c = groupSeparator Then
Continue While
End If
Dim n As Integer = Asc(s(i)) - Asc("0"c)
If n < 0 OrElse n > 9 Then
Throw New FormatException("invalid group separator")
End If
priceInCents += n * scale
scale *= 10
End While
' If we haven't thrown an exception yet,
' we have the value in cents: return it.
Return priceInCents
End Function
You write a method that looks something like this:
static int ConvertToPriceInCents( string s )
{
if ( s == null ) throw new ArgumentNullException("s") ;
if ( s == "" ) throw new ArgumentOutOfRangeException("s","s must not be empty." ) ;
int priceInCents = 0 ;
int scale = 1 ;
int i = s.Length ;
// collect the fractional part; identify the decimal separator
while ( --i >= 0 )
{
int n = s[i] - '0' ;
if ( n < 0 || n > 9 ) break ; // bail out, we found the decimal separator
priceInCents += n*scale ;
scale *= 10 ;
}
char decimalSeparator = s[i] ;
char groupSeparator = decimalSeparator == '.' ? ',' : '.' ;
if ( scale != 10 && scale != 100 ) throw new FormatException("value must have 1 or 2 digits to the right of the decimal separator") ;
if ( decimalSeparator != ',' && decimalSeparator != '.' ) throw new FormatException("Invalid decimal separator") ;
// if we only found one digit to the right of the decimal separator,
// we need to normalize and scale up by a factor of 10 (so something like 3.5 represents 350 cents)
if ( scale == 10 )
{
scale *= 10 ;
priceInCents *= 10 ;
}
// get the integer portion of value
// we're being a little lax here and ignoring group separators regardless of position.
// It's a hard thing to do, especially when you consider that
// - group sizes vary across cultures, and
// - aren't necessarily uniform in size.
while ( --i >= 0 )
{
char c = s[i] ;
if ( c == groupSeparator ) continue ;
int n = s[i] - '0' ;
if ( n < 0 || n > 9 ) throw new FormatException("invalid group separator") ;
priceInCents += n*scale ;
scale *= 10 ;
}
// If we haven't thrown an exception yet,
// we have the value in cents: return it.
return priceInCents ;
}

Divide and Conquer Recursion

I am just trying to understand how the recursion works in this example, and would appreciate it if somebody could break this down for me. I have the following algorithm which basically returns the maximum element in an array:
int MaximumElement(int array[], int index, int n)
{
int maxval1, maxval2;
if ( n==1 ) return array[index];
maxval1 = MaximumElement(array, index, n/2);
maxval2 = MaximumElement(array, index+(n/2), n-(n/2));
if (maxval1 > maxval2)
return maxval1;
else
return maxval2;
}
I am not able to understand how the recursive calls work here. Does the first recursive call always get executed when the second call is being made? I really appreciate it if someone could please explain this to me. Many thanks!
Code comments embedded:
// the names index and n are misleading, it would be better if we named it:
// startIndex and rangeToCheck
int MaximumElement(int array[], int startIndex, int rangeToCheck)
{
int maxval1, maxval2;
// when the range to check is only one cell - return it as the maximum
// that's the base-case of the recursion
if ( rangeToCheck==1 ) return array[startIndex];
// "divide" by checking the range between the index and the first "half" of the range
System.out.println("index = "+startIndex+"; rangeToCheck/2 = " + rangeToCheck/2);
maxval1 = MaximumElement(array, startIndex, rangeToCheck/2);
// check the second "half" of the range
System.out.println("index = "+startIndex+"; rangeToCheck-(rangeToCheck/2 = " + (rangeToCheck-(rangeToCheck/2)));
maxval2 = MaximumElement(array, startIndex+(rangeToCheck/2), rangeToCheck-(rangeToCheck/2));
// and now "Conquer" - compare the 2 "local maximums" that we got from the last step
// and return the bigger one
if (maxval1 > maxval2)
return maxval1;
else
return maxval2;
}
Example of usage:
int[] arr = {5,3,4,8,7,2};
int big = MaximumElement(arr,0,arr.length-1);
System.out.println("big = " + big);
OUTPUT:
index = 0; rangeToCheck/2 = 2
index = 0; rangeToCheck/2 = 1
index = 0; rangeToCheck-(rangeToCheck/2 = 1
index = 0; rangeToCheck-(rangeToCheck/2 = 3
index = 2; rangeToCheck/2 = 1
index = 2; rangeToCheck-(rangeToCheck/2 = 2
index = 3; rangeToCheck/2 = 1
index = 3; rangeToCheck-(rangeToCheck/2 = 1
big = 8
What is happening here is that both recursive calls are being made, one after another. The first one searches have the array and returns the max, the second searches the other half and returns the max. Then the two maxes are compared and the bigger max is returned.
Yes. What you have guessed is right. Out of the two recursive calls MaximumElement(array, index, n/2) and MaximumElement(array, index+(n/2), n-(n/2)), the first call is repeatedly carried out until the call is made with a single element of the array. Then the two elements are compared and the largest is returned. Then this comparison process is continued until the largest element is returned.

Resources