write a java program for you are given a string representing a sequence of N arrows,each pointing in one of the four cardinal directions:up(^),down(v),left(<),right(>) . write a function solution that,given a string S denoting the direction of the arrows,returns the minimum number of arrows that must be rotated to make them all point in the same direction.
package com.company;
import java.util.Scanner;
public class Main {
// Function to get the specific character from the string
//to be used to access the index of a string
public static char getCharFromString(String str, int index)
{
return str.charAt(index);
}
static int lowest_to_change_arrow_direction(String my_string)
{
int string_length = my_string.length();
char up = '^';
char down = 'v';
char left = '<';
char right = '>';
//Now count the number of each to determine the count for each
int up_count = 0;
int down_count = 0;
int left_count = 0;
int right_count = 0;
for(int i = 0; i<string_length;i++)
{
int index = i;
// Get the specific character
char ch = getCharFromString(my_string, index);
if (ch == up)
{
up_count = up_count + 1;
}
else if (ch == down)
{
down_count = down_count + 1;
}
else if (ch == left)
{
left_count = left_count + 1;
}
else if (ch == right)
{
right_count = right_count+1;
}
else
{
//just do nothing
}
}
//now determine the maximum in order to know which direction others sholud follow
int[] directions ={up_count,down_count,left_count,right_count};
int maximum_index = 0;
int maximum = 0;
int lowet_sum = 0;
for(int j = 0; j < 4; j++)
{
if(directions[j]>maximum)
{
maximum = directions[j];
maximum_index = j;
}
}
//Now add the three lowest
for(int x = 0; x < 4; x++)
{
if(maximum_index != x)
{
lowet_sum = lowet_sum + directions[x];
}
}
return lowet_sum;
}
public static void main(String[] args) {
//driver program for testing
Scanner input = new Scanner(System.in);
System.out.println("Enter your string of arrows: ");
String my_string = input.nextLine();
int lowest = lowest_to_change_arrow_direction(my_string);
System.out.println("Minimum number of arrows that must be rotated\n" +
" to make them all point in the same direction is " +lowest);
}
}
Comments
Leave a comment