CS50 Tideman sort_pairs - cs50

My code is not passing check50 and I can't find what's wrong.
// Sort pairs in decreasing order by strength of victory
void sort_pairs(void)
{
// TODO
for (int i = 0; i < pair_count - 1; i++)
{
int c = 0;
int high = preferences[pairs[i].winner][pairs[i].loser] -preferences[pairs[i].loser}[pairs[i].winner];
for (int j = i + 1; j < pair_count; j++)
{
if (preferences[pairs[j].winner][pairs[j].loser] - preferences[pairs[j].loser][pairs[j].winner] > high)
{
high = preferences[pairs[j].winner][pairs[j].loser] - preferences[pairs[j].loser][pairs[j].winner];
c = j;
}
}
pair temp = pairs[i];
pairs[i] = pairs[c];
pairs[c] = temp;
}
return;
}

Related

Interleaving Strings LCS

Hi I was trying to solve the interleaving strings problem.Here is the detailed explanation of the problem. https://practice.geeksforgeeks.org/problems/interleaved-strings/1
I was trying using lcs but it was not passing leetcode cases. Here is my Code:-
(I am taking lcs from start and end)
class Solution {
public boolean isInterLeave(String a, String b, String c) {
StringBuffer s=new StringBuffer();
StringBuffer s1=new StringBuffer();
StringBuffer s2=new StringBuffer();
StringBuffer s4=new StringBuffer();
int m=a.length();
int n=c.length();
int q=b.length();
if(n!=m+q){
return false;
}
LinkedHashSet<Integer> res2= new LinkedHashSet<Integer>();
res2= lcs(a,c,m,n);
LinkedHashSet<Integer> res4= new LinkedHashSet<Integer>();
res4= lcs(b,c,q,n);
for(int i=0;i<n;i++){
if(res2.contains(i)==false){
s.append(c.charAt(i));
}
}
for(int i=0;i<n;i++){
if(res4.contains(i)==false){
s1.append(c.charAt(i));
}
}
LinkedHashSet<Integer> res5= new LinkedHashSet<Integer>();
res5= LCS(a,c,m,n);
for(int i=0;i<n;i++){
if(res5.contains(i)==false){
s2.append(c.charAt(i));
}
} LinkedHashSet<Integer> res6= new LinkedHashSet<Integer>();
res6= LCS(b,c,q,n);
for(int i=0;i<n;i++){
if(res6.contains(i)==false){
s4.append(c.charAt(i));
}
}
String z=s.toString();
String u=s1.toString();
String v=s2.toString();
String w=s4.toString();
if( (b.equals(z)==true || a.equals(u)==true) || ( b.equals(v)==true || a.equals(w)==true)){
return true;
}
else{
return false;
}
}
public static LinkedHashSet<Integer> lcs(String X, String Y, int m, int n)
{
int[][] L = new int[m+1][n+1];
// Following steps build L[m+1][n+1] in bottom up fashion. Note
// that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]
for (int i=0; i<=m; i++)
{
for (int j=0; j<=n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X.charAt(i-1) == Y.charAt(j-1))
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = Math.max(L[i-1][j], L[i][j-1]);
}
}
// Following code is used to print LCS
// Create a character array to store the lcs string
LinkedHashSet<Integer> linkedset =
new LinkedHashSet<Integer>();
// Start from the right-most-bottom-most corner and
// one by one store characters in lcs[]
int i=1;
int j=1;
while (i <= m && j <= n)
{
// If current character in X[] and Y are same, then
// current character is part of LCS
if (X.charAt(i-1) == Y.charAt(j-1))
{
// Put current character in result
linkedset.add(j-1);
// reduce values of i, j and index
i++;
j++;
}
// If not same, then find the larger of two and
// go in the direction of larger value
else if (L[i-1][j] > L[i][j-1])
i++;
else
j++;
}
return linkedset;
}
public static LinkedHashSet<Integer> LCS(String X, String Y, int m, int n)
{
int[][] L = new int[m+1][n+1];
// Following steps build L[m+1][n+1] in bottom up fashion. Note
// that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]
for (int i=0; i<=m; i++)
{
for (int j=0; j<=n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0;
else if (X.charAt(i-1) == Y.charAt(j-1))
L[i][j] = L[i-1][j-1] + 1;
else
L[i][j] = Math.max(L[i-1][j], L[i][j-1]);
}
}
// Following code is used to print LCS
// Create a character array to store the lcs string
LinkedHashSet<Integer> linkedset =
new LinkedHashSet<Integer>();
// Start from the right-most-bottom-most corner and
// one by one store characters in lcs[]
int i = m;
int j = n;
while (i > 0 && j > 0)
{
// If current character in X[] and Y are same, then
// current character is part of LCS
if (X.charAt(i-1) == Y.charAt(j-1))
{
// Put current character in result
linkedset.add(j-1);
// reduce values of i, j and index
i--;
j--;
}
// If not same, then find the larger of two and
// go in the direction of larger value
else if (L[i-1][j] > L[i][j-1])
i--;
else
j--;
}
return linkedset;
}
}
Can anyone suggest an LCS approach to this problem?.My code is not passing the following test case
"cacabcbaccbbcbb" -String A
"acaaccaacbbbabbacc"-String B
"accacaabcbacaccacacbbbbcbabbbbacc"-String C
This will be the LCS+DP approach. Try it out:
class Solution {
public boolean isInterleave(String s1, String s2, String s3) {
int m = s1.length(), n = s2.length();
if (n + m != s3.length()) return false;
if (s3.length() == 0) return true;
boolean[][] dp = new boolean[m+1][n+1];
dp[0][0] = true;
for (int i = 0; i <= m; i++) {
if (s1.substring(0, i).equals(s3.substring(0, i)))
dp[i][0] = true;
else
dp[i][0] = false;
}
for (int j = 0; j <= n; j++) {
if (s2.substring(0, j).equals(s3.substring(0, j)))
dp[0][j] = true;
else
dp[0][j] = false;
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
dp[i][j] = (dp[i-1][j] && s1.charAt(i-1) == s3.charAt(i+j-1))
|| (dp[i][j-1] && s2.charAt(j-1) == s3.charAt(i+j-1));
}
}
return dp[m][n];
}
}

