World's most popular travel blog for travel bloggers.
Showing posts with label Solved Assignments. Show all posts
Showing posts with label Solved Assignments. Show all posts
An algorithm is a finite set of steps defining the solution of a particular problem. An algorithm is expressed in pseudo code – something resembling C language or Pascal, but with some statements in English rather than within the programming language
  1. A sequential solution of any program that written in human language, called algorithm.
  2. Algorithm is first step of the solution process, after the analysis of problem, programmers write the algorithm of that problem.
Pseudo code 
  • Input Num
  • Initialize Len to zero and Y to Num
  • While Y is not zero
  •                Save Remainder by Y Mod 16 in array HEXD at index Len
  •                Initialize Y to Y divided 16
  •                Increment Len
  • for(Initialize I to Len-1 ; Condition I Greater than  -1 ;  Decrement I )
  •                If HEXD[I] Less than 10
  •                           HEXC[I]=HEXD[I]+48
  •                Else
  •                           HEXC[I]=HEXD[I]+55
  • Initialize HEXC[I] to NULL
  • Print HEXC
Detailed Algorithm:
Step 1:  Input NUM
Step 2:  LEN = 0 & Y=NUM
Step 3:  While (Y > 0)
                       HEXD[LEN]=Y%16
                       Y=Y/16
                       LEN++
Step 4: for(I=LEN-1;I>-1;I–)
                       IF(HEXD[I]<10)
                                HEXC[I]=HEXD[I]+48;
                       ELSE
                                HEXC[I]=HEXD[I]+55;
Step 5:  HEXC[I]=NULL
Step 5:  Print HEXC

Flowchart:-


SSL Client Application Components 

At a minimum, an SSL client application comprises the following components: 

Java client 

A Java client performs these functions:

  • Initialises an SSLContextwith client identity, a HostnameVerifierJSSE, a TrustManagerJSSE, and a HandshakeCompletedListener. 
  • Creates a keystore and retrieves the private key and certificate chain. 
  • Uses an SSLSocketFactory, and 
  • Uses HTTPS connect to a JSP served by an instance of WebLogic

HostnameVerifier


The HostnameVerifier implements the weblogic.security.SSL.HostnameVerifierJSSE interface. It provides a callback mechanism so that implementers of this interface can supply a policy for handling the case where the host that is being connected the server name from the c(SubjectDN) must match. 

HandshakeCompletedListener 

The HandshakeCompletedListener implements the javax.net.ssl.HandshakeCompletedListenerinterface. It defines how the SSL client receives notifications about the completion of an SSL handshake on a given SSL connection. It also defines the number od times an SSL handshake takes place on a given SSL connection. 

TrustManager

The TrustManager implements the weblogic.security.SSL.TrustManagerJSSE interface. it builts a certificate path to a trusted root and returns true if it can be validated and is trusted for client SSL authentication.

build script (build.xml)

This script compiles all the files required for the application and deploys them to the WebLogic Server applications directories.

Sample package code for this type program


package examples.security.sslclient;

import java.io.File;
import java.net.URL;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Hashtable;
import java.security.Provider;
import javax.naming.NamingException;
import javax.naming.Context;
import javax.naming.InitialContext
import javax.servlet.ServletOutputStream;
import weblogic.net.http.*;
import weblogic.jndi.Environment;
/** SSLClient is a short example of how to use the SSL library o
* WebLogic to make outgoi
* d
* WebLogic (in a Servlet).
*
*/

>> See complete program in STUDY MATERIAL MCS051 Block 3 Page 37
Coming soon

Become a Member to this website http://www.ignougroup.com/register/ and get informed 
#!/bin/bash
# isuserloggedin.sh
# Usage: isuserloggedin.sh username
# Shell script which checks after every one minute whether a user has logged in
# or not
# You can also run script in background using & then foreground it to view result

