My code is as follows:
/**
*
* #notice Returns a Sale array with all the sales that have not ended.
*
*/
function getOngoingSales() public view returns(Sale[] memory) {
uint256 _ongoingSalesCounter = 0;
for(uint i = 0; i<sales.length; i++) {
if (sales[i].ended == false) _ongoingSalesCounter++;
}
Sale[] memory _ongoingSales = new Sale[](_ongoingSalesCounter);
uint256 _pos = 0;
for(uint i = 0; i<sales.length; i++) {
if (sales[i].ended == false) {
_ongoingSales[_pos] = sales[i];
_pos ++;
}
}
return _ongoingSales;
}
The problem is that I have to loop twice the array to get to my wanted result. Is there a more effective way of doing this?
You can try to combine the two loops into one,
/**
*
* #notice Returns a Sale array with all the sales that have not ended.
*
*/
function getOngoingSales() public view returns(Sale[] memory) {
Sale[] memory _ongoingSales;
for(uint i = 0; i<sales.length; i++) {
if (sales[i].ended == false) _ongoingSales.push(sales[i]);
}
return _ongoingSales;
}
Before time complexity: O(2n)
After time complexity: O(n)
Related
I've tackled a task: find a specific address in a sheet, move it to the end of the sheet, and remove it via a function pop! here is the code:
function removeAccount(address _account) external{
uint counter = arrayOfAccounts.length;
uint index;
for(uint i; i < counter; i++) {
if(arrayOfAccounts[i] == _account){
index = i;
break;
}
for(uint i = index; i < counter-1; i++){
arrayOfAccounts[i] = arrayOfAccounts[i + 1];
}
arrayOfAccounts.pop();
}
}
}
}
transact to Wote.removeAccount errored: VM error: revert.
revert
The transaction has been reverted to the initial state.
Note: The called function should be payable if you send value and the value you send should be less than your current balance.
Debug the transaction to get more information.
In case you dont care about addresses order
function removeAccount(address _account) external {
if(arrayOfAccounts.length == 1) {
arrayOfAccounts.pop();
}
else if(arrayOfAccounts[arrayOfAccounts.length - 1] == _account) {
arrayOfAccounts.pop();
}
else {
for (uint i = 0; i < arrayOfAccounts.length - 1; i++) {
if(_account == arrayOfAccounts[i]) {
arrayOfAccounts[i] = arrayOfAccounts[arrayOfAccounts.length - 1];
arrayOfAccounts.pop();
}
}
}
}
If order matters
function removeAccount(address _account) external{
uint counter = arrayOfAccounts.length;
for(uint i; i < counter; i++) {
if(arrayOfAccounts[i] == _account){
for(uint j = i; j < counter-1; j++){
arrayOfAccounts[j] = arrayOfAccounts[j + 1];
}
arrayOfAccounts.pop();
break;
}
}
}
}
Else if order doesn't matter
function removeAccount(address _account) external{
uint numAccounts = arrayOfAccounts.length;
for(uint i = 0; i < numAccounts; i++) {
if(arrayOfAccounts[i] == _account){ // if _account is in the array
arrayOfAccounts[i] = arrayOfAccounts[numAccounts - 1]; // move the last account to _account's index
arrayOfAccounts.pop(); // remove the last account
break;
}
}
}
The reason is just simple.
You used the second for loop inside the first for loop.
And also please initialize the index with counter;
uint256 index = counter;
And pop only when index is less than counter
contract task_list {
struct tasksStruct {
string name;
uint32 timestamp;
bool is_done;
}
tasksStruct[] tasks;
function add_task(string _name) public {
tasksStruct newTask = tasksStruct(_name, now, false);
tasks.push(newTask);
}
function show_opened_tasks() public view returns (uint) {
uint count_of_opened_tasks = 0;
for (uint i=0; i<tasks.length; i++){
if (!tasks[i].is_done) {
count_of_opened_tasks += 1;
}
}
}
}
how does pushing for an array of structures work here? and why there is an error out of range of the array?
You're missing the data location for the reference types in the add_task() function. After fixing this, you'll be able to push to the array.
// added location `memory` for `name`
function add_task(string memory _name) public {
// added location `memory` for `newTask`
tasksStruct memory newTask = tasksStruct(_name, uint32(now), false);
tasks.push(newTask);
}
Also you probably want to return the count_of_opened_tasks from the show_opened_tasks() function - otherwise you'll always get returned the default value 0.
function show_opened_tasks() public view returns (uint) {
uint count_of_opened_tasks = 0;
for (uint i=0; i<tasks.length; i++){
if (!tasks[i].is_done) {
count_of_opened_tasks += 1;
}
}
// added return
return count_of_opened_tasks;
}
I am very new to Solidity, so sorry for the silly question. I am trying to add an element of a struct and then return it, here is my code:
struct Flat {
uint256 priceInWei;
address currentOccupant;
bool flatIsAvailable;
}
Flat[8] public flatDB;
modifier landlordOnly() {
require(msg.sender == landlordAddress);
_;
}
constructor() public {
landlordAddress = msg.sender;
for (uint i=0; i<8; i++) {
flatDB[i].flatIsAvailable = true;
if (i % 2 == 0) {
flatDB[i].priceInWei = 0.1 ether;
} else {
flatDB[i].priceInWei = 0.2 ether;
}
}
}
uint256[] array;
function getFlatDB() payable public returns (uint256) {
for (uint i=0; i<8; i++) {
array.push(flatDB[i].priceInWei);
}
return array;
}
But when I try to compile I have an error at line 41:
TypeError: Return argument type uint256[] storage ref is not implicitly convertible to expected type (type of first return variable) uint256. return array; ^---^
Can someone explain me what's wrong? Thanks!
Seems like the return type you have (uint256) doesn't correspond to the type you're actually trying to return (uint256[]). Try rewriting your getFlatDB function in the following way:
function getFlatDB() payable public returns (uint256[]) {
uint256[] memory array = new uint256[](8);
for (uint i=0; i<8; i++) {
array[i] = flatDB[i].priceInWei;
}
return array;
}
Note how we declare the temporary fixed size return array inside the function with memory keyword.
I have this contract with an array of structs:
pragma solidity ^0.6.0;
pragma experimental ABIEncoderV2;
contract Tickets {
struct Ticket {
uint id;
int val;
}
Ticket[] tickets;
function addTicket(uint id, int val) public returns(bool success) {
Ticket memory newTicket;
newTicket.id = id;
newTicket.val = val;
tickets.push(newTicket);
return true;
}
function getTicket(uint id) public view returns(Ticket memory) {
uint index;
for(uint i = 0; i<tickets.length; i++){
if (tickets[i].id == id) {
index = i;
break;
}
}
Ticket memory t = tickets[index];
return t;
}
function findTickets(int val) public view returns(Ticket[] memory) {
Ticket[] memory result;
for(uint i = 0; i<tickets.length; i++){
if (tickets[i].val == val) {
result.push(tickets[i]); // HERE IS THE ERROR
}
}
return result;
}
}
I need to returns a filtered by val array but when I buil this code: result.push(tickets[i].id); it throw this error:
TypeError: Member "push" is not available in struct Tickets.Ticket memory[] memory outside of storage.
How I can implement the filter without using push ?
Returning dynamic-length array of struct is still a bit tricky in Solidity (even in the current 0.8 version). So I made a little workaround to make it work even in the 0.6.
Determine the result count, you'll need it for step 2.
Create a fixed-length array
Fill the fixed-length array
Return the fixed-length array
function findTickets(int val) public view returns(Ticket[] memory) {
uint256 resultCount;
for (uint i = 0; i < tickets.length; i++) {
if (tickets[i].val == val) {
resultCount++; // step 1 - determine the result count
}
}
Ticket[] memory result = new Ticket[](resultCount); // step 2 - create the fixed-length array
uint256 j;
for (uint i = 0; i < tickets.length; i++) {
if (tickets[i].val == val) {
result[j] = tickets[i]; // step 3 - fill the array
j++;
}
}
return result; // step 4 - return
}
I am trying to test this simple contract to remove an address from an array but I keep getting this "invalid opcode" error.
contract C {
address[] addrList;
function addAddr(address addr) public{
addrList.push(addr);
}
function deleteAddr(address addr)public {
for(uint256 i = 0; i < addrList.length; i++) {
if(addr == addrList[i]) {
for(uint256 j = i; j < addrList.length; j++)
addrList[j] = addrList[j + 1];
delete addrList[addrList.length - 1];
addrList.length--; // <== This gives Error: Expression has to be an lvalue.
}
The error is coming because you are iterating variable j from i to addrList.length-1. This makes the addrList[j+1] out of index.
You need to iterate j from i to addrList.length-2. This can be achieved by updating the condition to j < addrList.length-1.
pragma solidity ^0.5.3;
contract C {
address[] addrList;
function addAddr(address addr) public{
addrList.push(addr);
}
function deleteAddr(address addr) public {
for(uint256 i = 0; i < addrList.length; i++) {
if(addr == addrList[i]) {
for(uint256 j = i; j < addrList.length-1; j++) {
addrList[j] = addrList[j + 1];
}
//delete addrList[addrList.length - 1];
addrList.length--;
}
}
}
function returnList() view public returns (address[] memory) {
return addrList;
}
}
Also, you do not require to use the delete step as compiler cleans up the memory slots by itself.