Amazon puzzle asked in initial screening test [closed] - amazon

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 days ago.
Improve this question
Amazon can sell products in packs of 6,9 and 20. Given a number N, give the algorythm to find its possible or not.
Ex - 21 -- Not Possible
47 (9*3+20) -- Possible

A very simple, but recursive, solution would be
private bool isDiv(int n) {
if (n < 6) {
return false;
} else if (n == 6 || n == 9 || n == 20) {
Console.Write(n);
return true;
} else if (isDiv(n - 6)) {
Console.Write(" + " + 6);
return true;
} else if (isDiv(n - 9)) {
Console.Write(" + " + 9);
return true;
} else if (isDiv(n - 20)) {
Console.Write(" + " + 20);
return true;
}
return false;
}
But keep in mind that this is not the fastest solution - but it works good for small numbers like the ones in your example
Oh and 21 is quite possible:
2*6 + 9 = 21

A very simple logical solution using C
#include <stdio.h>
int main(){
int x = 6, y=9, z=20,n=26,t1,t2,i;
t1 = n%z;
for(i=0; i<2;i++)
{
if (t1 < y)
{
t2 = t1%x;
}
else
{
t2 = t1%y;
t1 = t2;
}
}
if (t2 == 0 || t1 == 0)
{
printf("Yes we can do it");
}
else
{
printf("we cannot do it");
}
}

Related

From plain text to TEX - Javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I'm building a math application and I want to show math formulas written with a good design in javascript (nodejs). So I would transorm plain text to TEX format.
From formula like this:
(25*5)/6
To formula like this:
\frac{(25 \cdot 5)}{6}
To good design:
If there are other known methods you advise me.
Many thanks in advance!
I've rewritten this expression parser from java to javascript. not the most straightforward way. Note that this is not extensively tested.
function texFromExpression(str){
var pos = -1, ch;
function nextChar(){
ch = (++pos < str.length) ? str.charAt(pos) : -1;
}
function eat(charToEat) {
while (ch == ' ') nextChar();
if (ch == charToEat) {
nextChar();
return true;
}
return false;
}
function parse(){
nextChar();
var x = parseExpression();
if (pos < str.length) throw `Unexpected: ${ch}`
return x;
}
function parseExpression() {
var x = parseTerm();
for (;;) {
if (eat('+')) x = `${x} + ${parseTerm()}` // addition
else if (eat('-')) x = `${x} - ${parseTerm()}` // subtraction
else return x;
}
}
function parseTerm() {
var x = parseFactor();
for (;;) {
if (eat('*')) x=`${x} \\cdot ${parseTerm()}`; // multiplication
else if (eat('/')) x= `\\frac{${x}}{${parseTerm()}}`; // division
else return x;
}
}
function parseFactor() {
if (eat('+')) return `${parseFactor()}`; // unary plus
if (eat('-')) return `-${parseFactor()}`; // unary minus
var x;
var startPos = pos;
if (eat('(')) { // parentheses
x = `{(${parseExpression()})}`
eat(')');
} else if ((ch >= '0' && ch <= '9') || ch == '.') { // numbers
while ((ch >= '0' && ch <= '9') || ch == '.') nextChar();
x = str.substring(startPos, pos);
} else if (ch >= 'a' && ch <= 'z') { // variables
while (ch >= 'a' && ch <= 'z') nextChar();
x= str.substring(startPos, pos);
if(x.length>1){
x = `\\${x} {${parseFactor()}}`;
}
} else {
throw `Unexpected: ${ch}`
}
if (eat('^')) x = `${x} ^ {${parseFactor()}}` //superscript
if(eat('_')) x = `${x}_{${parseFactor()}}`;
return x;
}
return `$${parse()}$`;
}

ENFILE: File table overflow Node.js

