79089517

Date: 2024-10-15 10:34:07
Score: 0.5
Natty:
Report link

We need to track, where next ? at in the patternArray and how many question marks are left in recursive function. If you figure it out, you can solve problem with ease. Note: Not fully tested. Will only work if valid inputs are given or Atleast one valid answer is present.

import java.util.ArrayList;
import java.util.List;

public class HourWork {
    public static void main(String[] args) {
        String pattern = "?0???0?";
        int totalHours = 36;
        int dayHours = 8;
        char[] patternArray = pattern.toCharArray();
        int currentHours = 0;
        int totalQuestionMark = 0;
        int index = -1;
        for (int i = 0; i < patternArray.length; i++) {
            if (patternArray[i] != '?') {
                currentHours += patternArray[i] - '0';
            } else {
                if (index == -1) {
                    index = i;
                }
                totalQuestionMark++;
            }
        }
        int remainingHours = totalHours - currentHours;
        List<String> re = new ArrayList<>();
        findScheduleRec(remainingHours, dayHours, patternArray, index, re, totalQuestionMark);
        System.out.println(re);
    }

    private static void findScheduleRec(int rem, int dayHours, char[] patternArray, int index, List<String> re, int totalQuestionMark) {
        if (totalQuestionMark == 1 && rem <= dayHours) {
            patternArray[index] = (char) ('0' + rem);
            re.add(new String(patternArray));
            patternArray[index] = '?';
            return;
        } else if (totalQuestionMark == 1) {
            return;
        }
        for (int i = 0; i <= dayHours; i++) {
            int r = rem - i;
            patternArray[index] = (char) ('0' + i);
            totalQuestionMark--;
            int from = index;
            while (from < patternArray.length && patternArray[from] != '?') {
                from++;
            }
            findScheduleRec(r, dayHours, patternArray, from, re, totalQuestionMark);
            patternArray[index] = '?';
            totalQuestionMark++;
        }
    }
}
Reasons:
  • Blacklisted phrase (1): ???
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Vishwas Raj