You are on page 1of 4

DEPARTMENT OF

COMPUTER SCIENCE & ENGINEERING

Experiment 3.2
Student Name: Divyansh Rana UID: 21BCS5863
Branch: CSE Section/Group: 632-A
Semester: 5th Date of Performance:25/10/23
Subject Name: Advanced Programming Subject Code: 21CSP-314

Task-1
1 Aim: You are given a number N. In one operation, you can either increase the value of N by 1 or
decrease the value of N by 1.

2 Objective: Determine the minimum number of operations required (possibly zero) to convert number
N to a number P such that binary representation P of is a palindrome.

3 Code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Math;

public class ClosestTwoNumbersInBinaryRepresentation {

public static int bitToInt(String p) {


int sz = p.length();
int ans = 0;
for (int i = 0; i < sz; i++) {
ans += Integer.parseInt(p.charAt(i) + "") * (int) Math.pow(2, sz - i - 1);
}
return ans;
}

public static void bin(ArrayList<Integer> v, String p, int si, int sz) {


if (si <= 0) {
String res1 = p;
int x = res1.length();
int y = sz % 2 == 0 ? 2 : 1;
for (int i = x - y; i >= 0; i--) {
res1 += res1.charAt(i);
}
int res = bitToInt(res1);
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
v.add(res);
return;
}
p += "0";
bin(v, p, si - 1, sz);
p = p.substring(0, p.length() - 1);
p += "1";
bin(v, p, si - 1, sz);
}

public static void main(String[] args) {


ArrayList<Integer> v = new ArrayList<>();
v.add(0);
for (int i = 1; i < 32; i++) {
String s = "";
String p = "1";
bin(v, p, Math.

1. Script and Output:


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

Task-2
1 Aim: A 10 x 10 Crossword grid is provided to you, along with a set of words (or names of
places) which need to be filled into the grid. Cells are marked either + or -. Cells marked with a
- are to be filled with the word list.

2 Objective: Complete the crosswordPuzzle function in the editor below. It should return an array of
strings, each representing a row of the finished puzzle.

3 Code:
public static Map<Integer, Integer> solveSets(Set<Set<Integer>> ss, List<List<Integer>> ws,
Map<Integer, Integer> used) {
if (ws.isEmpty()) {
return used;
}

List<Integer> w = ws.remove(0);

for (Set<Integer> set : ss) {


if (set.size() != w.size()) {
continue;
}

boolean ok = true;
int rc = set.iterator().next();
for (int d = 0; d < w.size(); d++) {
if (used.containsKey(rc) && used.get(rc) != w.get(d)) {
ok = false;
break;
}

rc = add(rc, set.toArray(new Integer[0])[d + 1]);


}

if (!ok) {
continue;
}

Map<Integer, Integer> used2 = new HashMap<>(used);


rc = set.iterator().next();
for (int d = 0; d < w.size(); d++) {
used2.put(rc, w.get(d));
rc = add(rc, set.toArray(new Integer[0])[d + 1]);
}

Set<Set<Integer>> ss2 = new HashSet<>(ss);


ss2.remove(set);

Map<Integer, Integer> attempt = solveSets(ss2, ws, used2);


DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
if (attempt != null) {
return attempt;

1. Script and Output:

You might also like