I am trying to make a more memory efficient prime number generator. I can't think of anything better than using a file as my prime number array, and read line by line synchronously. I run this and at about 29000 it gives me the ENFILE: File table overflow error. Any ideas to fix/improve this code?
This is the library I'm using
#!/usr/bin/env node
var num = 3,
prime,
fs = require("fs"),
readline = require("./line_reader.js");
console.log("Hundreds: 2");
console.log("Hundreds: 3");
function appendPrime (num) {
fs.appendFileSync("Primes.txt", num+'\n');
}
while (true) {
prime = true;
var times = Math.floor(Math.pow(num, 0.5));
if (num % 2 == 0 || num % 3 == 0) {
prime = false;
} else {
readline.eachLine("Primes.txt", function (line, last, cb) {
if (num % line == 0) {
prime = false;
cb(true);
} else {
cb();
}
});
}
if (prime) {
var place = String(num).length;
switch (true) {
case place <= 3:
console.log("Hundreds: "+num);
break;
case place <= 5 :
console.log("Thousands: "+num);
break;
case 6 :
console.log("Hundred thousands: "+num);
break;
case place <= 8 :
console.log("Millions: "+num);
break;
case 9 :
console.log("Hundred millions: "+num);
break;
case place >= 10 :
console.log("Billions or above: "+num);
break;
}
appendPrime(num);
}
num += 2;
}
Try this
sudo launchctl limit maxfiles 16384 16384 && ulimit -n 16384

Node.js not writing to file?

I am trying to make a prime number sieve, and it works very well for me. However, it doesn't write the data to a file. It says that the primes were dumped to a file. Is there some size limit on fs.writeFile? The prime number array can get very large. Can someone help me with this?
Code:
#!/usr/bin/env node
var primes = ["2", "3"];
var num = 3;
var prime;
var fs = require("fs");
console.log("Hundreds: 2");
console.log("Hundreds: 3");
while (true) {
prime = true;
var times = Math.pow(num, 0.5);
for (var i=0;i<times;i++) {
if (num % parseInt(primes[i], 32) == 0) {
prime = false;
break;
}
}
if (prime) {
var place = String(num).length;
switch (true) {
case place <= 3:
console.log("Hundreds: "+num);
break;
case place <= 5 :
console.log("Thousands: "+num);
break;
case 6 :
console.log("Hundred thousands: "+num);
break;
case place <= 8 :
console.log("Millions: "+num);
break;
case 9 :
console.log("Hundred millions: "+num);
break;
case place >= 10 :
console.log("Billions or above: "+num);
break;
}
primes.push(num.toString(32));
prime = false;
}
if ((num - 1) % 5000000 == 0) {
fs.writeFile("Primes.txt", JSON.stringify(primes, null, '\t'), function (err) {
if (err) {
console.log("Primes couldn't be dumped");
throw err;
}
console.log("Primes dumped");
});
}
num += 2;
}
By running your code I came to the conclusion that somehow the primes calculation were disturbing the file write. So I tried using fs.writeFileSync(...) and it worked. The file is actually written pretty fast compared to the time it takes to reach your 5000000 threshold (in the long run, it may start taking a lot of time because you have over 300000 new primes being generated between your file writes and you write all the previous primes as well). I really don't know why the asynchronous method isn't writing it. It may be too busy calculating the primes. You know, nodejs asynchronous calls aren't parallel.
try something like this
...
if ((num - 1) % 5000000 == 0) {
fs.writeFileSync("Primes.txt", JSON.stringify(primes, null, '\t'))
console.log("Primes dumped");
}
...
the link to the api is here: https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback
Be aware that Primes.txt will be rewritten every time. Think about using fs.appendFileSync(...). This would solve the problem taking too long to write the file after some time the code is running.
I've worked on '.appendFileSync()'. And for that, I had to imitate the 'JSON.stringify()' output for array type. This is my code so far:
var primes = ["2", "3"];
var num = 3;
var prime;
var fs = require("fs");
latestPrimes = "[\n\t2,\n\t3"
while (true) {
prime = true;
var times = Math.pow(num, 0.5);
for (var i=0;i<times;i++) {
if (num % parseInt(primes[i], 32) == 0) {
prime = false;
break;
}
}
if (prime) {
var place = String(num).length;
if (place <= 3)
console.log("Hundreds: "+num);
else if (place <= 5)
console.log("Thousands: "+num);
else if (place === 6)
console.log("Hundred thousands: "+num);
else if (place <= 8)
console.log("Millions: "+num);
else if (place === 9)
console.log("Hundred millions: "+num);
else if (place >= 10)
console.log("Billions or above: "+num);
primes.push(num.toString(32));
latestPrimes += ",\n\t"+num.toString(32)
}
if ((num - 1) % 5000000 == 0) {
console.log('amount of primes:', primes.length)
fs.appendFileSync("Primes.txt", latestPrimes)
console.log("Primes dumped");
latestPrimes = ""
}
num += 2;
}
when you stop the program, you just have add the string "\n]" to the end of the file to close the array.

