December 21, 2021

Find missing number in a sequence Minimum complexity | n Log n

/**
 * Find missing number in a sequence Minimum complexity (n Log n)
 * 
 * input : {1,2,3,5}
 * output : 4
 */
package com.codecreeks.solutions;

import java.util.Arrays;

/**
 * @author Consumerfed Information Technology Section
 *
 */
public class MissingNumberArray {
private static int loopCount = 0;
public static void main(String[] args) {
long startTime = System.currentTimeMillis();
int[] a = {1,2,3,4,6,7,8,9,10,11,12};
int len = a.length;
MissingNumberArray m = new MissingNumberArray();
int value = 0;
if(a[len-1]!=len) {
value = m.findMissingNumber(a, 0, len);
System.out.println(" The Missing number in the array :"+Arrays.toString(a)+" is "+value);
}else {
loopCount++;
System.out.println(" There is no missing number in the given array "+Arrays.toString(a));
}
System.out.println(" For "+len+" size array it tooks "+loopCount+" search to find the answer ");
System.out.println(" Complexity :"+len*Math.log(len));
System.out.println(" Time Taken : "+(System.currentTimeMillis() - startTime)+" ms");
}
private int findMissingNumber(int[] array, int startPstn, int endPstn) {
loopCount++;
int arraySize = endPstn - startPstn;
int position = startPstn + arraySize / 2;
if(arraySize==0) {
return position +1;
}else if (arraySize == 1) {
return array[position] + 1;
}
else if (array[position] != position + 1) {
return findMissingNumber(array, startPstn, position);
} else {
return findMissingNumber(array, position + 1, endPstn);
}
}
}

December 14, 2021

Squaring and Sorting an input array contains negative and positive number | complexity

/**
 * Squaring and Sorting an input array contains negative and positive number
 * 
 * Complexity O(2n)
 * 
 */
package consumerfed;

import java.util.Arrays;

/**
 * @author konzerntech
 *
 */
public class SquareAndSort {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

int[] input = { -10, -8, -3, -1, 4, 6, 8 };
int len = input.length;
int[] output = new int[len];

int[] a = new int[len];
int[] b = new int[len];

int aLen = 0;
int bLen = 0;

for (int i = 0; i < len; i++) {
int value = input[i];
int square = value * value;
if (value < 0) {
a[aLen] = square;
aLen++;
} else {
b[bLen] = square;
bLen++;
}
}

int aPtr = aLen-1;
int bPtr = 0;


for (int i = 0; i < len; i++) {

if (bPtr > (bLen - 1)) {
while (aPtr >= 0) {
output[i] = a[aPtr];
i++;
aPtr--;
}
break;
}

if (aPtr < 0) {
while (bPtr < bLen) {
output[i] = b[bPtr];
i++;
bPtr++;
}
break;
}

if (b[bPtr] < a[aPtr]) {
output[i] = b[bPtr];
bPtr++;
} else {
output[i] = a[aPtr];
aPtr--;
}

}
System.out.println("Input : "+Arrays.toString(input));
System.out.println("Output : "+Arrays.toString(output));
}

}

December 07, 2021

An application help to know buy or sell stock in stockmaster

Hi Team


We are planning to develop an application where any user who doesnt know about stock master can buy or sell stocks

The application is developed in java spring boot

Git url


Thanks @sanoop kakkoor for his #support

November 28, 2021

English to malayalam translation java code

Hi Team

English to Malayalam translation java code is available in GitHub


The translation is not 100% accurate , but the logic remains the same.you can modify the code accordingly, you can even raise the bug in the git itself. The translation will not take any time, performance is high, developed using plain java code.


https://github.com/consumerfed

Please comment and revisit the blog

November 14, 2021

Wipro interview question - how to move the said value to one end of an array



package com.interviewquestions.wipro;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
 * 
 * @author nao jinguji
 *
 */