Google Code Jam: My solution to Train Timetable problem is failing

I'm trying to solve this problem from Google's Code Jam 2008:
The problem is called Train Timetable and you can find the full explanation here:
Code Jam - Train Timetable
Note: I've decided to solve the problem with Node.js.
My code is the next:
function timeToMinutes(time) {
const timeArray = time.split(":");
const hours = parseInt(timeArray[0]);
const minutes = parseInt(timeArray[1]);
const hoursInMinutes = hours * 60;
const total = hoursInMinutes + minutes;
return total;
}
function timetableFiller(NAB, NBA, array) {
let timetable = {
departuresFromA: [],
arrivalsToB: [],
departuresFromB: [],
arrivalsToA: [],
};
for (let i = 0; i < NAB + NBA; i++) {
let tempArr = [];
tempArr = array[i].split(" ");
if (i < NAB) {
timetable.departuresFromA.push(tempArr[0]);
timetable.arrivalsToB.push(tempArr[1]);
} else {
timetable.departuresFromB.push(tempArr[0]);
timetable.arrivalsToA.push(tempArr[1]);
}
}
return timetable;
}
function timetableToMinutes(timetable) {
let timetableMinutes = {
departuresFromA: [],
arrivalsToB: [],
departuresFromB: [],
arrivalsToA: [],
};
for (const property in timetable) {
timetable[property].map((element) =>
timetableMinutes[property].push(timeToMinutes(element))
);
}
return timetableMinutes;
}
function trainsNeededCounter(arrivalsFromDestiny, departuresFromOrigin, tat) {
let trainsNeeded = departuresFromOrigin.length;
for (let i = 0; i < arrivalsFromDestiny.length; i++) {
for (let j = 0; j < departuresFromOrigin.length; j++) {
if (arrivalsFromDestiny[i] + tat <= departuresFromOrigin[j]) {
trainsNeeded = trainsNeeded - 1;
departuresFromOrigin.splice(j, 1);
}
}
}
return trainsNeeded;
}
function responseGenerator(inputA, inputB, caseNumber) {
return `Case #${caseNumber}: ${inputA} ${inputB}`;
}
function problemSolution(input) {
const numberOfCases = parseInt(input[0]);
input.shift();
let response = [];
let caseNumber = 0;
let NAB;
let NBA;
for (let i = 0; i < input.length; i = i + NAB + NBA + 2) {
caseNumber = caseNumber + 1;
const tat = parseInt(input[i]);
const arrayNTrips = input[i + 1].split(" ");
NAB = parseInt(arrayNTrips[0]);
NBA = parseInt(arrayNTrips[1]);
const arraySchedule = input.slice(i + 2, i + 2 + NAB + NBA);
const timetable = timetableFiller(NAB, NBA, arraySchedule);
const timetableMinutes = timetableToMinutes(timetable);
const trainsNeededAB = trainsNeededCounter(
timetableMinutes.arrivalsToA,
timetableMinutes.departuresFromA,
tat
);
const trainsNeededBA = trainsNeededCounter(
timetableMinutes.arrivalsToB,
timetableMinutes.departuresFromB,
tat
);
response.push(
responseGenerator(trainsNeededAB, trainsNeededBA, caseNumber)
);
}
return response;
}
function readInput() {
const readline = require("readline");
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false,
});
let problem = [];
rl.on("line", (line) => {
problem.push(line);
}).on("close", () => {
const solution = problemSolution(problem);
solution.map((response) => console.log(response));
});
}
readInput();
How to replicate the issue
You should login into Code Jam with your Google account.
Paste into the code area on the right side and activate the Test run mode.
As input you can copy paste the sample input provided in the problem and you can see that the output is exactly as the sample output.
I've tried with my own variations of the input and the responses seems correct but when I run the real attempt the platform says WA or Wrong Answer.
Thank you so much for your help!
I made a video about this recently. You should check it out.
I think you can understand the logic flow from it. We are both doing the same thing basically.
https://youtu.be/_Cp51vMDZAs
-check this out
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
void solve(int t)
{
int NA, NB;
float T;
cin >> T >> NA >> NB;
cin.ignore();
vector<string> ASchedule, BSchedule;
if (NA > 0)
for (int i = 0; i < NA; i++)
{
string s;
getline(cin, s);
ASchedule.push_back(s);
}
if (NB > 0)
for (int i = 0; i < NB; i++)
{
string s;
getline(cin, s);
BSchedule.push_back(s);
}
int alength, blength;
alength = (int)ASchedule.size();
blength = (int)BSchedule.size();
if (alength == 0 || blength == 0)
{
cout << "Case #" << t << ": " << alength << " " << blength << endl;
return;
}
float TT = T / 10;
string val, value;
int d;
float ADH, ADM, AAH, AAM, BDH, BDM, BAH, BAM;
vector<float> AD, AA, BD, BA;
for (int i = 0; i < alength; i++)
{
val = ASchedule[i];
ADH = stof(val.substr(0, 2));
AAH = stof(val.substr(6, 2));
ADM = stof(val.substr(3, 2));
AAM = stof(val.substr(9, 2));
if (val.at(9) == '0')
{
AAM /= 10;
AAM += TT;
AAM *= 10;
}
else
AAM += T;
if (AAM > 59)
{
d = -1;
while (AAM != 59)
{
AAM -= 1;
d++;
}
AAH++;
AAM = 0;
AAM += d;
}
// if (ADH > 23)
// ADH = 0;
// if (AAH > 23)
// AAH = 0;
ADM /= 100;
ADH += ADM;
AAM /= 100;
AAH += AAM;
AD.push_back(ADH);
AA.push_back(AAH);
}
for (int j = 0; j < blength; j++)
{
value = BSchedule[j];
BDH = stof(value.substr(0, 2));
BDM = stof(value.substr(3, 2));
BAH = stof(value.substr(6, 2));
BAM = stof(value.substr(9, 2));
if (value.at(9) == '0')
{
BAM /= 10;
BAM += TT;
BAM *= 10;
}
else
BAM += T;
if (BAM > 59)
{
d = -1;
while (BAM != 59)
{
BAM -= 1;
d++;
}
BAH++;
BAM = 0;
BAM += d;
}
// if (BDH > 23)
// BDH = 0;
// if (BAH > 23)
// BAH = 0;
BDM /= 100;
BDH += BDM;
BAM /= 100;
BAH += BAM;
BA.push_back(BAH);
BD.push_back(BDH);
}
int no1 = alength, no2 = blength;
sort(BD.begin(), BD.end());
sort(BA.begin(), BA.end());
sort(AA.begin(), AA.end());
sort(AD.begin(), AD.end());
for (int i = 0; i < alength; i++)
for (int j = 0; j < blength; j++)
if (AD[i] >= BA[j])
{
no1--;
BA[j] = 50;
break;
}
for (int i = 0; i < blength; i++)
for (int j = 0; j < alength; j++)
if (AA[j] <= BD[i])
{
no2--;
AA[j] = 50;
break;
}
cout << "Case #" << t << ": " << no1 << " " << no2 << endl;
}
int main()
{
int N;
cin >> N;
cin.ignore();
for (int t = 1; t <= N; t++)
solve(t);
}