Optimising A* pathfinding, runs very slow. Possible bugs(?) visual c++

Hi I'm having a few problems with my A* pathfinding algorithm. The algorithm does successfully execute, however in a debug environment it executes in about 10 seconds, in release it will still take 2-3 seconds. This speed is way too slow. I suspect this is either due to a bug in the code, or the fact it isn't well optimised.
The map that pathfinding is being used on is a 30*30 grid, with each square being 10 unites away from one another.
I have noticed when running the algorithm, that when the open and closed list are searched to see if a node already exists, the node already stored in one of the lists always has a lower cost, so there is no updating of nodes. Not sure if this is normal or not. Also, I am not sure if quicksort is a good sort to be using in this situation.
Here is the code:
The coords struture used as a node:
struct coords
{
int x;
int z;
coords* parent;
int cost;
int score;
};
The sort compare function:
bool decompare(coords* o1, coords* o2)
{
return (o1->score < o2->score);
}
The main pathfind loop:
while (!goalFound) //While goal has not been found
{
current = openList.front(); //Retrieve current state from the open list
openList.pop_front();
for (int count = 1; count < 5; count++)
{
if (!goalFound)
{
coords* possibleState = new (coords); //Allocate new possible state
found = false;
if (count == 1)
{
possibleState->x = current->x;
possibleState->z = current->z + 10; //North
}
else if (count == 2)
{
possibleState->x = current->x + 10; //East
possibleState->z = current->z;
}
else if (count == 3)
{
possibleState->x = current->x; //South
possibleState->z = current->z - 10;
}
else if (count == 4)
{
possibleState->x = current->x - 10; //West
possibleState->z = current->z;
}
if (possibleState->x >-1 && possibleState->x <291 && possibleState->z >-1 && possibleState->z < 291) //If possible state is in game boundary
{
possibleState->cost = current->cost + 10; //Add 10 to current state to get cost of new possible state
int a = (possibleState->x / 10) + (30 * (possibleState->z / 10)); //get index of map
if (map[a] != wallTest) //Test possible state is not inside a wall
{
p = openList.begin();
while (p != openList.end() && !found) //Search open list to see if possible state already exists
{
if (possibleState->x == (*p)->x && possibleState->z == (*p)->z) //Already exists
{
found = true;
if (!possibleState->cost >= (*p)->cost) //Test possible state has lower cost
{
(*p)->parent = current; //Update existing with attributes of possible state
a = abs((*p)->x - goalState->x);
b = abs((*p)->z - goalState->z);
(*p)->cost = possibleState->cost;
(*p)->score = (possibleState->cost) + ((a)+(b));
}
}
else
{
found = false; //Set not found
}
p++;
}
q = closedList.begin();
while (q != closedList.end())
{
if (possibleState->x == (*q)->x && possibleState->z == (*q)->z)
{
found = true;
int a = (*q)->cost;
if (possibleState->cost < a) //Test if on closed list
{
(*q)->parent = current;
a = abs((*q)->x - goalState->x);
b = abs((*q)->z - goalState->z);
(*q)->cost = possibleState->cost;
(*q)->score = (possibleState->cost) + ((a)+(b)); //If cost lower push onto open list
coords* newcoord;
newcoord->x = (*q)->x;
newcoord->z = (*q)->z;
newcoord->score = (*q)->score;
newcoord->cost = (*q)->cost;
openList.push_back(newcoord);
closedList.erase(q);
}
}
q++;
}
if (!found) //If not found on either list
{
possibleState->parent = current; //Push onto open list
a = abs((possibleState)->x / 10 - goalState->x / 10);
b = abs((possibleState)->z / 10 - goalState->z / 10);
(possibleState)->score = (possibleState->cost) + ((a)+(b));
openList.push_back(possibleState);
}
sort(openList.begin(), openList.end(), decompare); // Sort the open list by score
}
if (possibleState->x == goalState->x && possibleState->z == goalState->z) //if goal found
{
openList.push_back(possibleState);
node = possibleState;
goalFound = true;
while (node != 0)
{
wayPoints.push_back(*node);
node = node->parent;
wayCount = wayPoints.size() - 1;
}
}
}
}
}
closedList.push_back(current);
}
player->setWayPoints(wayPoints);
wayPoints.clear();
player->setMoved(2);
player->setPath(1);
openList.clear();
closedList.clear();
goalFound = false;
player->setNewPath(1);
return true;
}
else {
return false;
}
}
Are there any bugs that need to be sorted in this code that anyone can see? Or is it just important optimizations that need making? Thanks

