NEWTON
Asked
4 months ago
14
views
0
The function below is an example. Please ignore the for loop.
The idea is that I want to keep updating the value largest once I found a number larger than it from the input (a series of numbers bitpacked into Uint256), but I also hope it remains its initialized value if not. Right now if I do the following, the pointers seem to get messed up.
func getLargest(array) -> (res : felt)
let largest = 5
local currentNum
# pseudocode here, using for loops for simplicity tho cairo doesn't it
for (i=0, i < array.length, i++):
currentNum = array[i]
if (currentNum > largest):
assert largest = currentNum
end
let res = largest
return (res)
end
Test 1
Input(s): 1
Output(s): 5
Test 2
Input(s): 10
Output(s): 10
ㅤ This question was originally posted on Triality
0
Test #1
Test #2
For some additional context, there was an ask to provide code for this in the case of a felt*, with the problem statement of given a lower_bound - let's say 5, return that lower_bound if no value in the array is greater than it or return the greatest value in the array if there is one larger than it.
%builtins output range_check
from starkware.cairo.common.serialize import serialize_word
from starkware.cairo.common.math_cmp import is_le
func main{output_ptr : felt*, range_check_ptr}():
alloc_locals
local lower_bound : felt = 5
tempvar arr : felt* = new (1, 2, 3)
let arr_size : felt = 3
let (largest_val) = get_largest_val(arr, arr_size, lower_bound)
serialize_word(largest_val)
tempvar arr1 : felt* = new (1, 6, 3)
let arr_size1 : felt = 3
let (largest_val1) = get_largest_val(arr1, arr_size1, lower_bound)
serialize_word(largest_val1)
return ()
end
#Get the largest value of all the numbers of an array and a base number to test against
func get_largest_val{range_check_ptr}(arr : felt*, arr_size : felt, curr_largest : felt) -> (res : felt):
if arr_size == 0:
return (curr_largest)
end
let (isLe) = is_le(curr_largest, arr[0])
if isLe == 1:
return get_largest_val(arr+1, arr_size - 1, arr[0])
end
return get_largest_val(arr+1, arr_size - 1, curr_largest)
end
This script would give the following output:
Program output:
5
6
Number of steps: 200
ㅤ This answer was originally posted on Triality
answered
5 months ago
How do I write a log based 2 function in Cairo?
How to calculate the sum of the digits of a felt in Cairo?
How to use Hints in Cairo Lang?
Cairo: How to reassign Uint256 in a conditional
How can I use dynamic allocation in Cairo?
Cairo Lang / StarkNet: What are Revoked references? What is alloc_locals?
Cairo: How do I initialize an array in cairo
Cairo error for Unexpected '.' after ... which is future
How can I use start_prank with deploy_contract?
How can I prepare my Cairo lang project for an audit?
How do I interact with my Pathfinder node?
Are you able to nest mappings in Cairo like you can in Solidity?
Cairo: Where/how is it defined and why is it much smaller than the field prime?
How to write a function in Cairo Lang (StarkNet)?