public class Wipro {

public static void main(String[] args) {
// List<Integer> input = List.of(2,1,2,2,2,3,4,2);
// List<Integer> input = Arrays.asList(arr);
// int toMove = 2;
/*
List<Integer> output = new ArrayList(input.size());
for(int i :input) {
if(i!=toMove) {
output.add(i);
}
}
int len = input.size() -output.size();
for(int i =0; i<len; i++ ) {
output.add(toMove);
}
System.out.println(output);
System.out.println("------------"); */
int[] input = {2,1,2,2,2,3,4,2};
int toMove = 2;
int ptr = 0;
for(int i =0; i<input.length; i++ ) {
int value = input[i];
if(value!=toMove) {
input[ptr] = value;
input[i] = toMove;
ptr++;
}
}
for(int i =0; i<input.length; i++ ) {
System.out.print(input[i]);
}
}

}

September 21, 2021

Firebase | Firestore | Firestore junit test | deep stubbing mockito

This is a sample code how to perform deep stubbing mockito on firestore
you need to mock all the 


public class FirestoreClientTest{

@Mock
Firestore firestore;

@Mock
DocumentReference documentReference;

@Mock
CollectionReference collectionReference;

@Mock
ApiFuture apiFuture;

@Mock
QuerySnapshot querySnapshot;

@Test
public void test(){
when(firestore.collection(any(String.class)).thenReturn(collectionReference);
when(collectionReference.document(any(String.class)).thenReturn(documentReference);
when(documentReference.get()).thenReturn(apiFuture);
when(apiFuture.get()).thenReturn(querySnapshot);

UserInfo userInfo = firestore.getUserDetails();

//Assert statements
}

}

September 14, 2021

Google Firebase Firestore Spring boot Integration sample code

1. Create a new Cloud Firestore database in your GCP project

2. If you are authenticated in the Cloud SDK, your credentials will be automatically found by the Spring Boot Starter for Google Cloud Firestore.

3. Pom dependency

<!-- https://mvnrepository.com/artifact/com.google.cloud/spring-cloud-gcp-starter -->
<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>spring-cloud-gcp-starter</artifactId>
    <version>2.0.4</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.google.cloud/google-cloud-firestore -->
<dependency>
    <groupId>com.google.cloud</groupId>
    <artifactId>google-cloud-firestore</artifactId>
    <version>3.0.1</version>
</dependency>



4. Repository (writing data)

@Autowired
Firestore firestore;

User data = new User("javabelazy",
Arrays.asList(
new Phone(12345, PhoneType.CELL),
new Phone(54321, PhoneType.WORK)));

WriteResult writeResult = this.firestore.document("users/id").set(data).get();

5. Application.properties

spring.cloud.gcp.firestore.project-id =abcdefg

6. Git URL

August 28, 2021

Work inside a software firm

Hi friends

I would like to share few things through this post, I have been worked in many software firms from product based company to service based company. Small firms to large firm, even MNC's. I feel like some small firms are good to work. 

As a contract employee in an MNC, Some manager behaves to us like we are slaves. They know our aim is to get a permanent job in that firm they will use this as opportunity and keep adding works to us. We were in such a situation we want to ask a small time break in public holidays as well.

This covid situation has changed the way the work environment, most employees under the surverlience camera of managers, micromanagement or mental stress what ever we can call, some point these might me the reason for the most of the disease the employees are suffering now, they even intentially forget this work from home is due the pandemic situation, the HR team will keep silent.

I saw peoples crying due to their sudden termination, I read newspaper posting news of IT peoples suicides. Some people simply quit this profession.

In the coming post I will mention the company name as well as the managers.

August 21, 2021

How to get httprequest inside controller of spring boot

private @Autowired HttpServletRequest request;

HttpServletRequest curRequest = 
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();

August 14, 2021

How to get the Path Variables from a URL inside a Spring interceptor

How to get the Path Variables in URL inside a Spring interceptor


  •              Assume the URI is http://javabelazy/status/{statusId} and our interceptor is registered for this URI.
  •               This map would then be a map of a elements,with keys 'statusId ' 
              

public class JWTInterceptor extends HandlerInterceptorAdapter{
    @Override
  public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler)
  throws Exception
  {

    final Map<String, String> pathVariables = (Map<String, String>) request
                                                                    .getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            
               
               final Integer status = Integer.valueOf(pathVariables.get("statusId"));
               
            
  }
}


August 08, 2021

MyG Digital | The best electronic online store | cheating shared in instagram | iphone cheating

A viral video shared by pb dileep in instagram

https://www.instagram.com/tv/CRsznDnHeMz/?utm_medium=copy_link

August 07, 2021

Tikdata coding test solution



input txt is a file  with data known as ‘tickData’. This file consists of several columns. For this question we will consider only "STOCK","LTP","TIME" columns. Rest columns and values

can be ignored.
There are two task you need to perform :

TASK 1 : Convert tickData file in OHLC File :

tick data is the price of the particular stock at any given time. you need to group the data for each stock for each minute and find its Open (first price in that minute) ,
High (highest price in that minute), Low (lowest price in that minute), close(last price of that minute) for that minute. This is called OHLC (open/high/low/close) data.

In a minute we can receive the price of the stocks for upto 100 times.(Not fixed)
e.g.

"STOCK" "LTP" "TIME"
"NQ" 6972.75 08.11.51.319 AM
"NQ" 6974.25 08.12.12.761 AM
"NQ" 6975.25 08.12.42.728 AM
"NQ" 6973.75 08.13.12.700 AM
"NQ" 6974.25 08.13.42.768 AM


For given input above, Output will be

STOCK Open High Low Close TIME
NQ 6972.75 6972.75 6972.75 6972.75 01-NOV-18 08.11.00.00 AM
NQ 6974.25 6975.25 6974.25 6975.25 01-NOV-18 08.12.00.00 AM
NQ 6973.75 6974.25 6973.75 6974.25 01-NOV-18 08.13.00.00 AM

Basically take all prices for the stock in a particular minute, Find its open, high, low, close and print it along with a time and stock name (tab separated).

TASK 2 :

Now since you have OHLC data with you from step 1, you need to calculate the zScore for the stocks. please follow the steps given below to find the zScore of the stocks at a given minute.

1. At any given minute, take the last 20 close prices for that stock. e.g. If we're calculating zScore for 08:20:00 AM , we will take all close prices for the stock from 08:00:00 to 08:19:00.
2. Since we have a list of the last 20 close prices, we will calculate average and standard deviation of the close prices.
3. Now we have average and standard deviation of last 20 prices and current minutes data as well. so zScore = (current_close - average)/standard_deviation;

e.g.
Consider from Task 1 you got the following OHLC data. (This is sample Data only for explanation and not actual data)

Stock open high low close time
NQ 100 100.2 99 100.2 01-NOV-18 09.10.00.00 AM
NQ 100 101.2 99 101.2 01-NOV-18 09.11.00.00 AM
NQ 100 100.2 99 99 01-NOV-18 09.12.00.00 AM
NQ 100 100.2 99 100 01-NOV-18 09.13.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.14.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.15.00.00 AM
NQ 100 100.2 99 100 01-NOV-18 09.16.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.17.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.18.00.00 AM
NQ 100 103 99 103 01-NOV-18 09.19.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.20.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.21.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.22.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.23.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.24.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.25.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.26.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.27.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.28.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.29.00.00 AM
NQ 100 100.2 99 100.2 01-NOV-18 09.30.00.00 AM

Now if we wish to calculate zScore at 01-NOV-18 09.30.00.00 AM, We will take previous 20 close prices i.e. From 01-NOV-18 09.10.00.00 AM to 01-NOV-18 09.29.00.00 AM.
Calculate average of the prices and standard_deviation for the same.
average = 100.31
standard_deviation = 0.72974
zScore  = (100.2-100.31)/0.72974 = -1.5073


Output should be:

Stock zScore time
NQ -1.5073 01-NOV-18 09.30.00.00 AM
and so on.


Solution



#MygDigital cheating

July 28, 2021

Parking lot - problem and solution

Problem Statement I own a parking lot that can hold up to 'n' cars at any given point in time. Each slot is given a number starting at 1 increasing with increasing distance from the entry point in steps of one. I want to create an automated ticketing system that allows my customers to use my parking lot without human intervention. When a car enters my parking lot, I want to have a ticket issued to the driver. The ticket issuing process includes us documenting the registration number (number plate) and the colour of the car and allocating an available parking slot to the car before actually handing over a ticket to the driver (we assume that our customers are nice enough to always park in the slots allocated to them). The customer should be allocated a parking slot which is nearest to the entry. At the exit the customer returns the ticket with the time the car was parked in the lot, which then marks the slot they were using as being available. Total parking charge should be calculated as per the parking time. Charge applicable is $10 for first 2 hours and $10 for every additional hour. We interact with the system via a simple set of commands which produce a specific output.