Clear list each cell end edit event [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Here I am search by comboboxselected value as search setting and item id
problem appear only when change combobox item and search by another setting get 'item not found' although am sure its exist but not in current list.
if (e.ColumnIndex == 0)
{
List<ComboUnit> ItemUnitsList = new List<ComboUnit>();
ComboUnit ItemUnitsObj = new ComboUnit();
long x = Convert.ToInt64(dataGridView1.Rows[i].Cells[0].Value);
string r = ddlInvSearchSet1.SelectedValue.ToString();
TechTouch.Methods o = new TechTouch.Methods();
List<db.Vitems> itemDetails = o.SearchItem(x, r);
if (itemDetails.Count == 0)
{
{
MessageBox.Show("NO Items Found");
dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[0];
// dataGridView1.Rows[i].Cells [2]= dataGridView1.Columns[2].Index + 1;
dataGridView1.BeginEdit(true);
dataGridView1.AllowUserToAddRows = false;
}
itemDetails.Clear();
dataGridView1.Refresh();
}
else
{
foreach (var item in itemDetails)
{
ItemUnitsObj.UnitName = item.UnitNameArabic;
ItemUnitsObj.UnitId = item.UnitId;
ItemUnitsList.Add(ItemUnitsObj);
ItemUnitsObj = new ComboUnit();
dataGridView1.Rows[i].Cells[1].Value = itemDetails.First().NameArabic;
if (itemDetails.Count > 1)
{
DataGridViewComboBoxCell comboBoxCell = new DataGridViewComboBoxCell();
comboBoxCell.DataSource = ItemUnitsList;
comboBoxCell.DisplayMember = "UnitName";
comboBoxCell.ValueMember = "UnitId";
dataGridView1.Rows[i].Cells[2] = comboBoxCell;
}
else
{
DataGridViewTextBoxCell textBoxCell = new DataGridViewTextBoxCell();
textBoxCell.Value = itemDetails.First().UnitNameArabic;
dataGridView1.Rows[i].Cells[4].Value = itemDetails.First().SalePrice;
dataGridView1.Rows[i].Cells[2] = textBoxCell;
dataGridView1.Rows[i].Cells[7].Value = itemDetails.First().UnitId;
dataGridView1.Refresh();
}
}
}
itemDetails.Clear();
}
Add itemDetails.Clear(); Inside IF statement
if (itemDetails.Count == 0)
{
MessageBox.Show("NO Items Found");
dataGridView1.CurrentCell = dataGridView1.Rows[i].Cells[0];
dataGridView1.Rows[i].Cells[0].Value = "";
dataGridView1.BeginEdit(true);
itemDetails.Clear();
}
else
{
}

Resources