DAILY CODING CHALLENGE (DECEMBER 2018)

12.31.2018

12.30.2018

12.29.2018

12.28.2018

12.27.2018

12.26.2018

12.25.2018

12.24.2018

12.23.2018

12.22.2018

12.21.2018

12.20.2018

12.19.2018

12/18/2018

12/17/2018

12/16/2018

12/15/2018

12/14/2018

12/13/2018

12/12/2018

12/11/2018

12/10/2018

12/9/2018

12/6/2018

12/5/2018

12/4/2018

12/3/2018


12.31.2018

#12.31.2018 - Shashi
#Write a program that accepts RGB color values (0-255) and returns the Hexadecimal equivalent of it.
#If values <0 or >255 are sent then round them off to nearest valid value.

def rgb(r, g, b): #function starts here
   
return "{:02X}{:02X}{:02X}".format(validate(r), validate(g), validate(b))
#single line return with validation checks + hex formatting

def validate(num): #function for validating values
   
if num < 0: #if value less than 0
       
return 0 #return 0
   
if num > 255: #if value greater than 255
       
return 255 #return 255
   
return num #else return the value as is.

#function calls
print(rgb(
234,0,0)) #send R, G and B values are parameters to function
print(rgb(
-12,-2,10)) #sending values < 0
print(rgb(
286,224,100)) #sending values > 255
#program ends


12.30.2018

#rot13 encryption program.
#Take a string message and convert each letter to 13 characters after it.
#Loop back for letters extending beyond z.
#Example: "hello" is encrypted as "uryyb"
#12.30.2018 - Shashi

def rot13(message):
   output =
"" #to hold final converted output
   
# Loop through each character in message.
   
for i in message:
       
# convert character to number.
       c = ord(i)
       
# Add or remove 13 to it depending on position.
       
if c >= ord('a') and c <= ord('z'): #if char between a and z
           
if c > ord('m'): #if value > m
               c -=
13 #subtract 13 so round robin loop maintained
           
else:
               c +=
13 #add 13
       
elif c >= ord('A') and c <= ord('Z'): #for uppercase letters
           
if c > ord('M'): #same process as before.
               c -=
13
           
else:
               c +=
13
       
# Append to final result.
       output += chr(c)
#convert value back to character and add to result
       
#loop continues
   
# return final output back
   
return output
#function called here
print(rot13(
"hello"))
print(rot13(
"secret message"))


12.29.2018

#12.29.2018 - Shashi
#Supermarket Queue Self Checkout challenge.
#There is a queue
for the self-checkout tills at the supermarket.
#Your task is write a function to calculate the total time required
for all the customers to check out!
#The function has two input variables:
#customers: an
array (list in python) of positive integers representing the queue. Each integer represents a customer,
#and its value is the amount of time they require to check out.
#n: a positive integer, the number of checkout tills.
#
queueTime([10,2,3,3], 2) should return 10
#because here n=
2 and the 2nd, 3rd, and 4th people in the queue finish before the 1st person has finished.
#queueTime([
2,3,10], 2) should return 12 and so on.

def
queue_time(customers, n): #function starts here
   tills = [
0]*n #Create an array 0s with N elements
   
for i in customers: #loop through customers array
     tills[
0] += i #add up each next element in array
     tills.sort() #sort in ascending order
     
   return
max(tills) #return max value in tills

print("Max time for [2,3,10] customers to check out using 2 tills is: ", queue_time([2,3,10], 2), "minutes")
print("Max time for [10,2,3,3] customers to check out using 2 tills is: ", queue_time([10,2,3,3], 2), "minutes")
print("Max time for [5,3,4] customers to check out using 1 till is: ", queue_time([5,3,4], 1), "minutes")
print("Max time for [5,3,1,4] customers to check out using 4 tills is: ", queue_time([5,3,1,4], 4), "minutes")


12.28.2018

#12.28.2018 - Shashi
#Program to check
if a number is Prime or not.
#A prime number is a number that is only divisible by itself and
1.


#function starts here
def
is_prime(num):

 result = True #assign result to
default TRUE
 
if num > 1: #if number is >1
   # check
for any value between 2 and number that divides the number
   
for i in range(2,num): #loop from 2 to num
     
if (num % i) == 0: #if num can be divided by i
       result = False #set result to FALSE and
break loop
       
break
#
if input number is less than
# or equal to
1, it is not prime
 
else:
   result = False
 
return result #return final result to calling function
 
#function called from here
print(is_prime(11)) #should be true
print(is_prime(14)) #should be false
print(is_prime(211)) #should be true
print(is_prime(-112)) #should be false
#end of program


12.27.2018

#Program to accept a whole number >0 and return its roman numeral equivalent.
#In Roman Numerals, a smaller number in front of a larger number means subtraction, all
else means addition.
#For example, IV means
4, VI means 6.
#
12.27.2018 - Shashi
def
numToRoman(input):
   #set up data
for Roman numerals and their equivalent whole numbers
   ints = (
1000, 900,  500, 400, 100,  90, 50,  40, 10,  9,   5,  4, 1)
   nums = (
'M',  'CM', 'D', 'CD','C', 'XC','L','XL','X','IX','V','IV','I')
   result =
"" #to hold the final converted value
   
for i in range(len(ints)): #loop from 1 till no. of items in ints[]
     count =
int(input / ints[i]) #get count of how many times a value from ints[] divides input
     result += nums[i] * count #connect that numeral
"count" number of times to result.
     input -= ints[i] * count #pick up remainder and perform the same division operation
for next divider.
   
return result  #return result once loop is done.

#Function calls here.
#For
301, 100 (C) divides it and 3 is quotient/count. So 3 C's added first.
#input=input-(ints[i]*count) means 301-(100*3) = 301-300 = 1
#1 is then continued to be checked with the rest of the list. Only 1 satisfies it.
#So, it`s equivalent, I, is added to the end. Final result is CCCI.
print("301 in Roman Numerals is:",numToRoman(301))
print("5 in Roman Numerals is:",numToRoman(5))
print("3399 in Roman Numerals is:",numToRoman(3399))
print("88 in Roman Numerals is:",numToRoman(88))
#End of program


12.26.2018

#12.26.2018 - Shashi
#Program that accepts a string of text and replaces each letter with its position in the alphabet.
#So, a=
1, b=2 etc. Ignore case.

from string
import ascii_lowercase #import ascii_lowercase constants from python module string

#Create mapping
for all letters by matching them with their index position.
ALL_LETTERS = {letter: str(index)
for index, letter in enumerate(ascii_lowercase, start=1)}

#Function starts here
def
alphabet_process(text):
   text = text.lower() #convert accepted text to lowercase
   #create numbers list
for converted characters.
   numbers = [ALL_LETTERS[character]
for character in text if character in ALL_LETTERS]

   
return ' '.join(numbers)  #return list by joining elements with a space.

#driver function calls.
print(alphabet_process(
"The quick brown fox jumps over the lazy dog"))
print(alphabet_process(
"Another sample text to check"))
#program ends here


12.25.2018

#tribonacci sequence - adding 3 neighboring numbers at a time.
#a program that accepts a base sequence of
3 numbers and N.
#Function then generates N digits in that sequence.
#So
if the base sequence was 0,0,1 and 10 was N then the output would be: 0, 0, 1, 1, 2, 4, 7, 13, 24, 44
#
12.25.2018 - Shashi

#function starts here
def
tribonacci(signature, n):
   tribonacci = [] #create empty list to hold growing tribonacci values

   
for i in range(n): #loop from 1 till N
       new_member = signature[-
1] + signature[-2] + signature[-3]
       #-ve position means counting from right, instead of left
       #so -
1 means last element, -2 one before last etc.
       #
new element = last element + one before + one before that - since 3 elements need adding
       signature.append(new_member) #add
new sum of that to list. So for 9,0,1 new member is 1+0+0 = 1
       member = signature.pop(
0) #remove the first added member from signature. Sp, 0.
       tribonacci.append(member) #add that member to tribonacci set of growing sums.
    #loop until N elements done.
   
return tribonacci #return final list when loop is done.
   
   
tribo = [] #to hold result of function call
tribo = tribonacci([
0, 0, 1], 10) #function call + value returned
   
#print output with , separator    
print("List is")
print(*tribo, sep = ", ") 
#end of program


12.24.2018

#An isogram is a word that has no repeating letters, consecutive or non-consecutive.
#Implement a function that determines whether a string that contains only letters is an isogram.
#Assume the empty string is an isogram. Ignore letter
case.
#is_isogram(
"Dermatoglyphics" ) == true
#is_isogram(
"aba" ) == false
#is_isogram(
"moOse" ) == false # -- ignore letter case
#
12.24.2018 - Shashi

def
is_isogram(word):
   seen = set() #create empty set