C# Lock implement goes wrong

I try to make a lock on the incrementer "counter" in the Countrange method.
The counter should count under some conditions in the threads. If I complete the threads in order (not parallel) i get the right counter value over and over, but when i try to lock like i do in de program, it still isn't threadsafe, because i get diffrent counter values when i run the program a few times.
{
class Program
{
static int e, p, b, m;
static int counter = 0;
static int lok = 0;
static void Main(string[] args)
{
string input = Console.ReadLine();
string[] inputs = input.Split(' ');
counter = 0;
p = Convert.ToInt32(inputs[4]);
e = Convert.ToInt32(inputs[2]);
b = Convert.ToInt32(inputs[1]);
m = Convert.ToInt32(inputs[3]);
Thread[] ts = new Thread[p];
for (int t = 0; t < p; t++)
{
ts[t] = new Thread(countrange);
}
for (int t = 0; t < p; t++)
{
ts[t].Start(t);
}
for (int t = 0; t < p; t++)
{
ts[t].Join();
}
Console.Write(counter);
//Console.ReadKey();
}
public static void countrange(object mt)
{
int to = eind * (((int)mt + 1) / p) + verdeler + b;
int from = eind * (((int)mt) / p) + verdeler - a + b;
for (int i = from; i < to; i++)
{
proef = proef + moduler * keer;
}
{
if (proef % m == 0)
lock (mt)
{
counter++;
}
}
}
}
}
}
I made the lock static, now it works