 Please take a look at the example below, which includes all the commands you need to support - they're self explanatory


The system should accept a filename as a parameter at the command prompt and read the commands from that file. 

Example: File To install all dependencies, compile and run tests: $ bin/setup To run the code so it accepts input from a file: $ bin/parking_lot file_inputs.txt Commands 

• Create parking lot of size n : create_parking_lot {capacity} 
• Park a car : park {car_number} 
• Remove(Unpark) car from : leave {car_number} {hours} 
• Print status of parking slot : status Input (contents of file): create_parking_lot 6 park K
A-01-HH-1234 park 
KA-01-HH-9999 
park KA-01-BB-0001 
park KA-01-HH-7777 
park KA-01-HH-2701 
park KA-01-HH-3141 
leave KA-01-HH-3141 4 
status park KA-01-P-333 
park DL-12-AA-9999 
leave KA-01-HH-1234 4 
leave KA-01-BB-0001 6 
leave DL-12-AA-9999 2 
park KA-09-HH-0987 
park CA-09-IO-1111 
park KA-09-HH-0123 
status 
Output (to STDOUT): Created parking lot with 6 slots Allocated slot number: 1 Allocated slot number: 2 Allocated slot number: 3 Allocated slot number: 4 Allocated slot number: 5 Allocated slot number: 6 Registration number KA-01-HH3141 with Slot Number 6 is free with Charge 30 Slot No. Registration No. 1 KA-01-HH-1234 2 KA-01-HH-9999 3 KA-01-BB-0001 4 KA-01-HH-7777 5 KA-01-HH-2701 Allocated slot number: 6 Sorry, parking lot is full Registration number KA-01-HH1234 with Slot Number 1 is free with Charge 30 Registration number KA-01-BB0001 with Slot Number 3 is free with Charge 50 Registration number DL-12-AA-9999 not found Allocated slot number: 1 Allocated slot number: 3 Sorry, parking lot is full Slot No. Registration No. 1 KA-09-HH-0987 2 KA-01-HH-9999 3 CA-09-IO-1111 4 KA-01-HH-7777 5 KA-01-HH-2701 6 KA-01-P-333

July 21, 2021

What is Apigee

Apigee Edge is an api gateway provide by google, you can create a proxy layer for all API s



What you can achieve through Apigee?

you dont need to write code, just use the existing policies and modify it to your  own business logic.


Suppose : you need to create a proxy layer to endpoint "https://javabelazy/tutorials"
you need to specify the url in  TargetEndpoint 


1. set quota limit : you can specify the quota limit for your particular api, say 100 hit per second, dynamical limit can also be achieved, refer quoto policy, spike arrest policy etc

2. Authentication : LDAP, OAuth etc can be achieved.

3. Tranformation : You can transfer you request as well as response 


July 07, 2021

Spring boot Grpc google remote procedure call full source code

Hi Team

if you are searching for a GRPC server spring boot project, here is the link. the running code




GRPC is google Remote Procedure Call introduced in the year 2016.
The application runs in port 9090.


June 07, 2021

IllegalArgumentException no serializer found for class org.mockito and no properties discovered to create beanserializer [Solved]

Solution : (Mockito.anyObject(), Mockito.any(TypeReference.class))


Hi 

Recently I went through a scenario and got the below error while using object Mapper

java.lang.illegalargumentexception :no serializer found for class org.mockito.internal.invocation.mock ref.mock weakreference and no properties discovered to create beanserializer (to avoid exception disable serializationfeature.fail_on_empty_beans [ Solved ]

Here is the scenario


public class A{

@Autowired
private ObjectMapper obj;

private boolean isWar(Test abc){

  obj.convertValue(object, new TypeReference<Map<String,Object>>(){});
}

}


and my junit class is here



@Test
public void testSomething(){
when (objectMapper.convertValue(obj,map.class)).thenReturn(something);
}


Changing the convertValue parameter as (Mockito.anyObject(), Mockito.any(TypeReference.class)) solved the problem

April 14, 2021

HttpServlet stream closed : inputstream or reader can only be read once [solution]

The code will be working fine. description is not posted

The solution mentioned here has already worked succesfully. Dont think for a one line solution, its just like thinking of getting a smartphone for just 251.


Copy paste the following code

package com.javabelazy.filter;
 
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
 
public class HttpHelper {
    public static String getBodyString(HttpServletRequest request) throws IOException {
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = request.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
}


A wrapper class

package com.javabelazy.filter;
 
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
 
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
 
public class RequestReaderHttpServletRequestWrapper extends HttpServletRequestWrapper{
 
    private final byte[] body;
 
    public RequestReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        body = HttpHelper.getBodyString(request).getBytes(Charset.forName("UTF-8"));
    }
 
    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }
 
    @Override
    public ServletInputStream getInputStream() throws IOException {
 
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
 
        return new ServletInputStream() {
 
            @Override
            public int read() throws IOException {
                return bais.read();
            }
 
            @Override
            public boolean isFinished() {
                return false;
            }
 
            @Override
            public boolean isReady() {
                return false;
            }
 
            @Override
            public void setReadListener(ReadListener readListener) {
 
            }
        };
    }
}

Filter class

package com.javabelazy.filter;
 
 
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
 
 
public class HttpServletRequestReplacedFilter implements Filter {
    @Override
    public void destroy() {
 
    }
 
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;
        if(request instanceof HttpServletRequest) {
            requestWrapper = new RequestReaderHttpServletRequestWrapper((HttpServletRequest) request);
        }
        //Get the stream in the request, convert the fetched string into a stream, and put it into the new request object.
                 // Pass the new request object in the chain.doFiler method
        if(requestWrapper == null) {
            chain.doFilter(request, response);
        } else {
            chain.doFilter(requestWrapper, response);
        }
    }
 
