Skip to content

Instantly share code, notes, and snippets.

@ujjwal-kr
Created November 18, 2022 11:30
Show Gist options
  • Save ujjwal-kr/59234e996b2102e32effc8659cf796af to your computer and use it in GitHub Desktop.
Save ujjwal-kr/59234e996b2102e32effc8659cf796af to your computer and use it in GitHub Desktop.
#include <iostream>
#include <unordered_map>
#include <string>
#include <algorithm>
void get_label(std::unordered_map<std::string, size_t> map, int pc) {
std::vector<std::size_t> label_point_vec = {};
std::vector<std::string> key_vec = {};
for (const auto &pair : map) {
label_point_vec.push_back(pair.second);
key_vec.push_back(pair.first);
}
std::sort(label_point_vec.begin(), label_point_vec.end());
size_t final_point;
std::string final_label;
std::vector<size_t> point_stack;
for (auto point : label_point_vec) {
if (pc >= point) {
point_stack.push_back(point);
}
}
final_point = point_stack[point_stack.size() - 1];
for (auto& k : key_vec) {
auto n = map.find(k);
if (n->second == final_point) {
final_label = k;
break;
}
}
std::cout << final_label << std::endl;
}
int main() {
std::unordered_map<std::string, size_t> map;
int pc = 17;
map["main"] = 0;
map["kek"] = 5;
map["ok"] = 17;
get_label(map, pc);
}
@ujjwal-kr
Copy link
Author

Question

You are given a relational mapping such that:

main: 0
test: 7
kek: 15

Note that the numbers cannot be repeated. This is an example function mapping of the ram programming language. Each key here is the function name and the number represents the address the function procedure starts. There is also another input; the program_counter. Treat it as a constant here.

The problem

There is no way to log errors in the programming language as of now. The function mapping is generated from the parser and you also have the line number (given as the program_counter) where the error has occurred. The program counter can be anywhere between those numbers; or can be equal to those numbers as well.
For example, if the program counter is 8, the error should in the "test" label because 8 lies between 7 and 15. (in the above example).

Write a program which takes the map and program counter as the input and outputs the appropriate label associated.

Test Case

main: 0
test: 7
kek: 15

pc: 9

expected output: test

OR

main: 0
test: 7
kek: 15

pc: 15

expected output: kek

@ujjwal-kr
Copy link
Author

Here is the cpp implementation of this problem, This is my first cpp program so I know its not perfect the original rust implementation can be found in https://github.com/ujjwal-kr/ram in the dev branch, at src/funcs/errors.rs

@ujjwal-kr
Copy link
Author

hint:

u r smart enough to get better than this..

if pc is:

0 - 6 -> main
7-14 -> test
15-infinite -> kek

@TheEmperor342
Copy link

TheEmperor342 commented Nov 18, 2022

d = { 'kek': 15, 'main': 0, 'test': 7 }
d_values = d.values()
x = int(input("ok: "))

for i in range(len((s := sorted(d_values)))-1):
  if (x > s[i] and x < s[i + 1]) or x == s[i+1] or x == s[0]:
    print(list(d.keys())[d_values.index(s[i])])
    break
else: print(list(d.keys())[d_values.index(s[-1])])

@0xGamer
Copy link

0xGamer commented Nov 18, 2022

import * as readline from "readline";
let inp = new Map<string, number>([
  ["kek", 15],
  ["main", 0],
  ["test", 7],
]);
let rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});
rl.question("Please enter error code: ", (answer) => {
  const parsed = parseInt(answer);
  if (!Number.isNaN(parsed)) {
    let max = -1;
    let result: string = "Error";

    inp.forEach((value: number, key: string) => {
      if (value <= parsed && value >= max) {
        max = value;
        result = key;
      }
    });
    console.log(result);
  } else {
    throw new Error("Invalid Error Code");
  }
  rl.close();
});

@PhantomKnight287
Copy link

use std::io;

fn main() {
    let mappings = vec![vec!["main", "0"], vec!["test", "7"], vec!["kek", "15"]];

    let mut input = String::new();
    println!("Enter A Number: ");
    io::stdin()
        .read_line(&mut input)
        .expect("An error occured while reading input");
    let input = input
        .trim()
        .parse::<i32>()
        .expect("Invalid Number Supplied");
    let size = mappings.len() - 1;
    for (key, value) in mappings.iter().enumerate() {
        if (input >= mappings[mappings.len() - 1][1].parse::<i32>().unwrap()) {
            return println!("{}", mappings[mappings.len() - 1][0]);
        }

        if (input >= value[1].parse::<i32>().unwrap()
            && input < mappings[key + 1][1].parse::<i32>().unwrap())
        {
            return println!("{}", mappings[key][0]);
        }
    }
}

Took me almost an hour but I think it was worth it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment