Executing function upon required number of times - function

calculate the sum of squares of given integers, excluding any negatives.
The first line of the input will be an integer N (1 <= N <= 100), indicating the number of test cases to follow.
Each of the test cases will consist of a line with an integer X (0 < X <= 100), followed by another line consisting of X number of space-separated integers Yn (-100 <= Yn <= 100).
For each test case, calculate the sum of squares of the integers, excluding any negatives, and print the calculated sum in the output.
Note: There should be no output until all the input has been received.
Note 2: Do not put blank lines between test cases solutions.
Note 3: Take input from standard input, and output to standard output.
Rules
Write your solution using Go Programming Language
Your source code must be a single file (package main)
Do not use any for statement
You may only use standard library packages
"Problem which I am facing"
'square' function below is not getting executed the required number of times according to the input test cases. To meet specific requirements I wasn't allowed to use the 'for' statement. Please help me out. Language is Go.
package main
import "fmt"
var s []int
func square(l int) {
i := 0
sum := 0
Square:
if l > 0 {
s[i] = s[i] * s[i]
sum = sum + s[i]
i++
l--
goto Square
}
fmt.Println(sum)
}
func myfunc(a int) {
Here:
if a > 0 {
var b int
fmt.Scanln(&b)
if b > 0 {
s = append(s, b)
}
a--
goto Here
}
}
func main() {
var a int
fmt.Scanln(&a)
TestCases:
if a > 0 {
var T int
fmt.Scanln(&T)
myfunc(T)
a--
goto TestCases
}
square(len(s))
}

Here is an implementation using recursion:
package main
import "fmt"
func testCase(N int) {
if N <= 0 {
return
}
var X int
fmt.Scanf("%d", &X)
fmt.Println(sumOfSquare(X))
testCase(N-1)
}
func sumOfSquare(X int) int {
if X == 0 {
return 0
}
var Y int
fmt.Scanf("%d", &Y)
if Y > 0 {
return Y*Y + sumOfSquare(X-1)
}
return sumOfSquare(X-1)
}
func main() {
var N int
fmt.Scanf("%d", &N)
testCase(N)
}
Here is an example output:
$ go run main.go
2 4 3 -1 1 14 5 9 6 -53 32 16
206
1397

I have this program in python using recursion, but not in go-lang.
Here is the code
def squaresum(counter,alist):
if counter==0:
return 0
else:
if int(alist[counter-1])<0:
return 0 + squaresum(counter-1, alist)
else:
return int(alist[counter-1])**2 + squaresum(counter-1,alist)
def testcase(a):
if a==0:
return
terms = int(input())
nums = input()
list1 = nums.split()
print(squaresum(terms,list1))
testcase(a-1)
if __name__=='__main__':
casecount = int(input())
testcase(casecount)

Related

Convolution decoding using viterbi algorithm in unetstack

