2
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

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

  • Thank you, that is what I was looking for! – frost Jun 12 at 19:05
  • Glad that worked. Happy to help. – biplavo Jun 12 at 19:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.