if [ $# -ne 1 ]
then
   echo "You supplied wrong arguments"
   echo "usage : `basename $0` username"
exit 1
fi

isuserexist()
{
grep -w "$1" /etc/passwd > /dev/null

if [ $? -eq 1 ]
then
   echo "$1 is not a valid user"
exit 1
fi
}

isuserexist $1
time=0
while true
do
#  you can replace following two statements with
#   if `who|grep $1 > /dev/null`
who|grep $1 > /dev/null
if [ $? -eq 0 ]
then
  echo "User $1 is logged in "
  if [ $time -gt 60 ]
  then
     hours=$((time/60))
     minutes=$((time%60))
     echo "He is logged in $hours hour(s) $minutes minute(s) late"
  else
     echo "He is logged in $time minute(s) late"
  fi
exit 0

else
let time++

# You can use following formats also
#   time=`expr $time + 1 `
#  time=$((time+1))

sleep 60
fi
done

Output:
[root@localhost shell]# sh isuserloggedin.sh
you have suplied wrong arguments
usage : isuserloggedin.sh username
[root@localhost shell]# sh isuserloggedin.sh root
User root is logged in
He is logged in 0 minute(s) late
[root@localhost shell]# sh isuserloggedin.sh roott
roott is not a valid user
Run script in background
[root@localhost shell]# sh isuserloggedin.sh venu &
[1] 15917
[root@localhost shell]# User venu is logged in
He is logged in 3 minute(s) late

[1]+ Done sh isuserloggedin.sh venu
Run script in background then foreground it
[root@localhost shell]# sh isuserloggedin.sh venu &
[1] 16223
[root@localhost shell]# fg
sh isuserloggedin.sh venu
User venu is logged in
He is logged in 1 minute(s) late
[root@localhost shell]#

Key Differences Between Strong Entity and Weak Entity

  1. The basic difference between strong entity and a weak entity is that the strong entity has a primary key whereas, a weak entity has the partial key which acts as a discriminator between the entities of a weak entity set.
  2. A weak entity always depends on the strong entity for its existence whereas, a strong entity is independent of any other entity’s existence.
  3. A strong entity is denoted with a single rectangle and a weak entity is denoted with a double rectangle.
  4. The relationship between two strong entities is denoted with single diamond whereas, a relationship between a weak and a strong entity is denoted with double diamond called Identifying Relationship.
  5. The strong entity may or may not show the total participation in its relations, but the weak entity always shows total participation in the identifying relationship which is denoted by the double line.
Design ER n Table accordingly

Question:

The following are the relational schemes of Employee, Project and Assigned-to Employee (Emp#, Emp_name, Profession), Project (Proj#, Proj_name, Chief_Architect), Assigned-to (Proj#, Emp#). 

Create appropriate samples of each relation according to the question. Write the following queries in SQL.
(i)  Get Emp# of employees working on Project numbered MCS-043.
(ii) Get details of employees working on database projects.
(iii) Finally create an optimal query tree for each query.




Given the following semi-structure data in XML, create the DTD 
(Document Type Declaration) for it 

<document>
    <student>
      <NAME>
      <Address>
    </student>
   <student>
      <NAME>
      <Address>
   </student>
</document>

What are the different options available for storing XML data?


Introduction

  • Project Name: - Medical Store Management 
  • This project is used mainly for medical stores to maintain the details of medical store such as stock and account. 
  • This medical shop management software is so designed as to ease the work load of medical shop professionals. The main feature includes inventory and stock control, accounting, client management

Scope & Objectives 

As this is generic software it can be used by a wide variety of outlets (Retailers) to automate the process of manually maintaining the records related to the subject of maintaining the stock and cash flows. 
This project is basically updating the manual chemist inventory System To Automated inventory system, So that organization can manage their record in efficient and organized form.

This software helps you to track all the products of medical shop moreover it’s a medical shop accounting software. Flexible and adaptive software suited to medical shops or stores or pharmacies of any size. 
 Project Characteristics: 
 Customer management 
 Transition management 
 Sales management 
 Reporting

 The main goal of the application is to maintain the records of purchase, Sales and stock details with cash transaction maintenance. 
 Medical Store Management software is very needy for Medical Store . This software help them maintain day to day transactions in computer.

Background & Specification

A medical store needs to maintain its inventory of medicines and other products using a 
computerized system. It is planning to create a network of computers which should be 
placed at various sales and cash counters. It also proposes to have a centralized 
workstation for the database and system administrators. Customer orders are accepted 
at the sales counters which in turn produces a medicine collection challan. The challan 
includes the order number, name of medicine, batch number, date of expiry, shelf 
number where it is kept and quantity ordered. One order may contain more than one 
medicine. As per challan, medicines are put in a basket by a person, who passes it to 
billing assistant. Billing assistant checks the medicine is as per the challan, any 
shortcoming is either corrected or reported to customer. On receiving conformation 
from the customer the bill is generated. The cash counter collects the money as per the 
bill and dispenses the medicine to the customer.

Project Features 

 There Will be two user Accessing System System 
 Manager : Who will act As Administrator 
 Other Staff: Who Will accessing the System 
 User The Features for manager are 
       Add ,delete update any product 
 Manage store i-e(put price,make salaries,Calculate Revenue )

User Classes and Characteristics 

 User Of project include customers and staff 
 Customer can be Member or visitor who are accessing this system. 
 Staff Which act as administrator and controlling overall system 
 User Should IT literate And know to use computer 
 Cashier Should Know Data entry & Typing 
 Manager should have knowledge of Internet & Browsing 

Operating environment 

 This project will be operating in windows environment.Also compatible with internet explorer. 
 The only requirement For using this project is having machine. Design and implemention constraints 
 This project is developed using java.on the back hand for database we are using Sql server. The product is Accomplished With the login facility for user. User Documentation 
 This project will include a user manual. The user manual include Complete overview of the producst,Configuration of the Tool used (Sql Sever or other), technical details, backup procedures and Contact Information which will include email address and Ph# .

Hardware Requirements 

 Processor : 1.6 Ghz and above
 RAM : 1GB RAM 
 Monitor : 1 5”Colour Monitor 
 Processor Speed : 1.7 GHZ 
 Hard disk : 10GB HDD 
 CD Drive : 52- X CD ROM 
 Keyboard : Mercury 110 Keys 
 Mouse : Logitech Mouse

System Features Description & priorirty 

 Proposed Database is intended to store, retrieve, update, andmanipulate information related to Chemist which include 
 Order Processing & taking 
 Staff information 
 Customer Bill Detail 
 Product Details 
 Calculation of Revenue
 Searching of product 
 Remainder About Products expiry,Shaortage 
 Generate Reports

Functional Requirements 

 The software must allow input of products data from Administrator& secured access at , and from the data streaming real-time monitoring equipment 
 The project must request username and password for access to data, only after authentication will allow access to the system. 
 The project must require high levels of error correction and input validation. 
 The project must allow browsing by the Director&Staff of Cms To Acces And update information products & Customers ,vendors. 
 The project must identify the Products & Customer by a unique numeric identifier derived from a function performed on the Customer’s birth date or product Id;

Safety Requirements 

 The Database may get crashed or damaged due to some viruses or operating system requirements.Therefore Its is mandatory to have backup for your data.Ups/inverter facility should be there in case of power failure. 
 Security Requirements 
 System will use secure Database 
 Staff can just see the products & mark their attendance .They Cannot edit or,modify anything except their personal information. 
 Proper user Authentication Will be provided. 
 There should be separate account for Admin &user. So that no one else can access the database except Admin.

User requirements 

 The User Of system are Staff ,Managers and customer of the store.
 The members share assumed to have basic knowledge of computer & internet browsing While administrator of system should have more knowledge so he/she can resolve small problems and perform information’s.
 The user manual ,installation guide and other related material should be sufficient to educate the user how to use and maintain the system.


DFD 0 Level
DFD 1 level
DFD Level 1



Download complete pdf for reference DFD, ERD and Data Dicionary
Click Here


Reason why we choose Waterfall model over Spiral Model

Spiral model
  1. Good for large and critical projects
  2. Working software is produced early during the lifecycle.
  3. Large amount of risk analysis.
As we know we don't have a big project, so there is no need to use Spiral Model


Reason why we choose Waterfall model over Iterative Model

Iterative Model

  1. Produces working software early during the life-cycle.
  2. More flexible as scope and requirement changes can be implemented at low cost.
  3. Testing and debugging is easier, as the iterations are small.
  4. Low risks factors as the risks can be identified and resolved during each iteration.
We already have a fixed requirement and already documented.

SDLC Model: Waterfall Model

Reason of selecting Waterfall Model


ØThis is Small Project and Requirements Are Well understood.
ØThis model is simple and easy to understand and use.

ØWaterfall model is simple to implement and also the amount of resources required for it are minimal.
ØIt is easy to manage due to the rigidity of the model – each phase has specific deliverables and a review process.

Data Mining: What is Data Mining?

Overview

Generally, data mining (sometimes called data or knowledge discovery) is the process of analyzing data from different perspectives and summarizing it into useful information - information that can be used to increase revenue, cuts costs, or both. Data mining software is one of a number of analytical tools for analyzing data. It allows users to analyze data from many different dimensions or angles, categorize it, and summarize the relationships identified. Technically, data mining is the process of finding correlations or patterns among dozens of fields in large relational databases.

Continuous Innovation

Although data mining is a relatively new term, the technology is not. Companies have used powerful computers to sift through volumes of supermarket scanner data and analyze market research reports for years. However, continuous innovations in computer processing power, disk storage, and statistical software are dramatically increasing the accuracy of analysis while driving down the cost.

Example

For example, one Midwest grocery chain used the data mining capacity of Oracle software to analyze local buying patterns. They discovered that when men bought diapers on Thursdays and Saturdays, they also tended to buy beer. Further analysis showed that these shoppers typically did their weekly grocery shopping on Saturdays. On Thursdays, however, they only bought a few items. The retailer concluded that they purchased the beer to have it available for the upcoming weekend. The grocery chain could use this newly discovered information in various ways to increase revenue. For example, they could move the beer display closer to the diaper display. And, they could make sure beer and diapers were sold at full price on Thursdays.

Data, Information, and Knowledge

Data

Data are any facts, numbers, or text that can be processed by a computer. Today, organizations are accumulating vast and growing amounts of data in different formats and different databases. This includes:
  • operational or transactional data such as, sales, cost, inventory, payroll, and accounting
  • nonoperational data, such as industry sales, forecast data, and macro economic data
  • meta data - data about the data itself, such as logical database design or data dictionary definitions

Information

The patterns, associations, or relationships among all this data can provide information. For example, analysis of retail point of sale transaction data can yield information on which products are selling and when.

Knowledge

Information can be converted into knowledge about historical patterns and future trends. For example, summary information on retail supermarket sales can be analyzed in light of promotional efforts to provide knowledge of consumer buying behavior. Thus, a manufacturer or retailer could determine which items are most susceptible to promotional efforts.

Data Warehouses

Dramatic advances in data capture, processing power, data transmission, and storage capabilities are enabling organizations to integrate their various databases into data warehouses. Data warehousing is defined as a process of centralized data management and retrieval. Data warehousing, like data mining, is a relatively new term although the concept itself has been around for years. Data warehousing represents an ideal vision of maintaining a central repository of all organizational data. Centralization of data is needed to maximize user access and analysis. Dramatic technological advances are making this vision a reality for many companies. And, equally dramatic advances in data analysis software are allowing users to access this data freely. The data analysis software is what supports data mining.

What can data mining do?

Data mining is primarily used today by companies with a strong consumer focus - retail, financial, communication, and marketing organizations. It enables these companies to determine relationships among "internal" factors such as price, product positioning, or staff skills, and "external" factors such as economic indicators, competition, and customer demographics. And, it enables them to determine the impact on sales, customer satisfaction, and corporate profits. Finally, it enables them to "drill down" into summary information to view detail transactional data.
With data mining, a retailer could use point-of-sale records of customer purchases to send targeted promotions based on an individual's purchase history. By mining demographic data from comment or warranty cards, the retailer could develop products and promotions to appeal to specific customer segments.
For example, Blockbuster Entertainment mines its video rental history database to recommend rentals to individual customers. American Express can suggest products to its cardholders based on analysis of their monthly expenditures.
WalMart is pioneering massive data mining to transform its supplier relationships. WalMart captures point-of-sale transactions from over 2,900 stores in 6 countries and continuously transmits this data to its massive 7.5 terabyte Teradata data warehouse. WalMart allows more than 3,500 suppliers, to access data on their products and perform data analyses. These suppliers use this data to identify customer buying patterns at the store display level. They use this information to manage local store inventory and identify new merchandising opportunities. In 1995, WalMart computers processed over 1 million complex data queries.
The National Basketball Association (NBA) is exploring a data mining application that can be used in conjunction with image recordings of basketball games. The Advanced Scout software analyzes the movements of players to help coaches orchestrate plays and strategies. For example, an analysis of the play-by-play sheet of the game played between the New York Knicks and the Cleveland Cavaliers on January 6, 1995 reveals that when Mark Price played the Guard position, John Williams attempted four jump shots and made each one! Advanced Scout not only finds this pattern, but explains that it is interesting because it differs considerably from the average shooting percentage of 49.30% for the Cavaliers during that game.
By using the NBA universal clock, a coach can automatically bring up the video clips showing each of the jump shots attempted by Williams with Price on the floor, without needing to comb through hours of video footage. Those clips show a very successful pick-and-roll play in which Price draws the Knick's defense and then finds Williams for an open jump shot.

How does data mining work?

While large-scale information technology has been evolving separate transaction and analytical systems, data mining provides the link between the two. Data mining software analyzes relationships and patterns in stored transaction data based on open-ended user queries. Several types of analytical software are available: statistical, machine learning, and neural networks. Generally, any of four types of relationships are sought:
  • Classes: Stored data is used to locate data in predetermined groups. For example, a restaurant chain could mine customer purchase data to determine when customers visit and what they typically order. This information could be used to increase traffic by having daily specials.
  • Clusters: Data items are grouped according to logical relationships or consumer preferences. For example, data can be mined to identify market segments or consumer affinities.
  • Associations: Data can be mined to identify associations. The beer-diaper example is an example of associative mining.
  • Sequential patterns: Data is mined to anticipate behavior patterns and trends. For example, an outdoor equipment retailer could predict the likelihood of a backpack being purchased based on a consumer's purchase of sleeping bags and hiking shoes.
Data mining consists of five major elements:
  • Extract, transform, and load transaction data onto the data warehouse system.
  • Store and manage the data in a multidimensional database system.
  • Provide data access to business analysts and information technology professionals.
  • Analyze the data by application software.
  • Present the data in a useful format, such as a graph or table.
Different levels of analysis are available:
  • Artificial neural networks: Non-linear predictive models that learn through training and resemble biological neural networks in structure.
  • Genetic algorithms: Optimization techniques that use processes such as genetic combination, mutation, and natural selection in a design based on the concepts of natural evolution.
  • Decision trees: Tree-shaped structures that represent sets of decisions. These decisions generate rules for the classification of a dataset. Specific decision tree methods include Classification and Regression Trees (CART) and Chi Square Automatic Interaction Detection (CHAID) . CART and CHAID are decision tree techniques used for classification of a dataset. They provide a set of rules that you can apply to a new (unclassified) dataset to predict which records will have a given outcome. CART segments a dataset by creating 2-way splits while CHAID segments using chi square tests to create multi-way splits. CART typically requires less data preparation than CHAID.
  • Nearest neighbor method: A technique that classifies each record in a dataset based on a combination of the classes of the k record(s) most similar to it in a historical dataset (where k 1). Sometimes called the k-nearest neighbor technique.
  • Rule induction: The extraction of useful if-then rules from data based on statistical significance.
  • Data visualization: The visual interpretation of complex relationships in multidimensional data. Graphics tools are used to illustrate data relationships.

What technological infrastructure is required?

Today, data mining applications are available on all size systems for mainframe, client/server, and PC platforms. System prices range from several thousand dollars for the smallest applications up to $1 million a terabyte for the largest. Enterprise-wide applications generally range in size from 10 gigabytes to over 11 terabytes. NCR has the capacity to deliver applications exceeding 100 terabytes. There are two critical technological drivers:
  • Size of the database: the more data being processed and maintained, the more powerful the system required.
  • Query complexity: the more complex the queries and the greater the number of queries being processed, the more powerful the system required.
Relational database storage and management technology is adequate for many data mining applications less than 50 gigabytes. However, this infrastructure needs to be significantly enhanced to support larger applications. Some vendors have added extensive indexing capabilities to improve query performance. Others use new hardware architectures such as Massively Parallel Processors (MPP) to achieve order-of-magnitude improvements in query time. For example, MPP systems from NCR link hundreds of high-speed Pentium processors to achieve performance levels exceeding those of the largest supercomputers.

Discuss in detail the features, Process management, Memory management, I/O and File management and Security and Protection in Windows 10 Operating System.


Features

  • There's loads of stuff for touch, but it's different stuff
  • Office Apps Get Touch Support
  • Universal Apps
  • Improved Multitasking
  • Continuum
  • Start Menu Returns
  • Action Center
  • Unified Settings / Control Panel
  • Cortana on Desktop
  • Improvements to Windows Explorer
  • Snap Assist helps you snap windows
  • The Command Prompt enters the 21st Century

Process management


Memory Management



File Management

In Windows 10, Microsoft is making many improvements regarding storage. For starters, the new version has a much smaller footprint for installation. If you're making a clean install, you'll notice that Windows 10 takes a lot less space, often less than 10 GB.
Through the Settings app on System > Storage, users can easily manage their storage space, and move default saved locations to an external hard drive. You can even click on each hard drive to view what's taking up space in your system. Very useful information and very easy to use for beginners.
Quick Access ToolbarHere you can pin your most frequently accessed commands. Quick Access also automatically pins your most frequently accessed folders.
Ribbon ToolbarIf you are familiar with Microsoft Office or apps such as Paint and WordPad, the Ribbon toolbar command is used to manage your files and often reveals hidden commands quickly. When you select a file or folder, this will display a contextual tab with additional options. You can copy, move, delete, rename, and a host of other tasks using the Ribbon.
Navigation and Address BarYou can use these to navigate smoothly through a folder’s hierarchy or back and forward between folders. The Address bar also has a breadcrumb menu that makes it easy to navigate to a different folder path.
Quick AccessHere you can find your most frequently accessed folders and also ones you have pinned show up here, which is a new feature in Windows 10.
OneDrive synced foldersIf you have a Microsoft Account setup with your Windows 10 PC, you can have your files stored in the online storage service and have them synced to your computer.
This PCIn previous versions of Windows, this was called Computer Explorer. Here you can view and manage your internal storage and attached storage devices including optical media.
SearchUse the search command to find files stored in the current folder.
Status barDisplays information about the contents stored in the window, such the amount of files, size, file selection and quick access to folder layout.

Windows 10 security

  1. Threat resistance
  2. Virtualization-based security
    • Hypervisor Code Integrity (HVCI).
    • Local Security Authority (LSA).
  3. Device Guard
  4. Configurable code integrity
  5. Measured Boot and remote attestation
  6. Improvements in Windows Defender
  7. Information protection
  8. Windows Information Protection
  9. Improvements in BitLocker
  10. Identity protection and access control
  11. Microsoft Passport
  12. Windows Hello
    • Facial recognition.
    • Fingerprint recognition.
    • Iris recognition.
  13. Credential Guard




Windows 10 featureTPMInput/output memory management unitVirtualization extensionsSLATUEFI 2.3.1x64 architecture only
Credential GuardRNYYYY
Device GuardNYYYYY
BitLockerRNNNNN
Configurable code integrityNNNNRR
Microsoft PassportRNNNNN
Windows HelloRNNNNN
VBSNYYYNY
UEFI Secure BootRNNNYN
Device health attestation through Measured BootYNNNYY

Study and implement the Lamport’s Bakery Algorithm for Interprocess synchronization using C/C++ programming language.


In Detail: 

One decentralized algorithm in common use, for example, in bakeries, is to issue numbers to each customer. When the customers want to access the scarce resource (the clerk behind the counter), they compare the numbers on their slips and the user with the lowest numbered slip wins.

The problem with this is that there must be some way to distribute numbers, but this has been solved. In bakeries, we use a very small server to distribute numbers, in the form of a roll of tickets where conflicts between two customers are solved by the fact that human hands naturally exclude each other from the critical volume of space that must be occupied to take a ticket. We cannot use this approach for solving the problem on a computer.

Before going on to more interesting implementations for distributing numbers, note that clients of such a protocol may make extensive use of their numbers! For example, if the bakery contains multiple clerks, the clients could use their number to select a clerk (number modulo number of clerks). Similarly, in a FIFO queue implemented with a bounded buffer, the number modulo the queue size could indicate the slot in the  buffer to be used, allowing multiple processes to simultaneously place values in the queue.

Lamport’s Bakery Algorithm provides a decentralized implementation of the “take a number” idea. As originally formulated, this requires that each competing process share access to an array, but later distributed algorithms have eliminated this shared data structure. Here is the original formulation:


For each process, i, there are two values, C[i] and N[i], giving the status of process I and the number it has picked. In more detail:

N[i] = 0 --> Process i is not in the bakery. 
N[i] > 0 --> Process i has picked a number and is in the bakery. 
C[i] = 0 --> Process i is not trying to pick a number. 
C[i] = 1 --> Process i is trying to pick a number. 
when 
N[i] = min( for all j, N[j] where N[j] > 0 ) 
Process i is allowed into the critical section. 
Here is the basic algorithm used to pick a number: 
C[i] := 1; 
N[i] := max( for all j, N[j] ) + 1; 
C[i] := 0; 

In effect, the customer walks into the bakery, checks the numbers of all the waiting
customers, and then picks a number one larger than the number of any waiting
customer.

If two customers each walk in at the same time, they are each likely to pick the same
number. Lamport’s solution allows this but then makes sure that customers notice that
this has happened and break the tie in a sensible way.

To help the customers detect ties, each customer who is currently in the process of
picking a number holds his hand up (by setting C[i] to 1. s/he pulls down his hand
when s/he is done selecting a number -- note that selecting a number may take time,
since it involves inspecting the numbers of everyone else in the waiting room.

 Solution

A process does the following to wait for the baker: 
Step 1: 
while (for some j, C(j) = 1) do nothing; 
First, wait until any process which might have tied with you has finished selecting 
their numbers. Since we require customers to raise their hands while they pick 
numbers, each customer waits until all handsare down after picking a number in order 
to guarantee that all ties will be cleanly recognised in the next step. 
Step 2: 
repeat 
W := (the set of j such that N[j] > 0) 
(where W is the set of indeces of waiting processes) 
M := (the set of j in W 
such that N[j] <= N[k] 
for all k in W) 
(where M is the set of process indices with minimum numbers) 
j := min(M) 
(where is in M and the tie is broken) 
until i = j;

C implementation 

#include "pthread.h"
#include "stdio.h"
#include "unistd.h"
#include "string.h"
#define MEMBAR __sync_synchronize()
#define THREAD_COUNT 8
volatile int tickets[THREAD_COUNT];
volatile int choosing[THREAD_COUNT];
volatile int resource;
void lock(int thread) {
choosing[thread] = 1;
MEMBAR;
int max_ticket = 0;
for (int i = 0; i < THREAD_COUNT; ++i) {
int ticket = tickets[i];
max_ticket = ticket > max_ticket ? ticket : max_ticket;
}
tickets[thread] = max_ticket + 1;
MEMBAR;
choosing[thread] = 0;
MEMBAR;
for (int other = 0; other < THREAD_COUNT; ++other) {
while (choosing[other]) { }
MEMBAR;
while (tickets[other] != 0 &&
(tickets[other] < tickets[thread] ||
(tickets[other] == tickets[thread] && other < thread))) { }
}
}
void unlock(int thread) {
MEMBAR;
tickets[thread] = 0;
}
void use_resource(int thread) {
if (resource != 0) {
printf("Resource was acquired by %d, but is still in-use by %d!\n",
thread, resource);
}
resource = thread;
printf("%d using resource...\n", thread);
MEMBAR;
sleep(2);
resource = 0;
}
void *thread_body(void *arg) {
long thread = (long)arg;
lock(thread);
use_resource(thread);
unlock(thread);
return NULL;
}
int main(int argc, char **argv) {
memset((void*)tickets, 0, sizeof(tickets));
memset((void*)choosing, 0, sizeof(choosing));
resource = 0;
pthread_t threads[THREAD_COUNT];
for (int i = 0; i < THREAD_COUNT; ++i) {
pthread_create(&threads[i], NULL, &thread_body, (void*)((long)i));
}
for (int i = 0; i < THREAD_COUNT; ++i) {
pthread_join(threads[i], NULL);
}
return 0;
}
Second, wait until your ticket number is the minimum of all tickets in the room. There
may be others with this minimum number, butin inspecting all the tickets in the room, you found them! If you find a tie, see if your customer ID number is less than the ID numbers of those with whom you’ve tied, and only then enter the critical section and meet with the baker.

Conclusion

The solution shown above is simple. Instead of computing the value of the smallest
number, compute the minimum process ID among the processes that hold the smallest
value. In fact, we need not seek the minimum process ID, all we need to do is use any
deterministic algorithm that all participants can agree on for breaking the tie. As long
as all participants apply the same deterministic algorithms to the same information,
they will arrive at the same conclusion.