I have tried to implement convolution decoding using Viterbi algorithm in unetstack. However, there are some issues that I am facing.
The data is not getting sent to node 2. (arr - line 43 of MulAgent.groovy )
In some cases getting an error-
groovy.lang.MissingMethodException:No signature of method:Script2.send() is applicable for argument types:(java.lang.Integer, java.lang.Integer)
values: [2,1010]
//where 2, 1010 are the input values that we are giving
mul-sim.groovy(first file that opens and asks for input of data)
import org.arl.fjage.Message
import org.arl.unet.*
import org.arl.mac.*
import org.arl.unet.phy.*
import org.arl.fjage.RealTimePlatform
println'''
OUTPUT TABLE
+----+----------+----------+
| | 0 | 1 |
+----+----------+----------+
| a | 00(a) | 11(b) |
+----+----------+----------+
| b | 10(c) | 01(d) |
+----+----------+----------+
| c | 11(a) | 00(b) |
+----+----------+----------+
| d | 01(c) | 10(d) |
+----+----------+----------+ '''
println '''
2-node network to perform sender - receiver operation
-----------------------------------------
Node 1 will send an encoded value to node 2
The agent MulAgent present at node 2, will decode the received data and send the value to node 1 checking
You can interact with node 1 in the console shell. For example, try:
send <to-address> , < data>
For example:
send 2, 1011
When you are done, exit the shell by pressing ^D or entering:
shutdown
'''
platform = RealTimePlatform
// run simulation forever
simulate {
node '1', address: 1, remote: 1101, location: [0, 0, 0], shell: true, stack: { container ->
container.shell.addInitrc "${script.parent}/fshrc.groovy"
}
node '2', address: 2, remote: 1102, location: [1.km, 0, 0], shell:5102, stack: { container ->
container.add 'mul', new MulAgent()
}
}
MulAgent.groovy( Agent file
//Agent for the program that contains the decoding code
import org.arl.fjage.Message
import org.arl.unet.*
import org.arl.mac.*
class MulAgent extends UnetAgent {
final static int PROTOCOL = Protocol.DATA
int received_data
int new_data
def arr = new int[4][2]
def temp = new int[2]
def code=new int[4][2]
int i
int k
int j = 0
int error_bit;
int column_error = 0
int row_error = 0
int m = 4
int n = 4
int count
void startup() {
def phy = agentForService Services.PHYSICAL
subscribe topic(phy)
}
void processMessage(Message msg) {
if (msg instanceof DatagramNtf && msg.protocol == PROTOCOL)
{
for(i=0;i<2;i++)
{
temp[i] = msg.data[i]
println "Recieved data printing in Agent is ${temp[i]}"
}
for(i=0;i<2;i++)
arr[j][i] = temp[i];
println "Array in Agent is ${arr}}"
println "Recieved data printing in Agent is ${temp}"
println "Recieved total data printing in Agent is ${temp}"
send new DatagramReq(recipient: msg.sender,to: msg.from, protocol: Protocol.MAC, data: arr[j])
j++
// start
/*******************************************************************/
/* /
/ convolution decoding using viterbi /
/ ------------------------------------------ /
/ Step 1: take input as the encoded dataword /
/ Step 2: Sub module to calculate hamming distance /
/ Step 2: code for decoding using viterbi algorithm */
/*******************************************************************/
code=arr;
int state[]=[0,,0,0,0,0,0,0] //state
int mem[]=[0,0,0,0,0,0,0,0,0,0] //memory
int path=0; //path matrix
//int data[]=[1,1,0,1]
int n,l;
for (int j=0;j<4;j++)
{ for(int i=8;i>=0;i--)
{ mem[i+i]=mem[i]; //shifting by one bit
}
for (int i=0;i<8;i++)
{ state[i]=mem[i];
}
//disp(mem);
state[i]=0; //introduce 0
mem[i]=0;
// to calculate the hamming distance
int out1=((mem[1]^mem[2]^mem[4]^mem[5]^mem[6]^mem[7]^mem[8])^ ((mem[1]^mem[2]^mem[3]^mem[5]^mem[6]^mem[7]^mem[8])); //disp(out1); //output with 0
state[i]=1; //introduce 1
mem[i]=1;
int out2=((mem[1]^mem[2]^mem[4]^mem[5]^mem[6]^mem[7]^mem[8])^ ((mem[1]^mem[2]^mem[3]^mem[5]^mem[6]^mem[7]^mem[8]));
int l=(code[j][0]^out1)+(code[j][1]^out)); //hamming distance with out1
int m=(code[j][0]^out2)+(code[j][1]^out2)); //hamming distance with out2
if(l<m) { //consider with minimum hamming distance
path=path+l;
state[1]=0;
mem[1]=0;
data[j]=0;}
else
{ path=path+m;
data[j]=1;
}
if(l<m)
{ path=path+l;
decode[k]=0;}
else if(l>m)
{ path=path+m;
decode[k]=1;
}
println"path value =$path"
int code=data;
}
def codew=new int[4][2]
codew=code;//detecting 0 bit error
int correct=0;
int detect=0;
int n;
for(i=0;i<2;i++)
if(codew[i][j])
codew[i][j]=0;
for(int i=0;i<4;i++)
if(path!=0) //one error detected
{ if(y==codew) //corrected
{ correct=correct+1;
detect=detect+1;
}
}
if(path!=0) //detected
{ if(y!=codew) //not corrected
{ detect=detect+1;
}
}
n++;
if(codew[i][j])
codew[i][j]=0;
else
codew[i][j]=1;
}
if(detect==0)
println"detection completed"
println"$code"
else if(detect!=0)
println"detection completed"
println"$code"
}
}
fshrc.groovy (the received word is encoded and sent for decoding)
import org.arl.unet.*
import org.arl.unet.phy.*
import org.arl.unet.*
import org.arl.unet.phy.*
import org.arl.unet.mac.*
//import org.arl.unet.nodeinfo.NodeInfo
//import org.arl.unet.PDU
import org.arl.fjage.*
//import static org.arl.unet.Services.*
//import static org.arl.unet.phy.Physical.*
subcribe phy
send = { addr, value ->
println "sending $value to node $addr"
def y= new int[4];
def a=new int[4];
a=[1, 1, 1, 1]
y=[0, 0, 0, 0]
int i=3
println "$value"
int x=value;
while(x!=0)
{
y[i]=x%10;
println "$y"
x=x/10;
i--;
}
def code=new int[4][2];
/*code word encoded using generator functions
g1=1101
g2=1110
*/
for(i=0;i<4;i++)
{
int bit = y[3-i];
a[3-i] = bit;
code[i][0] = a[0]^a[1]^a[3];
code[i][1] = a[0]^a[1]^a[2];
}
println"The 4 bit encoded codeword:"
//The code word is printed
println"$code"
//println "sending ${value[0]} to node $addr "
phy << new DatagramReq(to: addr, protocol: Protocol.DATA, data: code[0])
def txNtf1= receive(TxFrameNtf, 1000)
def rxNtf1 = receive({ it instanceof RxFrameNtf && it.from == addr}, 5000)
if (txNtf1 && rxNtf1 && rxNtf1.from == addr)
println "Data Received at ${rxNtf.to} from ${rxNtf.from} is: ${rxNtf.data}"
//println "sending ${value[1]} to node $addr "
phy << new DatagramReq(to: addr, protocol: Protocol.DATA, data: code[1])
def txNtf2 = receive(TxFrameNtf, 1000)
def rxNtf2 = receive({ it instanceof RxFrameNtf && it.from == addr}, 5000)
if (txNtf2 && rxNtf2 && rxNtf2.from == addr)
println "Data Received at ${rxNtf2.to} from ${rxNtf2.from} is: ${rxNtf2.data}"
// println "sending ${value[2]} to node $addr "
phy << new DatagramReq(to: addr, protocol: Protocol.DATA, data: code[2])
def txNtf3 = receive(TxFrameNtf, 1000)
def rxNtf3 = receive({ it instanceof RxFrameNtf && it.from == addr}, 5000)
if (txNtf3 && rxNtf3 && rxNtf3.from == addr)
println "Data Received at ${rxNtf3.to} from ${rxNtf3.from} is: ${rxNtf3.data}"
//println "sending ${value[3]} to node $addr "
phy << new DatagramReq(to: addr, protocol: Protocol.DATA, data: code[3])
def txNtf4 = receive(TxFrameNtf, 1000)
def rxNtf4 = receive({ it instanceof RxFrameNtf && it.from == addr}, 5000)
if (txNtf4 && rxNtf4 && rxNtf4.from == addr)
println "Data Received at ${rxNtf4.to} from ${rxNtf4.from} is: ${rxNtf4.data}"
}

Defining the interface for a function using function properties

As you may know, functions in JavaScript can have properties as any object. For example (taken from the excellent JavaScript: The Definitive Guide, 6th ed, p. 178) computes a factorial using the function as memoization array:
function factorial(n: number): number {
if (isFinite(n) && n > 0 && n == Math.round(n)) {
if (!(n in factorial))
factorial[n] = n * factorial(n - 1);
return factorial[n];
}
else
return NaN;
}
factorial[1] = 1;
I tried defining the following interface:
interface Factorial {
(n: number) : number;
[ index: number ]: number;
}
But the compiler is telling me that Type '(n: number) => number' is not assignable to type 'Factorial'. Index signature is missing in type '(n: number) => number'.
I can't do the obvious thing and just define private index: number; inside the function, I'm stumped.
What you have is an example of hybrid types. You have to use type assertion to make sure the function complies with the interface:
let factorial = function (n: number): number {
if (isFinite(n) && n > 0 && n == Math.round(n)) {
if (!(n in factorial))
factorial[n] = n * factorial(n - 1);
return factorial[n];
}
else
return NaN;
} as Factorial;
factorial[1] = 1;

Golang, build error inside function

So I have a really frustrating build error I have been staring at for the past hour or two. It involves one of my functions in my linked list program. It thinks I have statements outside the function when they are clearly inside, and thinks the { : } ratio is off. Am I missing something really simple?
// Index returns the location of element e. If e is not present,
// return 0 and false; otherwise return the location and true.
func (list *linkedList) Index(e AnyType) (int, bool) {
var index int = 0
var contain bool = false
if list.Contains(e) == false {
return 0, false
}
for int i := 0; i < list.count; i++ { \\175
list.setCursor(i)
if list.cursorPtr.item == e {
index = list.cursorIdx
contain = true
}
}
return index, contain \\182
} \\183
Build errors
./lists.go:175: syntax error: unexpected name, expecting {
./lists.go:182: non-declaration statement outside function body
./lists.go:183: syntax error: unexpected }
I appreciate any help. Thank you.
Looks like it's all line 175's fault, should be
for i := 0; i < list.count; i++ {
note I removed int

Tracking depth in a non-recursive breadth first search

I have the following algorithm for a breadth first search:
q := []
q.append(root node of tree)
while q:
n := q.pop(0)
yield n
if n has children:
c := children of node
for i in c:
q.append(i)
1) How could this be extended so it keeps track of the current depth?
2) Would this extension apply to a similar algorithm for depth first search, with the queue q replaced by a stack?
Just store the depth with the nodes and increment it every time you generate a node's children.
q := [(root, 0)]
while q:
n, depth := q.pop()
yield n, depth
if n has children:
c := children of n
for i in c:
q.append(i, depth + 1)
This idea extends to DFS and heuristic-guided search.
To expand on larsmans' excellent answer, below is my c++ code for depth-limited breadth-first binary tree traversal.
(The code assumes that Node does not include depth information, and wraps each node in a NodeAndDepth structure before enqueueing it.)
struct NodeAndDepth {
NodeAndDepth(Node *n, unsigned int d) : node(n), depth(d) {}
Node *node;
unsigned int depth;
};
void traverseBreadthFirst_WithDepthLimit(Node *root, unsigned int maxDepth) {
if (maxDepth == 0 || root == NULL) { return; }
std::queue<NodeAndDepth> q;
q.push(NodeAndDepth(root, 1));
while (!q.empty()) {
NodeAndDepth n = q.front(); q.pop();
// visit(n.node);
// cout << n.depth << ": " << n.node->payload << endl;
if (n.depth >= maxDepth) { continue; }
if (n.node->left != NULL) {
q.push(NodeAndDepth(n.node->left, n.depth + 1));
}
if (n.node->right != NULL) {
q.push(NodeAndDepth(n.node->right, n.depth + 1));
}
}
}