    @Override
    public void init(FilterConfig arg0) throws ServletException {
 
    }
}

Add this to config

@Bean
public FilterRegistrationBean httpServletRequestReplacedRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new HttpServletRequestReplacedFilter());
registration.addUrlPatterns("/*");
        registration.addInitParameter("paramName", "paramValue");
registration.setName("httpServletRequestReplacedFilter");
registration.setOrder(1);
return registration;
}


you can make the filterregistrationBean a generic class


FilterRegistrationBean<HttpServletRequestReplacedFilter> registration = new FilterRegistrationBean();


or use the below annotation for filter class

 @Order(1)//Set the loading order of this class in the spring container
@Aspect
@Configuration

you can omit configuring bean in config class


Thanks for reading

February 07, 2021

Write a java program to search a value from 2D array

package com.hack.javacode;

/**

 *  @Author Vishnu parasad varma
 */

class Solution22 {

public boolean searchMatrix(int[][] matrix, int target) {

boolean found = false;

int row = matrix.length;

if (row > 0) {

for (int i = 0; i < row; ++i) {

if (!found) {
for (int j = 0; j < matrix[i].length; ++j) {
System.out.println(matrix[i][j]);

if (target == matrix[i][j]) {

found = true;
break;
}
}
}
}

}

return found;
}

public static void main(String[] args) {
Solution22 s = new Solution22();
int[][] nums = { { 1, 3, 5, 7 }, { 10, 11, 16, 20 }, { 23, 30, 34, 50 } };
int target = 38;
System.out.println(s.searchMatrix(nums, target));

}
}