for holding seen characters
   
for char in word.lower(): #loop through each character in lower case version of word
       
if char in seen: #if character being seen exists in seen set
           
return False #return false and get back.
       
else:
           seen.add(
char) #else add character to seen set
   
return True #true returned if loop ended without break (as in unique values only)
   
#function called from here
for different word samples    
print(is_isogram("quick")) #true because only unique letters
print(is_isogram("unique")) #false because u appears twice
print(is_isogram("moOse")) #false since function ignores case.
#end of program


12.23.2018

#Build Tower by the following given argument:
#number of
floors (integer and always greater than 0).
#Tower block is represented as *
#12.23.2018 - Shashi

def
tower_maker(n_floors):
       floors = [] #create empty list
for holding patterns
       
for i in range(n_floors): #loop controls by # of floors required
           n_floors -=
1 #decrement by 1 to organize spacing
           floors.append(
' ' * n_floors + '*' * (i * 2 + 1) + ' ' * n_floors)
           #each list item is SPACES, STARS, SAME # OF SPACES
       
return floors #after loop is done, return the pattern back
#end of function    

floors =
6 #floors required is 6
result = [] #make empty list to capture result
result = tower_maker(floors) #call function and assign returned value
print ("\nResult for" , floors , "floors\n") #print output via loop
for items in result:
       
print(items)

#repeat same process
for lesser # of floors
floors =
4
result = tower_maker(floors)
print (
"\nResult for" , floors , "floors\n")
for items in result:
       print(items)
#end of program


12.22.2018

