In: Computer Science
**java**
A bicycle combination lock has four rings with numbers 0 through 9. Given the actual numbers and the combination to unlock, print instructions to unlock the lock using the minimum number of twists. A “twist up” increases the number value of a ring, and a “twist down” decreases it. For example, if the actual number shown is 1729 and the desired combination is 5714, write your instructions like this:
Ring 1: Twist up 4 times
Ring 3: Twist down once
Ring 4: Twist up or down 5 times
Here is the solution for your question.
PLEASE DO UPVOTE:
OUTPUT:
RAWCODE:
import java.util.*;
public class Lock{
public static void main(String[] args)
{
int[] lockKey =
{5,7,1,4};
//Original Key
int[] userKey = new
int[4]; //Array
to store user key
Scanner sc = new Scanner(System.in);
for (int i=0;i<4;i++)
{
userKey[i] =
sc.nextInt(); //Storing User input
into userKey
}
int correct = 0,up,down;
for (int i=0;i<4;i++)
{
if (lockKey[i]
== userKey[i]) //If user key value
and original key value is equal then,increase correct by 1
correct++;
else if
(lockKey[i]>userKey[i]){ //If Lock key is greater
than userkey
up = Math.abs(lockKey[i] -
userKey[i]); //Up
rotaion will be lock key - user key
down =
Math.abs(((10-lockKey[i])+userKey[i])%10);//Down rotation, we use a
simple logic as it is a circular queue rotations will be
((10-lockKey[i])+userKey[i])%10)
if (up == down)
System.out.println("Ring
"+(i+1)+": Twist up or down "+down+" times"); //If up
and down rotaitons are equal then shows below message
else
System.out.println("Ring
"+(i+1)+": Twist "+(up>down?"down ":"up ")+Math.min(up,down)+"
times"); //Otherwise suggests either down or up
rotation.Which is best
}
else{ //If Lock key is less than
userkey
down = Math.abs(lockKey[i] -
userKey[i]); //Down rotaion will be
lock key - user key
up = Math.abs(((10-userKey[i])+lockKey[i])%10);
////Up rotation, we use a simple logic as it is a circular queue
rotations will be ((10-lockKey[i])+userKey[i])%10)
if (up == down)
System.out.println("Ring
"+(i+1)+": Twist up or down "+down+" times"); //If up
and down rotaitons are equal then shows below message
else
System.out.println("Ring
"+(i+1)+": Twist "+(up>down?"down ":"up ")+Math.min(up,down)+"
times"); //Otherwise suggests either down or up rotation.Which is
best
}
}
if (correct==4)
//If All user keys matches original key,then
lock opens
System.out.println("Lock Opened");
}
}
PLEASE DO UPVOTE.
THANK YOU!