January 28, 2021

Write a java program to rotate 1D array by n steps where n is a positive value

package com.leetcode.contest;

/**
 * Given an array, rotate the array to the right by k steps, where k is
 * non-negative.
 * 
 * Follow up:
 * 
 * Try to come up as many solutions as you can, there are at least 3 different
 * ways to solve this problem. Could you do it in-place with O(1) extra space?
 * 
 * @author Athul
 *
 */
class Solution21 {
public void rotate(int[] nums, int k) {

int len = nums.length;

int[] temp = new int[k];

int start = nums.length - k;

for (int i = 0; i < k; i++) {

temp[i] = nums[start];
start++;
}

int[] temp2 = new int[start];
int j = 0;
for (int i = 0; i < start; i++) {

temp2[i] = nums[j];
j++;
}
j = 0;
for (int i = 0; i < len; i++) {

if (i < k) {
nums[i] = temp[i];
} else {
nums[i] = temp2[j];
j++;
}

}
System.out.println();
}

public static void main(String[] args) {
Solution21 s = new Solution21();
int[] nums = { -1 };
s.rotate(nums, 2);
}
}

January 21, 2021

An Elephant and the Rope story | Motivational stories

As a man was passing the elephants, he suddenly stopped, confused by the fact that these huge creatures were being held by only a small rope tied to their front leg. No chains, no cages. It was obvious that the elephants could, at anytime, break away from their bonds but for some reason, they did not.

He saw a trainer nearby and asked why these animals just stood there and made no attempt to get away. “Well,” trainer said, “when they are very young and much smaller we use the same size rope to tie them and, at that age, it’s enough to hold them. As they grow up, they are conditioned to believe they cannot break away. They believe the rope can still hold them, so they never try to break free.”

The man was amazed. These animals could at any time break free from their bonds but because they believed they couldn’t, they were stuck right where they were.

Like the elephants, how many of us go through life hanging onto a belief that we cannot do something, simply because we failed at it once before?

Failure is part of learning; we should never give up the struggle in life

January 07, 2021

Coding test -parking lot problem solved

problem

I own a parking lot that can hold up to 'n' cars at any given point in time. Each slot is given a number starting at 1 increasing with increasing distance from the entry point in steps of one. I want to create an automated ticketing system that allows my customers to use my parking lot without human intervention. When a car enters my parking lot, I want to have a ticket issued to the driver. The ticket issuing process includes us documenting the registration number (number plate) and the colour of the car and allocating an available parking slot to the car before actually handing over a ticket to the driver (we assume that our customers are nice enough to always park in the slots allocated to them). The customer should be allocated a parking slot which is nearest to the entry. At the exit the customer returns the ticket with the time the car was parked in the lot, which then marks the slot they were using as being available. Total parking charge should be calculated as per the parking time. Charge applicable is AED 100 for first 2 hours and AED100 for every additional hour. We interact with the system via a simple set of commands which produce a specific output. Please take a look at the example below, which includes all the commands you need to support - they're self explanatory. The system should accept a filename as a parameter at the command prompt and read the commands from that file.

Solution

git hub url

Facebook comments