Chap5 HW

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 4

Samantha Sinnerine

CSCI-313
HW 5

R-5.10

We can define a recursive method called arraySum. The method takes the array and
the size 'n' as parameters. In the base case, when 'n' is 0, the method returns 0
as there are no elements to sum. Otherwise, it initializes a variable sum to 0 and
iterates through each element in the array, adding it to the sum. It then makes a
recursive call to arraySum with the updated size 'n-1' and adds the returned sum to
the current sum. Finally, it returns the sum, which represents the sum of all
elements in the array

-----------------------------------------------------------------------------------
--------------------------------------
C-5.16 -

To solve the Towers of Hanoi puzzle recursively, we can define a function called
hanoi that takes four parameters: the number of disks 'n', the source peg 'a', the
destination peg 'c', and the auxiliary peg 'b'. The base case is when 'n' is 1,
where we move the disk directly from the source peg to the destination peg. For
larger 'n', we recursively move 'n-1' disks from the source peg to the auxiliary
peg using the destination peg as temporary storage, then move the remaining largest
disk from the source peg to the destination peg, and finally recursively move the
'n-1' disks from the auxiliary peg to the destination peg using the source peg as
temporary storage.

-----------------------------------------------------------------------------------
--------------------------------------
P-5.28

import java.util.*;

public class SummationPuzzleSolver {


private static final char[] LETTERS = {'p', 'o', 't', 'a', 'n', 'b', 'i', 'd',
'g', 'l', 'y'};

public static void main(String[] args) {


String[] puzzles = {"pot + pan = bib", "dog + cat = pig", "boy + girl =
baby"};

for (String puzzle : puzzles) {


System.out.println("Solving puzzle: " + puzzle);
solvePuzzle(puzzle);
System.out.println();
}
}

private static void solvePuzzle(String puzzle) {


List<Character> availableDigits = new ArrayList<>();
for (char digit = '0'; digit <= '9'; digit++) {
availableDigits.add(digit);
}

boolean solutionFound = solveRecursively(puzzle, availableDigits, 0, new


HashMap<>());

if (!solutionFound) {
System.out.println("No solution found!");
}
}

private static boolean solveRecursively(String puzzle, List<Character>


availableDigits, int index, Map<Character, Character> assignment) {
if (index == LETTERS.length) {
if (isSolutionValid(puzzle, assignment)) {
printSolution(puzzle, assignment);
return true; // Solution found
}
return false; // Not a valid solution
}

char letter = LETTERS[index];


for (char digit : availableDigits) {
assignment.put(letter, digit);
availableDigits.remove(Character.valueOf(digit));

if (solveRecursively(puzzle, availableDigits, index + 1, assignment)) {


return true; // Solution found
}

assignment.remove(letter);
availableDigits.add(digit);
}

return false; // No solution found


}

private static boolean isSolutionValid(String puzzle, Map<Character, Character>


assignment) {
String[] equation = puzzle.split("=");
String leftHandSide = equation[0].trim();
String rightHandSide = equation[1].trim();

int leftHandSideValue = evaluateExpression(leftHandSide, assignment);


int rightHandSideValue = evaluateExpression(rightHandSide, assignment);

return leftHandSideValue == rightHandSideValue;


}

private static int evaluateExpression(String expression, Map<Character,


Character> assignment) {
StringBuilder sb = new StringBuilder();
for (char ch : expression.toCharArray()) {
if (Character.isLetter(ch)) {
char digit = assignment.get(ch);
sb.append(digit);
} else {
sb.append(ch);
}
}
return Integer.parseInt(sb.toString());
}
private static void printSolution(String puzzle, Map<Character, Character>
assignment) {
StringBuilder sb = new StringBuilder();
for (char ch : puzzle.toCharArray()) {
if (Character.isLetter(ch)) {
char digit = assignment.get(ch);
sb.append(digit);
} else {
sb.append(ch);
}
}
System.out.println("Solution: " + sb.toString());
}
}

-----------------------------------------------------------------------------------
--------------------------------------
P-5.29

public class drawRuler_nonRec {


public static void drawInterval(int centralLength) {
int numTicks = (int) Math.pow(2, centralLength) - 1; // Number of ticks to
be drawn

for (int i = 0; i < numTicks; i++) {


String tickLine = getTickLine(i, centralLength);
System.out.println(tickLine);
}
}

private static String getTickLine(int number, int centralLength) {


StringBuilder tickLine = new StringBuilder();
int numDashes = getNumDashes(number);

// Add dashes to the tick line


for (int i = 0; i < numDashes; i++) {
tickLine.append("-");
}

// Add the tick label if it is the center tick


if (numDashes == centralLength) {
tickLine.append(" " + number);
}

return tickLine.toString();
}

private static int getNumDashes(int number) {


int count = 0;
while (number % 2 == 1) {
count++;
number >>= 1; // Right shift the number by 1 bit
}
return count;
}
}

You might also like