Menu
Topics Index
...
`

Weekend Hack - 11 May 2013 - Results

Thanks to Soumya Tata and Pramod Jain for spending so much time, coming up with original and innovative answers and for submitting them. Thanks to many others who have tried to get the solution.
We have reviewed the solutions as per the criteria mentioned at Weekend Hack and included the comments below. Given the experience of the participants, they were really innovative and clean. Few minor comments found are included below in the order of the submission. These comments are not intended to point out the mistakes in the solutions but to learn from them.

The winner of the Weekend Hack 11 May 2013 - 1 is Pramod Jain. He will get a recharge or gift voucher worth Rs. 150.

To convert the given object into a string

Write a program to convert the given object into a string. Note that you need to use reflection api to do this. If present, the id field should be placed at the beginning and the rest of fields should be sorted. If the field contains capital letter then add one space before and make first letter as capital. If field contains any number then add one space before and equals to the field value with spaces as shown in below.

Input (Object) Output (String)
College object
------------------
numberOfStudents=75896
numberOfBranches=6
numberOfFaculty=1200
numberOfStudentsScoredMoreThanPercent80=65200
grade='A'
collegeCode="RITA"
collegeAddress="B K Samudram Mandal-Anantapur"
nameOfTheCollege="Srinivasa Ramanujan Institute of Technology"
College Address = "B K Samudram Mandal-Anantapur"
College Code = "RITA"
Grade = 'A'
Name Of The College = "Srinivasa Ramanujan Institute of Technology"
Number Of Branches = 6
Number Of Faculty = 1200
Number Of Students = 75896
Number Of Students Scored More Than Percent 80 = 65200
Student object
------------------
nameOfPerson="Mahesh Babu"
genderOfPerson=true
marksObtained=550
percentageGot=91.6
belongsToSection='A'
studentId=516
Student Id = 516
Belongs To Section = 'A'
Gender Of Person = true
Marks Obtained = 550
Name Of Person = "Mahesh Babu"
Percentage Got = 91.6
Employee object
------------------
salaryPerMonth=200000
nameOfEmployee="Oleti Kiran Kumar"
designationInCompany="Software Engineer"
employeeId=516
genderOfEmployee=true
Employee Id = 516
Designation In Company = "Software Engineer"
Gender Of Employee = true
Name Of Employee = "Oleti Kiran Kumar"
Salary Per Month = 200000.0
Company object
------------------
nameOfTheCompany="Infosys Technologies"
numberOfEmployees=3000
totalWorkingDaysPer1Year=200
turnOverPer01Years=1000000.0
companyId=3546
companyLocationInIndia="Plot No. 44, Hosur Road, Electronics City, Bengaluru, Karnataka, 560100"
chairPersonName="Kiran Kumar"
numberOfDepartments=25
Company Id = 3546
Chair Person Name = "Kiran Kumar"
Company Location In India = "Plot No. 44, Hosur Road, Electronics City, Bengaluru, Karnataka, 560100"
Name Of The Company = "Infosys Technologies"
Number Of Departments = 25
Number Of Employees = 3000
Total Working Days Per 1 Year = 200
Turn Over Per 01 Years = 1000000.0

Solution 1 - Submitted on Sat May 11 20:34:11 2013

import java.lang.reflect.Field;
import java.util.Arrays;

class ConvertObjectToString {

    public static void main(String s[]) {
        College college = new College();
        college.numberOfStudents = 75896;
        college.numberOfBranches = 6;
        college.numberOfFaculty = 1200;
        college.collegeCode = "RITA";
        college.grade = 'A';
        college.numberOfStudentsScoredMoreThanPercent80 = 65200;
        college.collegeAddress = "B K Samudram Mandal-Anantapur";
        college.nameOfTheCollege = "Srinivasa Ramanujan Institute of Technology";
        String query = convertObjectToString(college);
        System.out.println(query);
    }

    public static String convertObjectToString(Object object) {
        String result = null;
        result = "";
        int first = -1;
        Class c1 = object.getClass();
        Field[] fs = c1.getDeclaredFields();
        String s[] = new String[fs.length];
        for (int i = 0; i < fs.length; i++) {
            Class t = fs[i].getType();
            if (t == int.class) {
                String fin = "";
                s[i] = fs[i].toString();
                for (int l = 0; l < s[i].length(); l++) {
                    char c = s[i].charAt(l);
                    if (c == '0' || c == '2' || c == '1' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9') {
                        s[i] = s[i].substring(0, l) + " " + s[i].substring(l);
                        break;
                    }
                }
                if (s[i].contains("Id"))
                    first = i;
                s[i] = s[i].substring(s[i].lastIndexOf('.') + 1);
                char c = s[i].charAt(0);
                s[i] = s[i].substring(1);
                String[] CaseWords = s[i].split("(?=[A-Z])");
                for (String caseWord : CaseWords) {
                    fin = fin + caseWord + " ";
                }
                try {
                    s[i] = Character.toUpperCase(c) + fin + "= " + fs[i].getInt(object);
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else if (t == float.class) {
                String fin = "";
                s[i] = fs[i].toString();
                for (int l = 0; l < s[i].length(); l++) {
                    char c = s[i].charAt(l);
                    if (c == '0' || c == '2' || c == '1' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9') {
                        s[i] = s[i].substring(0, l) + " " + s[i].substring(l);
                        break;
                    }
                }
                if (s[i].contains("Id"))
                    first = i;
                s[i] = s[i].substring(s[i].lastIndexOf('.') + 1);
                char c = s[i].charAt(0);
                s[i] = s[i].substring(1);
                String[] CaseWords = s[i].split("(?=[A-Z])");
                for (String caseWord : CaseWords) {
                    fin = fin + caseWord + " ";
                }
                try {
                    s[i] = Character.toUpperCase(c) + fin + "= " + fs[i].getFloat(object);
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else if (t == double.class) {
                String fin = "";
                s[i] = fs[i].toString();
                for (int l = 0; l < s[i].length(); l++) {
                    char c = s[i].charAt(l);
                    if (c == '0' || c == '2' || c == '1' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9') {
                        s[i] = s[i].substring(0, l) + " " + s[i].substring(l);
                        break;
                    }
                }
                if (s[i].contains("Id"))
                    first = i;
                s[i] = s[i].substring(s[i].lastIndexOf('.') + 1);
                char c = s[i].charAt(0);
                s[i] = s[i].substring(1);
                String[] CaseWords = s[i].split("(?=[A-Z])");
                for (String caseWord : CaseWords) {
                    fin = fin + caseWord + " ";
                }
                try {
                    s[i] = Character.toUpperCase(c) + fin + "= " + fs[i].getDouble(object);
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else if (t == long.class) {
                String fin = "";
                s[i] = fs[i].toString();
                for (int l = 0; l < s[i].length(); l++) {
                    char c = s[i].charAt(l);
                    {
                        if (c == '0' || c == '2' || c == '1' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9') {
                            s[i] = s[i].substring(0, l) + " " + s[i].substring(l);
                            break;
                        }
                    }
                }
                if (s[i].contains("Id"))
                    first = i;
                s[i] = s[i].substring(s[i].lastIndexOf('.') + 1);
                char c = s[i].charAt(0);
                s[i] = s[i].substring(1);
                String[] CaseWords = s[i].split("(?=[A-Z])");
                for (String caseWord : CaseWords) {
                    fin = fin + caseWord + " ";
                }
                try {
                    s[i] = Character.toUpperCase(c) + fin + "= " + fs[i].getLong(object);
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else if (t == String.class) {
                String fin = "";
                s[i] = fs[i].toString();
                for (int l = 0; l < s[i].length(); l++) {
                    char c = s[i].charAt(l);
                    if (c == '0' || c == '2' || c == '1' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9') {
                        s[i] = s[i].substring(0, l) + " " + s[i].substring(l);
                        break;
                    }
                }
                if (s[i].contains("Id"))
                    first = i;
                s[i] = s[i].substring(s[i].lastIndexOf('.') + 1);
                char c = s[i].charAt(0);
                s[i] = s[i].substring(1);
                String[] CaseWords = s[i].split("(?=[A-Z])");
                for (String caseWord : CaseWords) {
                    fin = fin + caseWord + " ";
                }
                try {
                    s[i] = Character.toUpperCase(c) + fin + "= " + "\"" + (String) fs[i].get(object) + "\"";
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else if (t == boolean.class) {
                String fin = "";
                s[i] = fs[i].toString();
                for (int l = 0; l < s[i].length(); l++) {
                    char c = s[i].charAt(l);
                    if (c == '0' || c == '2' || c == '1' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9') {
                        s[i] = s[i].substring(0, l) + " " + s[i].substring(l);
                        break;
                    }
                }
                if (s[i].contains("Id"))
                    first = i;
                s[i] = s[i].substring(s[i].lastIndexOf('.') + 1);
                char c = s[i].charAt(0);
                s[i] = s[i].substring(1);
                String[] CaseWords = s[i].split("(?=[A-Z])");
                for (String caseWord : CaseWords) {
                    fin = fin + caseWord + " ";
                }
                try {
                    s[i] = Character.toUpperCase(c) + fin + "= " + fs[i].getBoolean(object);
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } else {
                String fin = "";
                s[i] = fs[i].toString();
                for (int l = 0; l < s[i].length(); l++) {
                    char c = s[i].charAt(l);
                    if (c == '0' || c == '2' || c == '1' || c == '3' || c == '4' || c == '5' || c == '6' || c == '7' || c == '8' || c == '9') {
                        s[i] = s[i].substring(0, l) + " " + s[i].substring(l);
                        break;
                    }
                }
                if (s[i].contains("Id"))
                    first = i;
                s[i] = s[i].substring(s[i].lastIndexOf('.') + 1);
                char c = s[i].charAt(0);
                s[i] = s[i].substring(1);
                String[] CaseWords = s[i].split("(?=[A-Z])");
                for (String caseWord : CaseWords) {
                    fin = fin + caseWord + " ";
                }
                try {
                    s[i] = Character.toUpperCase(c) + fin + "= " + "'" + fs[i].getChar(object) + "'";
                } catch (IllegalArgumentException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        if (first != -1)
            result = result + s[first];
        Arrays.sort(s);
        if (first == -1) {
            for (int i = 0; i < s.length; i++) {
                if (i == s.length - 1) {
                    result = result + s[i];
                    return result;
                }
                result = result + s[i] + "\n";
            }
        }
        for (int i = 0; i < s.length; i++) {
            if (!s[i].contains("Id")) {
                result = result + "\n" + s[i];
            }
        }
        return result;
    }
}

class Student {

    String nameOfPerson;
    boolean genderOfPerson;
    int marksObtained;
    double percentageGot;
    char belongsToSection;
    int studentId;
}

class Employee {

    double salaryPerMonth;
    String nameOfEmployee;
    String designationInCompany;
    int employeeId;
    boolean genderOfEmployee;
}

class Company {

    String nameOfTheCompany;
    int numberOfEmployees;
    int totalWorkingDaysPer1Year;
    double turnOverPer01Years;
    int companyId;
    String companyLocationInIndia;
    String chairPersonName;
    int numberOfDepartments;
}

class Mobile {

    String companyName;
    String modelName;
    double mobilePrice;
    double memoryCapacity;
    float cameraPixel;
    String screenResolution;
}

class College {

    int numberOfStudents;
    int numberOfBranches;
    int numberOfFaculty;
    int numberOfStudentsScoredMoreThanPercent80;
    char grade;
    String collegeCode;
    String collegeAddress;
    String nameOfTheCollege;
}

class Hotel {

    String hotelName;
    int numberOfChairsAndTables;
    int numberOfWorkers;
    String hotelTimings;
    String hotelLocationWithDoorNumber;
    long landLineNumberStartsWithAreaCode8554;
}

Review Comments

Overall Rating (out of 10): 4

Solution 2 - Submitted on Sun May 12 11:39:40 2013

import java.lang.reflect.Field;

class ConvertObjectToString {

    public static void main(String s[]) {
        College college = new College();
        college.numberOfStudents = 75896;
        college.numberOfBranches = 6;
        college.numberOfFaculty = 1200;
        college.collegeCode = "RITA";
        college.grade = 'A';
        college.numberOfStudentsScoredMoreThanPercent80 = 65200;
        college.collegeAddress = "B K Samudram Mandal-Anantapur";
        college.nameOfTheCollege = "Srinivasa Ramanujan Institute of Technology";
        String query = convertObjectToString(college);
        System.out.println(query);
    }

    public static String convertObjectToString(Object object) {
        String result = null;
        if (object == null)
            return null;
        result = "";
        for (Field field : object.getClass().getDeclaredFields()) { //making a string wth all parameters
            try {
                result = result.concat(change_to_standards(field.getName()) + " = " + add_datatype_format(field.get(object)) + "#");
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        String arr[] = result.split("#"); // seperating all parameters
        result = "";
        int isset = 0;
        for (int j = 0; j < arr.length; j++) { //making the parameter with id as first parameter
            if (arr[j].contains("Id")) {
                String temp = arr[j];
                arr[j] = arr[0];
                arr[0] = temp;
                isset = 1;
                result = result.concat(arr[0]) + String.valueOf('\n');
                break;
            }
        }
        for (int j = 0 + isset; j < arr.length; j++) { // sorting all other params and simultaneously adding them to string
            for (int i = j + 1; i < arr.length; i++) {
                if (arr[i].compareTo(arr[j]) < 0) {
                    String temp = arr[j];
                    arr[j] = arr[i];
                    arr[i] = temp;
                }
            }
            if (j != arr.length - 1)
                result = result.concat(arr[j]) + String.valueOf('\n');
            else
                result = result.concat(arr[j]);
        }
        return result;
    }

    public static String change_to_standards(String str) {
        int i = 0;
        String res = "";
        boolean flag = true;
        res = String.valueOf(Character.toUpperCase(str.charAt(0)));
        for (i = 1; i < str.length() - 1; i++) {
            res += str.charAt(i);
            if (str.charAt(i + 1) >= 'A' && str.charAt(i + 1) <= 'Z') //adding space before capital letters 
                res += ' ';
            if (str.charAt(i + 1) >= '0' && str.charAt(i + 1) <= '9' && flag) { //adding space before number(only once)
                res += ' ';
                flag = false;
            }
        }
        res += str.charAt(i);
        return res;
    }

    public static String add_datatype_format(Object obj) {
        String res = null;
        if (obj instanceof String)
            res = "\"" + obj.toString() + "\""; //return string wth double quotes
        else if (obj instanceof Character)
            res = "'" + obj.toString() + "'"; //return string wth single quotes
        else
            res = obj.toString(); //return the value
        return res;
    }
}

class Student {

    String nameOfPerson;
    boolean genderOfPerson;
    int marksObtained;
    double percentageGot;
    char belongsToSection;
    int studentId;
}

class Employee {

    double salaryPerMonth;
    String nameOfEmployee;
    String designationInCompany;
    int employeeId;
    boolean genderOfEmployee;
}

class Company {

    String nameOfTheCompany;
    int numberOfEmployees;
    int totalWorkingDaysPer1Year;
    double turnOverPer01Years;
    int companyId;
    String companyLocationInIndia;
    String chairPersonName;
    int numberOfDepartments;
}

class Mobile {

    String companyName;
    String modelName;
    double mobilePrice;
    double memoryCapacity;
    float cameraPixel;
    String screenResolution;
}

class College {

    int numberOfStudents;
    int numberOfBranches;
    int numberOfFaculty;
    int numberOfStudentsScoredMoreThanPercent80;
    char grade;
    String collegeCode;
    String collegeAddress;
    String nameOfTheCollege;
}

class Hotel {

    String hotelName;
    int numberOfChairsAndTables;
    int numberOfWorkers;
    String hotelTimings;
    String hotelLocationWithDoorNumber;
    long landLineNumberStartsWithAreaCode8554;
}

Review Comments

Overall Rating (out of 10): 6

  • Better variable names could be given to isset, arr, res
  • The code written is comparatively clean and does not contain duplicate code and the comments included are useful.
  • Code will not work if address or college name contained '#' in it. When you are splitting it back into strings it will not work. We could have used ArrayList of Strings instead of appending to one string and then splitting it back.
  • In the add_datatype_format it is not necessary to call toString again, since it is automatically called as part of String concatenation.
  • Could have use Collections.sort for sorting the names.
  • As per the requirement, we need to sort the names only and not names and data. With certain data the sorting might be different/incorrect.
  • © meritcampus 2019

    All Rights Reserved.

    Open In App