Finding an element in array

by frost   Last Updated June 12, 2019 19:28 PM

pragma solidity ^0.4.17;

contract Transport {
   address public manager;
   Car[] public carArray;
   Bike[] public bikeArray;

   struct Car {
      uint carId;
      address carOwner;
   }

   struct Bike {
      uint bikeId;
      address bikeOwner;
   }

   function Transport(address creator) public {
        manager = creator;
   }

   function carCreate(uint carId, address carOwner) public {

        Car memory newCar = Car ({
            carId: carId,
            carOwner: carOwner
        });

        //push this number into array
        carArray.push(newCar);
   }

   function bikeCreate(uint bikeId, address bikeOwner) public {

        Bike memory newBike = Bike ({
            bikeId: bikeId,
            bikeOwner: bikeOwner
        });

        //push this number into array
        bikeArray.push(newBike);
   }

   function createNewBatch(uint batchId, uint carId, uint bikeId) public {

        // check the existence of carId and bikeId before proceeding
        // require(carArray.carId.exists);
        // require(bikeArray.bikeId.exists);
        ...
        ...
   }
}

I am trying to write a contract of supply chain of transport, where cars and bikes are created and are required to be put in batches before being transported.

I got stuck in createNewBatch function since before putting everything into one batch (to be shipped later), I want to check whether the inputed carId and bikeId actually exist.

My logic is that I have to go back to the array of all the cars and bikes and check whether the supplied carId and bikeId matches any carId and bikeId in carArray and bikeArray. However, it does not work in terms of code. Would appreciate your help

Tags : solidity


Answers 1


Solution :

1) Store length of the Car array as well when creating new car : say carLength. Increase it as you add new one.

2) Similarly, store length of the Bike array : bikeLength

3) Loop i from 0 to carLength-1 and check Car[i].id == id to check if the car id is present

4) Perform same approach as step 3 for bike as well

Better Solution :

1) Create a mapping for Car Search : mapping(uint => bool) allCars, uint for carId

2) As you create new Car or Bike, also insert id into the allCars : allCars[carId] = true

3) Similarly allBikes[bikeId] = true

4) Now just query the map using carId or bikeId : allCars[carId] or allBikes[bikeId] will return true or false

biplavo
biplavo
June 12, 2019 19:01 PM

Related Questions


Updated October 09, 2018 12:28 PM

Updated November 28, 2018 04:28 AM

Updated December 12, 2018 08:28 AM

Updated January 10, 2019 23:28 PM

Updated July 23, 2018 00:28 AM