Dynamic programming money change

I have two functions recursive and iterative to calculate money change; in the iterative version I needed to check for if the money is multiple of change (money modulus change is zero): is there a way to do iterative without checking for modulus?
public static int MoneyChangeRecur(int money, int[] changes)
{
int minChange = 0;
if (money == 0) return 0;
int min = int.MaxValue;
for (int i = 0; i < changes.Length; i++)
{
if (money >= changes[i])
{
minChange = MoneyChangeRecur(money - changes[i], changes);
if (minChange + 1 <= min)
{
min = minChange + 1;
}
}
}
return min;
}
static int IterativeMoneychange(int money)
{
int[] ar = new int[money + 1];
int[] change = { 6, 5, 1 };
int min = 9999;
int index = 0;
for (int i = 0; i < money+1; i++)
{
min = 99999;
index = 0;
bool modSet = false;
for (int j= 0; j <change.Length; j++)
{
if (i >= change[j])
{
int mod=(i % change[j]);
if(mod==0&&change[j]!=1)
{
if (!modSet) min = 99999;
if ((i-change[j] )< min)
{
min = (i - change[j]);
modSet = true;
}
}
else
{
if ((i - change[j]) < min)
{
min = (i - change[j]);
modSet = false;
}
}
}
}
if (min != 99999)// min = 0;
ar[i] = ar[min] +1;
}
return ar[money];
}enter code here

If I have given the word ssseeerabbcccdd then output should be like s3e3rab2c3d2 in c#

class Program
{
static void Main(string[] args)
{
Console.Write("Enter Word : ");
string word = Console.ReadLine();
for (var i = 0; i < word.Length; i++)
{
var check = true;
var count = 0;
for (var k = i - 1; k <= 0; k--)
{
if (word[k] == word[i]) check = false;
}
if (check)
{
for (var j = i; j<= word.Length; j++)
{
if (word[i] == word[j]) count++;
}
Console.WriteLine(word[i] + " Occurs at " + count + " places.");
}
}
Console.ReadLine();
}
}
I have tried this one but not working.
The problem is that check is set to false if the string contains two adjacent identical characters. So if (check) {...} won't be executed, if this is the case. Another problem is that you set k to string position -1 in the first iteration of for (var k = i - 1; k <= 0; k--). If i=0, then k will be -1. You also need only one inner loop.
Here is a possible solution, although slightly different than your's.
class Program
{
static void Main(string[] args)
{
Console.Write("Enter Word : ");
string word = Console.ReadLine();
int i = 0;
while (i < word.Length)
{
int count = 1;
for (int k = i+1; k < word.Length; k++)
if (word[i] == word[k])
count++;
if (count>1)
{
Console.WriteLine(word[i] + " Occurs at " + count + " places.");
}
i += count; // continue next char or after after repeated chars
}
Console.ReadLine();
}
}

Resources