#12.22.2018 - Shashi
# Take
2 strings s1 and s2 including only letters from a to z.
#Return a
new sorted string, the longest possible, containing distinct letters.
# each taken only once - coming from s1 or s2.
#Examples:
# a =
"xyaabbbccccdefww" b = "xxxxyyyyabklmopq" 
# longest(a, b) ->
"abcdefklmopqwxy"
# a =
"abcdefghijklmnopqrstuvwxyz" longest(a, a) -> "abcdefghijklmnopqrstuvwxyz" ```

#Function definition follows
def
longDistinct(string1, string2): #2 string variables sent from calling function
   a = sorted(string1) #a and b hold the sorted versions of these
strings (ascending)
   b = sorted(string2)
   output = a + b #output is concatenated version of both sorted strings
   output = sorted(output) #output now sorted alphabetically.
   array = [] #blank array defined
   
for loopvalue in output:  #loop through each character in output string
       
if loopvalue not in array:  #if character not ALREADY in array,
           array.append(loopvalue)  #add it - ensures unique values only
 
   
print(''.join(array)) #connect array elements by using join and print.
#function ends here

#function is called from here.
longDistinct("aretheyhere","yestheyarehere") #these strings are sent to the function
longDistinct("xyaabbbccccdefww","xxxxyyyyabklmopq")
#end of program


12.21.2018

/*
12.21.2018 | Shashi
A format for expressing an ordered list of integers is to use a comma separated list of either:
individual integers or a range of integers denoted by the starting integer separated from the end integer
in the range by a dash, '-'. The range includes all integers in the interval including both endpoints.
It is not considered a range unless it spans at least 3 numbers. For example ("12, 13, 15-17")

Complete the solution so that it takes a list of integers in increasing order and returns a correctly formatted string in the range format.

Example:
{-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20}
returns "-6,-3-1,3-5,7-11,14,15,17-20"

*/


public class myClass{
   
public static void main(String[] args)
   {
       
//initial array with values.
       
int[] arr = {-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20};
           
       String output=
""; //to hold the final value.

       
int len = arr.length; //get length of array
       
int val1 = 0, val2 = 0; //Variables to hold the two range values
       
while (val1 < len) //Loop to control value progression until length
       {
           
//Iterative logic while loop that pre-increments val2
           
//constantly checking if numbers in val2 and val2-1 are consecutive.
           
while (++val2 < len && arr[val2] - arr[val2 - 1] == 1);
           
           
//If range between val2 and val1 is found to be >2
           
if (val2 - val1 > 2)
           {
               
//attach starting value (val1) with a - with end value (val2-1) and a comma.
               output += Integer.toString(arr[val1]) +
"-"+ Integer.toString(arr[val2 - 1]) +",";
               val1 = val2;
//reassign val1 since now the next value set has to start
           }
           
else //if no range is found
           {
               
for (; val1 < val2; val1++)//as long as val1<val2
                   output += Integer.toString(arr[val1])+
",";//add val1 to output string
           }
//end of else
           
//val1 progressively changed in both scenarios to approach LEN.
       }
//end of while
       
       
//remove any trailing commas from final output string
       output = output.replaceAll(
",$", "");
       System.out.println(output);
//print output string
   }
//end of main
}
//end of class
       
       



12.20.2018

//12.20.2018 | Shashi
/*Given an array of integers and a number k, where 1 <= k <= length of the array, compute the maximum and minimum values of each subarray of length k.
For example, given array = [10, 5, 2, 7, 8, 7] and k = 3,
        10 = max(10, 5, 2) | 2 = min(10,5,2)
        7 = max(5, 2, 7) | 2 = min(5,2,7)
        8 = max(2, 7, 8) | 2 = min(2,7,8)
        8 = max(7, 8, 7) | 7 = min(7,8,7)
*/

public class myClass
{
        
public static void main(String[] args)
        {
           
//Array values
           
int array[] = {9,259,230,64,233,319,108,79,122,134,20,385,337,81,342,222,100,176,380,-33};
           
int n = 5;  //subsets of N values in the array.
           minMaxElements(array, array.length, n);
//send array, length of array and how many elements to consider
        }
//end of main()
   
        
// Function to find max and min for N subset of an array.
        
static void minMaxElements(int arr[], int n, int k) 
        {
           
int j, max,min;
           
for (int i = 0; i <= n - k; i++) { //loop through array sub-set
               max = arr[i];
//assign first element to max and min as default
               min = arr[i];
               System.out.print(
"[ "+arr[i] + " "); //print first element of sub-set array
               
for (j = 1; j < k; j++)  //loop through remaining elements of the array sub-set
               {
                   System.out.print(arr[i +j] +
" "); //print remaining elements of sub-set array
                   
if (arr[i + j] > max)  //if array element greater than max
                       max = arr[i + j];  
//reassign max
                   
if (arr[i + j] < min)   //if arrray element lesser than min
                       min = arr[i + j];  
//reassign min
               }
//inner for loop
               System.out.print(
"] Max = "+max + ", Min = " +min ); //print max and min values of sub-set array
               System.out.println();
//print new line for next sub-set array
           }
//outer for loop
        }
//end of function
}
//end of class


12.19.2018

/*Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.
Notes: Only lower case letters will be used (a-z). No punctuation or digits will be included. Performance needs to be considered. Input strings s1 and s2 are null terminated.
Examples
scramble('rkqodlw', 'world') ==> True
scramble('cedewaraaossoqqyt', 'codewars') ==> True
scramble('katas', 'steak') ==> False
12.19.2018 | Shashi
*/


public class myClass{
        
public static void main(String[] args)
        {
           
//Call function to check if string2 chracters exist in string1
           
//In other words, string1 can be rearranged to match string2
           System.out.println(scramble(
"rkqodlw","world"));
           System.out.println(scramble(
"cedewaraaossoqqyt", "codewars"));
           System.out.println(scramble(
"katas", "steak"));
           
        }
//end of main()
   
   
        
public static boolean scramble(String str1, String str2)
        {
           String temp = str1;
//hold full first string in temp variable
           
int count = 0;//count variable to see how many characters in str1 match str2
           
boolean result = true; //to hold final result
           
           
//loop through str2 and check each character
           
for(int i=0 ; i<str2.length() ; i++){
               
char c = str2.charAt(i); //each character in str2
               
if(temp.contains(String.valueOf(c))){ //if full version contains current character
                   temp = temp.replaceFirst(String.valueOf(c),
""); //replace character in str2 with ""
                   count++;
//increment count
               }
               
//the loop eliminates characters in str1 that exist in str2
           }
           
if (count == str2.length()){ //check if character count equals str2's length.
               result =
true; //if it does then all characters in str2 exist in str1. so answer is yes.
           }
else {
               result =
false; //else it does not.
           }
           
return result; //return final result back.
        }
//end of function
}
//end of class


12/18/2018

//Take time in seconds and convert it to human readable HH:MM:SS format.
//Shashi | 12.18.2018

public class HumanReadableTime {
   
public static void main(String[] args)
   {
       
int seconds = 1000; //send value to function
       System.out.println(seconds +
" seconds >>> " + makeReadable(seconds));
       seconds = -
89887;
       System.out.println(seconds +
" seconds >>> " + makeReadable(seconds));  
       seconds =
61;
       System.out.println(seconds +
" seconds >>> " + makeReadable(seconds));
       seconds = -
5;
       System.out.println(seconds +
" seconds >>> " + makeReadable(seconds));  
   }
   
   
   
//function that converts seconds to readable format and returns String
 
public static String makeReadable(int inputseconds) {
   
if(inputseconds<0) return "Error in input.";//if negative number was sent.
   
   
//Else chop seconds into hours and mins
   
int minutes = inputseconds / 60;
   inputseconds -= minutes *
60;
   
int hours = minutes / 60;
   minutes -= hours *
60;
   
//To hold final solution    
   String format =
"";
   
   
//To pad hours with a leading 0 in front for single digits
   
if(hours<10)
      format =
"0"+Integer.toString(hours);
   
else
      format = Integer.toString(hours);
   
   
//Add a ":"
   format +=
":";
   
   
//To pad mins with a leading 0 for single digits
   
if(minutes<10)  
      format = format +
"0"+Integer.toString(minutes);
   
else
       format = format + Integer.toString(minutes);
   
   
//Add second ":"
   format +=
":";
   
   
//Pad seconds with leading 0 for single digits
   
if(inputseconds<10)
      format = format +
"0"+Integer.toString(inputseconds);
   
else 
     format = format + Integer.toString(inputseconds);

   
//Return final solution back.
   
return format;
   
 }
//end of function
}
//end of class


12/17/2018

/*12.17.2018 | Shashi
In this kata, you must create a digital root function. A digital root is the recursive sum of all the digits in a number. Given n, take the sum of the digits of n.
If that value has two digits, continue reducing in this way until a single-digit number is produced. This is only applicable to the natural numbers.
Here's how it works:
digital_root(16)
=> 1 + 6
=> 7
digital_root(942)
=> 9 + 4 + 2
=> 15 ...
=> 1 + 5
=> 6
*/


public class MyClass { //class opens here
        
public static void main(String args[]) { //main() starts here
         
          
int number=1234;  
          System.out.println(digital_root(number));
        }

        
//digital root function
        
public static int digital_root(int number)
        {
               
int sum = 0; //to store final sum
               
while (number > 0 || sum > 9)   //loop until sum is a single digit
               {
                   
//if 0 sent then send back 0  
                   
if (number == 0) {number=sum;sum = 0;}
               
                   
//sum = sum + number %10 (add all digits except 1st)
                   sum += number %
10;
                   
//number  = number/10 (extract 1st digit)
                   number = number/
10;
               }
//end of loop
           
           
return sum;//return final sum to calling method
           
        }
//end of function
}
//end of class


12/16/2018

/*Given an array (arr) as an argument complete the function countSmileys that should return the total number of smiling faces.
Rules for a smiling face:
-Each smiley face must contain a valid pair of eyes. Eyes can be marked as : or ;
-A smiley face can have a nose but it does not have to. Valid characters for a nose are - or ~
-Every smiling face must have a smiling mouth that should be marked with either ) or D.
No additional characters are allowed except for those mentioned.
Valid smiley face examples:
:) :D ;-D :~)
Invalid smiley faces:
;( :> :} :]
12.16.2018 | Shashi
*/


public class MyClass {
        
public static void main(String args[]) {//main() begins here
        
        String[] strArray =
new String[]{":)", ";(", ";}", ":-D"};
        System.out.println(countSmileys(strArray) +
" smileys.");           // should return 2;
        
        strArray =
new String[]{";D", ":-(", ":-)", ";~)"};
        System.out.println(countSmileys(strArray) +  
" smileys.");           // should return 3;
   
        strArray =
new String[]{";]", ":[", ";*", ":$", ";-D"};
        System.out.println(countSmileys(strArray) +
" smileys.");           // should return 1;
   
        }
//end of main()
   
        
public static int countSmileys(String[] smileys)
        {
          
int smileycount =0; //count # of valid smileys
         
          
for(int loop=0;loop<smileys.length;loop++) //loop through array
          {
              
if(validCheck(smileys[loop])) //check each smiley to see if its a valid one
                  smileycount++;
//increase count
          }
           
return smileycount; //return final count
           
        }
//end of countsmileys()
   
        
//function to check if the single smiley is in VALID list.
        
public static boolean validCheck(String str)
        {
               
//List of valid smileys
                String[] validsmileys = {
":)",":D",";)",";D",":-)",":~)",":-D",":~D",";-)",";~)",";-D",";~D"};
           
                
boolean found = false;
                
//loop through smiley array
                
for(int loop=0;loop<validsmileys.length;loop++)
                {
                    
//if smiley sent is in valid list
                    
if(str.equals(validsmileys[loop]))
                    {
                        found=
true;//set flag to true
                        
break; //end and quit loop
                    }
//end of if
                   
                }
//end of for loop
               
                
return found; //return value back
        }
//end of function

}
//end of class


12/15/2018

/*Kata.expandedForm(12); # Should return "10 + 2"
Kata.expandedForm(42); # Should return "40 + 2"
Kata.expandedForm(70304); # Should return "70000 + 300 + 4"*/

//Shashi | 12.14.2018

import java.util.Arrays;

public class MyClass {
        
public static void main(String args[]) {
           
           
int number = 47102;
           System.out.println(number +
" = " + expandedForm(number));
           number =
12;
           System.out.println(number +
" = " + expandedForm(number));    
           number =
70304;
           System.out.println(number +
" = " + expandedForm(number));  
        }
   
        
public static String expandedForm(int number)
        {
             
//convert number to String array
             String[] str = Integer.toString(number).split(
"");
             String output =
""; //to hold final answer

            
//loop through str's length to process each digit
            
for(int i = 0; i < str.length-1; i++) {
               
if(Integer.valueOf(str[i]) > 0) { //if digit is greater than 0
                 
for(int j = i; j < str.length-1; j++) { //add N number of 0s to final output of THAT digit
                   str[i] +=
'0'; //add N 0s to the digit depending on length of string left.
                 }
//if ends
               }
//inner loop adding 0s ends so outer loop can kick in
             }
//loop ends to go to next digit in array

             output = Arrays.toString(str);
//Convert string array to single String
             output = output.substring(
1, output.length()-1).replace(",", " +"); //go through string and replace "," with " +"
             output = output.replace(
" + 0",""); //replace any " + 0"  with blanks
             
             
return output; //return final result to calling function
        }
//end of function
}
//end of class


12/14/2018

/*Complete the method/function so that it converts dash/underscore delimited words into camel casing.
The first word within the output should be capitalized only if the original word was capitalized.
toCamelCase("the-stealth-warrior"); // returns "theStealthWarrior"
toCamelCase("The_Stealth_Warrior"); // returns "TheStealthWarrior"
Shashi | 12.14.2018
*/


public class MyClass { //class starts here
        
public static void main(String args[]) { //main starts here
         
         String word =
"The_amazing-stealth warrior";
         System.out.println(
"["+ word + "] is converted to [" + toCamelCase(word)+"]");
         word =
"The_Stealth_Warrior";
         System.out.println(
"["+ word + "] is converted to [" + toCamelCase(word)+"]");
         word =
"the-stealth-warrior";
         System.out.println(
"["+ word + "] is converted to [" + toCamelCase(word)+"]");
        }
//end of main()

//function starts here    
public  static String toCamelCase(String word){
        String[] wordArr = word.split(
"-|_| "); //split words based on these delimits
           String finalWord =
"";//final solution holder
           
           
if(word.length()>0) {//ensure its a valid word
            finalWord = wordArr[
0]; //store first word
           
     
//if first character of first word is NOT capitalized
           
if(Character.isUpperCase(finalWord.charAt(0))==false)
               finalWord.toLowerCase();
//convert all to lower else leave it as it is.
           
           
//loop through rest of the words
           
for(int i=1; i<wordArr.length; i++)
               
//connect words together ensuring first character of the word is upper case.
               finalWord = finalWord + wordArr[i].substring(
0, 1).toUpperCase() + wordArr[i].substring(1);
           }
//end of IF
           
           
//return final word back to calling function.
           
return finalWord;
 }
//end of function
}
//end of class


12/13/2018

/*Welcome. In this kata, you are asked to square every digit of a number.
For example, if we run 9119 through the function, 811181 will come out,
because 9^2 is 81 and 1^2 is 1.
Note: The function accepts an integer and returns an integer.
Shashi | 13.12.2018
*/


public class MyClass {
        
public static void main(String args[]) {
         
          
//Print message + call function
          System.out.println(
"9119 produces >> " + processNumber(9119)); //accept integer
          System.out.println(
"1234 produces >> " + processNumber(1234)); //accept integer
        }
   
        
//function accepts number and returns a number
        
public static int processNumber(int number)
        {
            String result =
"";
            
while (number != 0) {
                   
int digit = number % 10; //extract remainder of the division by 10.
                   result = digit*digit + result;
//square it and "attach" result as string
                   number = number/
10; //extract first N-1, N-2, N-3 digits and so on.
           }
//end of loop
        
return Integer.parseInt(result) ; //return output back to calling function.
        }
//end of function
}
//end of class

12/12/2018

/*Complete the function that accepts a string parameter, and reverses each word in the string. All spaces in the string should be retained.
Examples:
"This is an example!" ==> "sihT si na !elpmaxe"
"double  spaces"          ==> "elbuod  secaps"
Shashi | 12.11.2018
*/

public class MyClass {
        
public static void main(String args[]) {
        String stringvalue =
"This is a test message!"; //message
        System.out.println(
"["+stringvalue +"] reversed is [" + reverseString(stringvalue)+"]"); //function call
        stringvalue =
"double spaces";
        System.out.println(
"["+stringvalue +"] reversed is [" + reverseString(stringvalue)+"]"); //function call
        }
//end of main
   
        
//function that accepts string and sends back output
        
public static String reverseString(String stringValue)
        {
        
//split string into an array for easier processing.
        String[]array = stringValue.split(
" ");
        String result =
"";//to hold final value
        String reverse =
"";//to hold reversed version of each word
   
        
//loop through word array - one word at a time
        
for(int i=0;i<array.length;i++)
        {
           
//get length of that word
           
int length = array[i].length(); //get length of the string array
           reverse=
"";//get reverse holder ready
             
if(length>1) //skip single letter words
             {
             
//start from end of the word and work back to position 1.
             
for (int j = length - 1 ; j >= 0 ; j--){
                reverse = reverse + array[i].charAt(j);}
             }
//end of IF
             
else result = result + " " + array[i];//for single letter words
          
if(i==0) result = reverse; //avoid leading space
          
else        result =  result + " " +reverse; //add new reversed words with a space
        }
//end of word array loop

        
return result; //return final output back
        }
//end of function
}
//end of class


12/11/2018

/*Trolls are attacking your comment section!
A common way to deal with this situation is to remove all of the vowels from the trolls' comments, neutralizing the threat.
Your task is to write a function that takes a string and return a new string with all vowels removed.
For example, the string "This website is for losers LOL!" would become "Ths wbst s fr lsrs LL!".
Note: for this kata y isn't considered a vowel.
Shashi | 12.11.2018
*/

public class MyClass {
        
public static void main(String args[]) {
           System.out.println(killTroll(
"This website is for losers LOL!"));
        }
   
        
public static String killTroll(String comment) {            
          
return comment.replaceAll("(a|A|e|E|i|I|o|O|u|U)", "");
          
//Shorter solution
          
//return comment.replaceAll("(?i)[aeiou]" , ""); //remove case sensitivity + characters
        }
}


12/10/2018

# Implement a job scheduler which takes in a function f and an integer n, and calls f after n milliseconds.
# Shashi |
12.10.2018

# This is required to include time
module which has all time related functions.
import time

#function that accepts function
f() and time n() as parameters
def
schedulejob(f, n):
   time.
sleep(n/1000) #pause/wait until X/1000 seconds have passed
   return
f() #return f() back to calling function
#end of function
schedulejob()

#print date/time before function call
print("Current time is >>>> " + time.ctime())

#print date/time after the pause has taken place. lambda functions are temporary anon functions usable
for a short period of time.
print(schedulejob(lambda: "Function running at >>>> " + time.ctime(), 5000)) ##function runs after 5 seconds

#end of code



12/9/2018

/*The goal of this exercise is to convert a string to a new string
where each character in the new string is '(' if that character appears only once in the original string, or ')'
if that character appears more than once in the original string.
Ignore capitalization when determining if a character is a duplicate.
12.9.2018
"din" => "((("
"recede" => "()()()"
"Success" => ")())())"
"(( @" => "))((" */



public class MyClass {
        
public static void main(String args[]) {
        
//call function that accepts string and prints updated string
   
        
//Test message prints
        System.out.println(processString(
"Success"));
        System.out.println(processString(
"(( @"));
        System.out.println(processString(
"recede"));
        }
   
        
public static String processString(String input){
                   String result=
"";
                   
for(int loop=0; loop<input.length();loop++) //loop through input String- by each character.
                   {
                       
if(getCount(input,input.charAt(loop))>1)   //if more than one occurence
                       {
                           result = result+
")";  //add ")" to this position
                           
continue; //pick up the next pass
                       }
                       
else result = result+"("; //add "(" to this position (unique value)
                   }
//end of the for loop
                   
           
return result; //return value back to main()
        }
//end of function
   
        
//function that takes both string and letter to look for
        
public static int getCount(String input, char letter)
        {
           
int count = 0;
           
for(int loop=0;loop<input.length();loop++)
           {
               
//check how many times that character appears in the word
               
if(Character.toLowerCase(input.charAt(loop))==Character.toLowerCase(letter)) //ignore case
                   count++;
//increase count
           }
           
return count;//return the value back
        }
//end of function getCount()
   
}
//end of class

12/6/2018

/*

There is an array with some numbers. All numbers are equal except for one. Try to find it!
findUniq([ 1, 1, 1, 2, 1, 1 ]) === 2
findUniq([ 0, 0, 0.55, 0, 0 ]) === 0.55

*/


public class MyClass {
        
public static void main(String args[]) {
   
        
//Declare and initialize array with values (ensuring one of them is unique)
        
int[] arr = {1, 1, 1, 2, 1, 1,1,1,1,1,1,1,2,2,2,8,2,2,2,2};
   
        
//Print<>call function for unique value
        System.out.println(
"The unique value is:" + findUniq(arr));

        }
//end of main()
   
        
public static int findUniq(int[] arr)
        {
          
// Do XOR of all elements and return
           
int res = arr[0]; //assume first value is unique
           
for (int i = 0; i < arr.length; i++) //loop through array
               res = res ^ arr[i];
//execute XOR on "res" with new elements on array
         
           
return res;//return "res" back to main()
        }
//end of function
}
//end of class



12/5/2018

//Simple, given a string of words, return the length of the shortest word(s).
//String will never be empty and you do not need to account for different data types.
//Shashi | 12.05.2018

public class MyClass {
        
public static void main(String args[])
        {
           
//Call the function and send sample sentences to it.
           processString(
"She was too short for the ride.");
           processString(
"Check back tomorrow; I will see if the book has arrived.");
           processString(
"She advised him to come back at once.");
           processString(
"She sells sea shells on the sea shore.");
           processString(
"Two seats were vacant.");
           
        }
   
        
//Function that accepts sentences and processes them
        
public static void processString(String words)
        {
           
           
//Exclude punctuation
           String[] array = words.split(
"[\\p{Punct}\\s]+");
           
int shortest=array[0].length();        //assume the first element is the shortest.
           String shortWord=
"";
           
//loop through the string array to find shortest length all words
           
for(int loop = 0; loop<array.length;loop++)
           {
                
if(array[loop].length()<shortest)
                   shortest = array[loop].length();
               
           }
           
//All matching words put into one collection
           
for(int loop = 0; loop<array.length;loop++)
           {
               
if(array[loop].length() == shortest)
               {
                  
if(shortWord=="")
                   shortWord = array[loop];
                  
else
                    shortWord = shortWord +
"," + array[loop];
               }
           }
           System.out.println(
"Shortest word(s) " + shortWord + ":" + shortest + " character(s)");
           
        }
//end of function
}
//end of class



12/4/2018

//Move the first letter of each word to the end of it, then add "ay" to the end of the word.
//Leave punctuation marks untouched.
public class MyClass {
   
public static void main(String args[]) {
     
     String source =
"Look in the bag.";
     
     
//function to process the input and capture output
     String result = convertString(source);
     
     
//print processed final string.
     System.out.println(result);
   }
   
   
public static String convertString(String source)
   {
       
//Split the sentence by words and retain punctuation.
       String[] wordsArray = source.split(
"(?<=\\b|[^\\p{L}])", 0);
       String eachWord =
"";
       String result =
"";
       
//Loop through the word array, repurpose each word (length>1), retain punctuation
       
for(int loop=0;loop<wordsArray.length;loop++)
       {
           eachWord = wordsArray[loop];  
//load the word for processing
           
           
if(eachWord.length()>2) //at least 2 characters in it
           {
               eachWord = eachWord + eachWord.charAt(
0) + "ay"; // add first char and "ay"
               eachWord = eachWord.substring(
1); //remove first char
           }
           
           result = result + eachWord;
//add processed word to result sentence.
       }
       
       result = result.replaceAll(
"( )+", " "); //remove extra spaces
       
return result; //return sentence back.
   }
   
}



12/3/2018