#include <iostream>
using namespace std;
//Reference: https://www.geeksforgeeks.org/print-sums-subsets-given-set/
//==============testcase1==============
int arr[] = { 5, 4, 3 };
int n = 3;
//output: 12 9 8 5 7 4 3 0
//=====================================
//==============testcase2==============
//int arr[] = {2, 3};
//int n = 2;
//output: 5 2 3 0
//=====================================
// Prints sums of all subsets of arr[l..r]
void subsetSums(int arr[], int l, int r, int sum)
{
// Print current subset
if (l > r) {
cout << sum << " ";
return;
}
// Subset including arr[l]
subsetSums(arr, l + 1, r, sum + arr[l]);
// Subset excluding arr[l]
subsetSums(arr, l + 1, r, sum);
}
// Driver code
int main()
{
cout << "output: ";
subsetSums(arr, 0, n - 1,0);
return 0;
}
I want to convert to R64I assembly code. Here is what I have done.
# Reference: https://www.geeksforgeeks.org/print-sums-subsets-given-set/
.data
.align 4
# =========testcase1===========
arr: .word 5, 4, 3
n: .word 3
str: .string "output: "
space: .string " "
# output: 12 9 8 5 7 4 3 0
# ==============================
# =========testcase2===========
#arr: .word 2, 3
#n: .word 2
#str: .string "output: "
#space: .string " "
# output: 5 2 3 0
# ==============================
.text
.global _start
# Start your coding below, don't change anything upper except testing different testcase
_start:
#la t0, aa
#auipc t0, 0x1
#nop
#nop
#addi t0, t0, 148
#nop
#nop
li a7, 4
la a0, str
ecall
#load arr, 0, n, 0
la a0, arr
la a1, 0
la a2, n
la a3, 0
jal subsetSums
j end # Jump to end of program
subsetSums:
mv t0, a0
mv t1, a1
mv t2, a3
# if l > r print sum
blt a2, a1, sum
add t3, a1, 0
slli t3, t3, 2
addi t3, a0, t3
lw t4, 0(t3)
add a3, t2, t3
addi a1, t1, 1
jal subsetSums
addi a1, t1, 1
add a3, t2, 0
jal subsetSums
sum:
mv t0, a3
# Print sum
li a7, 1
addi a0, t0, 0
ecall
#Print
li a7, 4
la a0, space
ecall
lw ra, 0(sp) # Reload return address from stack
addi sp, sp, 4 # Restore stack pointer
jr x1
end:nop
I want to do 2 testcases. First one from arr: .word 5,4,3 and get the output: 12 9 8 5 7 4 3 0. However, I don't know how to print out the strings and numbers. I have just learned Hello World for two years. I have never learned Assembly code before and have no idea what I'm doing. EDIT2: Thank you for all your reply. I have fixed how to output string and number, however I get a bug in this code
subsetSums:
mv t0, a0
mv t1, a1
mv t2, a3
# if l > r print sum
blt a2, a1, sum
#BUG
add t3, a1, 0
slli t3, t3, 2
addi t3, a0, t3
lw t4, 0(t3)
add a3, t2, t3
addi a1, t1, 1
jal subsetSums
addi a1, t1, 1
add a3, t2, 0
jal subsetSums
#BUG
It seems I can't put the correct arguments in my function. As for why I use nop in end:, I have to do that to follow my professor.