How do I work with complex numbers in CUSPARSE?

I'm currently working with CUSPARSE. I'm having trouble because I don't know how to print a complex number. For example, when I write:
cuComplex a;
a.x=1.2;
a.y=2.2;
How do I print the varable a?
I've tried :
cout<< a;
but it doesn't work.
You will need to overload the << operator to take in cuComplex and cuDoubleComplex data types.
std::ostream& operator<<(std::ostream& strm, const cuComplex& in)
{
char sgn[2] = "+-"
strm << in.x << sgn[in.y < 0] << " i"<< std::abs(in.y);
return strm;
}
You can do the same for cuDoubleComplex
The data in std::complex is identical to the corresponding data in a cuComplex, i.e. you can reinterpret_cast pointers (and therefore arrays, too) of one type to the other – it works in practise and is, I think, actually guaranteed by C++11, you can test it like this:
namespace check_stdComplexdouble_to_cuDoubleComplex_binary_compatibility{
using std::complex;
const complex<double> testarr[] = { complex<double>(0.,.5)
, complex<double>(1.,1.5) };
const cuDoubleComplex* cucomplexd
= reinterpret_cast<const cuDoubleComplex*>(testarr);
auto tester() -> bool {
assert( cuCreal(cucomplexd[0])==0. && cuCimag(cucomplexd[0])==.5
&& cuCreal(cucomplexd[1])==1. && cuCimag(cucomplexd[1])==1.5 );
return true;
}
const bool ok = tester();
bool good(){return ok;}
};
If you call a CUBLAS function that's supposed to read/write from/to an std::complex<float>, you can just give it a reinterpret_casted pointer, e.g.
std::complex<double> result;
xhandle->cublasstat = yhandle->cublasstat
= cublasZdotc( *xhandle->cublashandle
, xhandle->vect_dimension
, xhandle->vector, 1
, yhandle->vector, 1
, reinterpret_cast<cuDoubleComplex*>(&result) );