Keyboard Switch Count
Keyboard Switch Count
PROBLEM STATEMENT :
There are three rows in a keyboard containing the alphabets. The alphabets in each row are given as the input. The string S containing the alphabets to be typed is passed as the input. The program must print the number of times, the switch must happen to type the alphabets. Assume initially the position is in the middle row.
Note: Assume S contains only lower case alphabets and no special characters will be present in S.
Boundary Condition(s):
1 <= Length of S <= 100
Input Format:
The first three lines contain the alphabets in the three rows of a keyboard.
The fourth line contains S.
Outupt Format:
The first line contains an integer representing the switch count.
Example Input/Output 1:
Input: ()
qwertyuiop
asdfghjkl
zxcvbnm
coding
Output:
8
Explanation:
The string to be typed is coding.
c - bottom row. Hence switch count is 1.
o - top row. So switch count = 1+2 = 3.
d - middle row. So switch count = 3+1 = 4.
i - top row. So switch count = 4+1 = 5.
n - bottom row. So switch count = 5+2 = 7.
g - middle row. So switch count = 7+1 = 8.
So 8 is printed as the output.
Example Input/Output 2:
Input: ()
qwertyuiop
asdfghjkl
zxcvbnm
gasstation
Output:
5
SOLUTION :
C (Programming Language)
#include<stdio.h>
#include<stdlib.h>
char row1[11],row2[11],row3[11];
int find(char ch)
{
if(strchr(row1,ch)!=NULL) return 1;
if(strchr(row2,ch)!=NULL) return 2;
if(strchr(row3,ch)!=NULL) return 3;
}
int main()
{
char str[101];
scanf("%s %s %s %s",row1,row2,row3,str);
int currRow=2, sum=0;
for(int i=0;i<strlen(str);i++)
{
char ch = str[i];
int newRow = find(ch);
sum += abs(newRow-currRow);
currRow = newRow;
}
printf("%d",sum);
}
C++ (CPP)
#include <bits/stdc++.h>
using namespace std;
char r1[11],r2[11],r3[11];
int find(char ch){
if(strchr(r1,ch)!=NULL) return 1;
if(strchr(r2,ch)!=NULL) return 2;
if(strchr(r3,ch)!=NULL) return 3;
}
int main(int argc, char** argv)
{
char str[101];
cin>>r1>>r2>>r3>>str;
int curr=2,sum=0;
for(int i=0;str[i];i++){
char ch=str[i];
int newrow=find(ch);
sum+=abs(newrow-curr);
curr=newrow;
}
cout<<sum;
}
JAVA
import java.util.*;
public class Hello {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String[] rows=new String[3];
for(int index=0;index<3;index++){
rows[index]=sc.nextLine();
}
int currRow=1,switchCount=0;
for(char ch:sc.nextLine().toCharArray()){
int charRow=0;
for(int index=0;index<3;index++){
if(rows[index].contains(ch+"")){
charRow=index;
}
}
if(currRow!=charRow){
switchCount+=Math.abs(currRow-charRow);
}
currRow=charRow;
}
System.out.print(switchCount);
}
}
PYTHON
d=dict()
d['#']=2
for i in list(input().strip()):
d[i]=3
for i in list(input().strip()):
d[i]=2
for i in list(input().strip()):
d[i]=1
s='#'+input().strip()
l=len(s);tot=0
for i in range(1,l):
tot+=abs(d[s[i]]-d[s[i-1]])
print(tot)
Comments
Post a Comment