Is there a better, simpler, or more efficient way to process the conjunctions to get the same outcome.
This will take in any coordinating conjunction listing type and get the outcome expected that is expected.
Basically…
I have 3 functions that takes in any type of and - or coordinating conjunction and gives an output of what is intended.
Stage 1
function {
// Takes a sentence
// Replaces `\r` `\n` `\t` and `\s\s` with ` `
// Figures out which part of the sentence is the conjunction part
// Places the conjunction in an array call foundConjunction = []
// Nothing to see here - (Keep Scrolling)
}
Stage 2
First Function
Counts number of whatever I'm looking for… may come in handy in the future… if I want to know how many words or phrases needs to be processed
Example:
4 , tells me the user has 5 items that he/she wants to chose from if he uses , or.
String.prototype.Count = function(find) {
let Key = find.test(this)
if (Key) {
return this.match(find).length
}
else {return 0}
}
Second Function
Picks a random number - used for when there is an , or -or- word or another word
function rand(min, max, interval) {
if (typeof(interval) === 'undefined') interval = 1
let r = Math.floor(Math.random() * (max - min + interval) / interval)
return r * interval + min
//var a = rand(0,2)
//var b = rand(4,6,0.0000001)
}
Third Function
Figures out what the heck you want.
String.prototype.conjunctionProcessing = function () {
let andKey = /,?(\sand\s).*$/g.test(this)
let orKey = /,(\sor\s).*$/g.test(this)
if (andKey===true&&orKey===false) {
let a = this.replace(/,?\sand/g, ',').split(/,\s/g)
let orKey = /\sor\s/g.test(a)
if (orKey) {
for (var i=0; i<a.length; i++) {
let b = a[i]
let orKey = /\sor\s/g.test(b)
if (orKey) {
let c = b.split(' or ');
let d = rand(0, c.length - 1);
a[i] = c[d];
}
}
}
return a
}
if (orKey) {
let a = this.replace(/,\sor?/g, ',').split(/,\s/g)
let orKey = /\sor\s/g.test(a)
if (orKey) {
for (var i=0; i<a.length; i++) {
let b = a[i]
let orKey = /\sor\s/g.test(b)
if (orKey) {
let c = b.split(' or ');
let rIndex = rand(0, c.length - 1);
a[i] = c[rIndex];
}
}
}
let rIndex = rand(0, a.length - 1);
let chosen1 = a[rIndex];
let andKey = /\sand\s/g.test(chosen1);
if (andKey) {return chosen1.split(/\sand\s/g)}
else {return chosen1};
}
}
Processing Time
// Try any of these to see the outcome
// width and height
// width or height
// depth, width and height
// blue, width, and height
// gold, teal, or green
// hamster, cat or dog, horse and cow
// hamster, cat or dog, horse or cow, and mouse
// iPad and iPhone, Galaxy Tab and Galaxy Note 8, or Surface Tablet and Windows Phone
foundConjunction = ["blue, black or white, width and height, or background color"]
s1 = foundConjunction[0];
s2 = s1.conjunctionProcessing()
console.log(s2)
String.prototype.Count = function(find) {
let Key = find.test(this)
if (Key) {
return this.match(find).length
} else {
return 0
}
}
function rand(min, max, interval) {
if (typeof(interval) === 'undefined') interval = 1
let r = Math.floor(Math.random() * (max - min + interval) / interval)
return r * interval + min
//var a = rand(0,2)
//var b = rand(4,6,0.0000001)
}
String.prototype.conjunctionProcessing = function() {
let andKey = /,?(\sand\s).*$/g.test(this)
let orKey = /,(\sor\s).*$/g.test(this)
if (andKey === true && orKey === false) {
let a = this.replace(/,?\sand/g, ',').split(/,\s/g)
let orKey = /\sor\s/g.test(a)
if (orKey) {
for (var i = 0; i < a.length; i++) {
let b = a[i]
let orKey = /\sor\s/g.test(b)
if (orKey) {
let c = b.split(' or ');
let d = rand(0, c.length - 1);
a[i] = c[d];
}
}
}
return a
}
if (orKey) {
let a = this.replace(/,\sor?/g, ',').split(/,\s/g)
let orKey = /\sor\s/g.test(a)
if (orKey) {
for (var i = 0; i < a.length; i++) {
let b = a[i]
let orKey = /\sor\s/g.test(b)
if (orKey) {
let c = b.split(' or ');
let rIndex = rand(0, c.length - 1);
a[i] = c[rIndex];
}
}
}
let rIndex = rand(0, a.length - 1);
let chosen1 = a[rIndex];
let andKey = /\sand\s/g.test(chosen1);
if (andKey) {
return chosen1.split(/\sand\s/g)
} else {
return chosen1
};
}
}
foundConjunction = ["blue, black or white, width and height, or background color"]
s1 = foundConjunction[0];
s2 = s1.conjunctionProcessing()
console.log(s2)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Related
Please excuse the bad structure of the program. I'm a newbie programmer trying my first project in creating a sorting visualizer. I was able to implement bubble sort, but when I came around to trying to see if quick sort worked with the values in the child divs, I keep getting this error. My partition function correctly changes the value in each div, but my quick sort function shoots this error out. What's going on?
return Math.floor(Math.random() * (max - min) + min);
}
function rand_num_height(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
//Visuals
let speed = 500;
let c = 0;
let delay = 10000 / (Math.floor(10 / 10) * speed);
let p = "#75DF5B";
let p1 = "#63D7D8";
let p2 = "#008FF9";
let sorted = "#A946DA";
let p3 = "#E9EC13";
let p4 = "#F50101";
const anim = (bar, height, color) => {
setTimeout(() => {
bar.style.height = height + "px";
bar.style.backgroundColor = color;
}, (c += delay + 50));
};
const bar_container = document.getElementById("bar-container");
let children = bar_container.children;
const generate = document.getElementById("generate");
const btn = document.getElementById("sort-btn");
const reset = document.getElementById("reset");
generate.addEventListener("click", () => {
generateNewArray(rand_num_bars(10, 15));
});
function generateNewArray(rand_num_bars) {
bar_container.innerHTML = "";
//Inserting child bars into parent bar container, using rand_num function to generate # of bars
for (let i = 0; i < rand_num_bars; i++) {
document.getElementById(
"bar-container"
).innerHTML += `<div id = 'indiv_bar'></div>`;
}
//Randomizing the height for each child bar
for (i = 0; i < children.length; i++) {
var rand_height = rand_num_height(100, 500);
children[i].style.height = `${rand_height}px`;
//Setting values of each element in bar_con array to the current child height to use for sorting later
children[i].value = rand_height;
}
}
function disableBtn() {
//Prevent buttons from triggering an event
generate.style.pointerEvents = "none";
btn.style.pointerEvents = "none";
//Styling the elements to visually show user buttons are disabled
generate.style.color = "#FF0000";
btn.style.color = "#FF0000";
}
//Bubble Sort Algorithm
function bubbleSort(arr) {
const n = arr.length;
for (let i = 0; i < n; i++) {
for (let j = 0; j < n - i - 1; j++) {
anim(arr[j], arr[j].value, p1);
anim(arr[j + 1], arr[j + 1].value, p2);
if (arr[j].value > arr[j + 1].value) {
[arr[j].value, arr[j + 1].value] = [arr[j + 1].value, arr[j].value];
anim(arr[j], arr[j].value, p2);
anim(arr[j + 1], arr[j + 1].value, p1);
}
anim(arr[j], arr[j].value, p);
anim(arr[j + 1], arr[j + 1].value, p);
}
anim(arr[n - i - 1], arr[n - i - 1].value, sorted);
}
sortState = true;
c = 0;
}
//Quick Sort Algorithm
function partition(arr, low, high) {
let i = low;
let j = high;
pivotEl = arr[low].value;
do {
do {
i++;
} while (arr[i].value <= pivotEl);
do {
j--;
} while (arr[j].value > pivotEl);
if (i <= j) {
[arr[i].value, arr[j].value] = [arr[j].value, arr[i].value];
}
} while (i < j);
[arr[low].value, arr[j].value] = [arr[j].value, arr[low].value];
return j;
}
function quickSort(arr, low, high) {
var j;
if (low < high) {
j = partition(arr, low, high);
quickSort(arr, low, j - 1);
quickSort(arr, j + 1, high);
}
}
btn.addEventListener("click", () => {
disableBtn();
quickSort(children, 0, children.length - 1);
});
Hello thanks to moluapple, I got this script from the adobe support community, I'm a beginner in javascript but I have a task to make, I have to paint numbers in each color of the image, actually, I see that in this solution brings me numbers in each layer, but doesn't work for the colors, can someone has a similar solution?
Let me add the expected result which is for each color on the picture the script adds a number to the color 1 for green 2 for yellow etc, let me show you.enter image description here
here is the original link
https://community.adobe.com/t5/illustrator-discussions/script-insert-text-number-in-the-middle-of-visible-bounds-of-the-each-object/td-p/8088914/page/3
(function() {
var doc = app.activeDocument,
lays = doc.layers,
WORK_LAY = lays.add(),
NUM_LAY = lays.add(),
i = lays.length - 1,
lay;
// main working loop
for (; i > 1; i--) {
//process each layer
lay = lays[i];
lay.name = lay.name + " Num:" + (i - 1); // i-1 as 2 layers beed added.
process(lay.pathItems, false);
process(lay.compoundPathItems, true); // if any
}
//clean up
NUM_LAY.name = "Numbers";
WORK_LAY.remove();
function process(items, isCompound) {
var j = 0,
b, xy, s, p, op;
for (; j < items.length; j++) {
// process each pathItem
op = items[j];
// add stroke
if (isCompound) {
strokeComPath(op);
} else {
!op.closed && op.closed = true;
op.filled = false;
op.stroked = true;
};
b = getCenterBounds(op);
xy = [b[0] + (b[2] - b[0]) / 2, b[1] + (b[3] - b[1]) / 2];
s = (
Math.min(op.height, op.width) < 20 ||
(op.area && Math.abs(op.area) < 150)
) ? 4 : 6; // adjust font size for small area paths.
add_nums(i - 1, xy, s);
}
}
function getMinVisibleSize(b) {
var s = Math.min(b[2] - b[0], b[1] - b[3]);
return Math.abs(s);
}
function getGeometricCenter(p) {
var b = p.geometricBounds;
return [(b[0] + b[2]) / 2, (b[1] + b[3]) / 2];
}
// returns square of distance between p1 and p2
function getDist2(p1, p2) {
return Math.pow(p1[0] + p2[0], 2) + Math.pow(p1[1] + p2[1], 2);
}
// returns visibleBounds of a path in a compoundPath p
// which is closest to center of the original path op
function findBestBounds(op, p) {
var opc = getGeometricCenter(op);
var idx = 0,
d;
var minD = getDist2(opc, getGeometricCenter(p.pathItems[0]));
for (var i = 0, iEnd = p.pathItems.length; i < iEnd; i++) {
d = getDist2(opc, getGeometricCenter(p.pathItems[i]));
if (d < minD) {
minD = d;
idx = i;
}
}
return p.pathItems[idx].visibleBounds;
}
function applyOffset(op, checkBounds) {
var p = op.duplicate(WORK_LAY, ElementPlacement.PLACEATBEGINNING),
// offset value the small the better, but meantime more slow.
offset = function() {
var minsize = Math.min(p.width, p.height);
if (minsize >= 50) {
return '-1'
} else if (20 < minsize && minsize < 50) {
return '-0.5'
} else {
return '-0.2' // 0.2 * 2 (both side ) * 50 (Times) = 20
}
},
xmlstring = '<LiveEffect name="Adobe Offset Path"><Dict data="I jntp 2 R mlim 4 R ofst #offset"/></LiveEffect>'
.replace('#offset', offset()),
TIMES = 100; // if shapes are too large, should increase the value.
if (checkBounds) {
// check its size only if it needs, because it's too slow
while (TIMES-- && getMinVisibleSize(p.visibleBounds) > 3) p.applyEffect(xmlstring);
} else {
while (TIMES--) p.applyEffect(xmlstring);
}
return p;
}
function getCenterBounds(op) {
var originalMinSize = getMinVisibleSize(op.visibleBounds);
var p = applyOffset(op, false);
if (getMinVisibleSize(p.visibleBounds) > originalMinSize) {
// in some cases, path p becomes larger for some unknown reason
p.remove();
p = applyOffset(op, true);
}
var b = p.visibleBounds;
if (getMinVisibleSize(b) > 10) {
activeDocument.selection = [p];
executeMenuCommand("expandStyle");
p = activeDocument.selection[0];
if (p.typename == "CompoundPathItem") {
b = findBestBounds(op, p);
}
}
p.remove();
return b;
}
function add_nums(n, xy, s) {
var txt = NUM_LAY.textFrames.add();
txt.contents = n;
txt.textRange.justification = Justification.CENTER;
txt.textRange.characterAttributes.size = s;
txt.position = [xy[0] - txt.width / 2, xy[1] + txt.height / 2];
}
function strokeComPath(compoundPath) {
var p = compoundPath.pathItems,
l = p.length,
i = 0;
for (; i < l; i++) {
!p[i].closed && p[i].closed = true;
p[i].stroked = true;
p[i].filled = false;
};
}
})();
I don't understand what exactly you're trying to gain. So here is a guess:
If you change the function process() this way:
function process(items, isCompound) {
var j = 0,
b, xy, s, p, op;
for (; j < items.length; j++) {
// process each pathItem
op = items[j];
c = op.fillColor; // <--- here
color = 'CMYK ' + // <--- here
[ Math.round(c.cyan), // <--- here
Math.round(c.magenta), // <--- here
Math.round(c.yellow), // <--- here
Math.round(c.black) // <--- here
].join(','); // <--- here
// add stroke
if (isCompound) {
strokeComPath(op);
} else {
!op.closed && op.closed = true;
// op.filled = false; // <--- here
// op.stroked = true; // <--- here
};
b = getCenterBounds(op);
xy = [b[0] + (b[2] - b[0]) / 2, b[1] + (b[3] - b[1]) / 2];
s = (
Math.min(op.height, op.width) < 20 ||
(op.area && Math.abs(op.area) < 150)
) ? 4 : 6; // adjust font size for small area paths.
// add_nums(i - 1 + color, xy, s);
add_nums(color, xy, s); // <--- here
}
}
It will put CMYK percents inside the shapes instead of numbers.
Here is the another modification of the main function process(). It's turned out that it can be done if you add & modify just two lines:
function process(items, isCompound) {
var j = 0,
b, xy, s, p, op;
for (; j < items.length; j++) {
// process each pathItem
op = items[j];
try { color = op.fillColor.spot.name } catch(e) { continue } // <-- HERE
// add stroke
if (isCompound) {
strokeComPath(op);
} else {
!op.closed && op.closed = true;
op.filled = false;
op.stroked = true;
};
b = getCenterBounds(op);
xy = [b[0] + (b[2] - b[0]) / 2, b[1] + (b[3] - b[1]) / 2];
s = (
Math.min(op.height, op.width) < 20 ||
(op.area && Math.abs(op.area) < 150)
) ? 4 : 6; // adjust font size for small area paths.
add_nums(color, xy, s); // <--- HERE
}
}
And the colors should be Spot Global colors. The script put in the middle of every shape a name of the swatch color.
Input:
Output:
last stone weight 2 solution in cpp
This is able to pass all test cases.
class Solution {
public:
int lastStoneWeightII(vector<int>& stones) {
int n = stones.size();
int total = 0;
for(int i = 0; i < n; i++){
total += stones[i];
}
int req = total / 2;
vector <bool> dp(req + 1, false);
dp[0] = true;
int reach = 0;
for(int i = 0; i < n; i++){
for(int j = req; j - stones[i] >= 0; j--){
dp[j] = dp[j] || dp[j - stones[i]];
if(dp[j]) reach = max(reach, j);
}
}
return total - (2 * reach);
}
};
I tried to replicate it in javascript and not able to pass
a simple test cases like [2,7,4,1,8,1]
Here is my attempt
var lastStoneWeightII = function(st) {
// stone #
const n = st.length;
// sum up
const sum = st.reduce((acc, curr) => {return acc+curr});
// e.g. half
const ha = Math.floor(sum / 2);
// half+1
const dp = Array(ha+1).fill(false);
// 1st ele = true
dp[0] = true;
// store tmp_max
let max = 0;
// loop element
for(let i=0; i<n; i++) {
// single element
const w = n[i];
// backward, half
for(let j=ha; j-w>=0; j--) {
// update condi
dp[j] = dp[j] || dp[j-w];
// never comes in
if(dp[j]) {
//test
console.log('++++ max', max, 'j', j)
max = Math.max(max, j);
}
}
}
return (sum - max) - max;
}
I have an annoying script I can't complete.
I need 32 non-repeating numbers out of a possible 0-64 number set. Every time I try to create a loop to check the new random number against all the numbers in the array I end up with nothing, or an infinite loop.
I'm stumped :(
Try this:
var keys = [], numbers = [], x, total = 0;
while(total < 32) {
x = Math.floor(Math.random() * 64);
// way faster that looping through the array to check if it exists
if(keys[x] == undefined) {
keys[x] = 1;
numbers.push(x);
total++;
}
}
console.log(numbers);
Working Demo
This code will generate a non repeating random number between 0 and whatever number you give it and will start over when it has been called the amount of the number you give it.
Give it a try:
let randomNumber = function (max) {
let min = 0, prevIndexes = [];
function exec(max2) {
max = max || max2;
let result = Math.floor(Math.random() * (max - min + 1) + min);
if (prevIndexes) {
if (prevIndexes.length - 1 === max) {
clear();
}
let foundDouble, eqPrevInn = true;
while (eqPrevInn) {
foundDouble = false;
result = Math.floor(Math.random() * (max - min + 1) + min);
for (let i = 0, l = prevIndexes.length; i < l; i++) {
if (result === prevIndexes[i]) {
foundDouble = true;
break;
}
}
if (!foundDouble) {
eqPrevInn = false;
}
}
}
prevIndexes.push(result);
console.log(prevIndexes);
return result;
}
let clear = function () {
if (prevIndexes) {
prevIndexes = [];
// console.log('prevIndexes has been cleared');
}
else {
// console.log('already clear');
}
}
return {
exec: exec,
clear: clear
}
};
let random32 = randomNumber(32/*range*/).exec;
for (let i = 0; i <= 32; i++) {
random32();
}
I'm trying to make a bingo game for fun. I've looked in a lot of places for a unique generator but I can't seem to find one. I've tried to make my own,but once it actually hits a number that's the same it does an infinite loop. I've tried a simple code that in theory should work but for some reason things pass through. What can I do!?
var bc = [];
for (var i = 0; i < 5; i++) {
var r = Math.floor(Math.random()*20+1) + 0;
if(!(r in bc)){
bc.push(r);
}
else
{
i--;
}
}
____________________________________________
____________________________________________
____________________________________________
b1=0;
b2=0;
b3=0;
b4=0;
b5=0;
var bc = [b1,b2,b3,b4,b5]
var bnc = function(){
var n = Math.floor(Math.random() * 5+1)+0;
var n2 = Math.floor(Math.random() * 5+1)+0;
b1 = n;
var a1 = true;
var as = false;
while(a1){
var c = n;
if(c===b1||c===0 ||as!==false){
c = n2;
as=true;
}
if(c===b1||c===0&&as===true){
c = n;
as=false;
}
if(c!=b1){
b2 = c;
a1 = false;
a2 = true;
}
}
};
bnc();
console.log("new1");
console.log(b1,b2,b3,b4,b5);
//_______________________________________
var bnc2 = function(){
var n = Math.floor(Math.random() * 5+1)+0;
var n2 = Math.floor(Math.random() * 5+1)+0;
var a1 = true;
var as = false;
while(a1){
var c = n;
if(c===b1||c===b2||c===0&&as===false){
c = n2;
as=true;
}
if(c===b1||c===b2||c===0&&as===true){
c = n;
as=false;
}
if(c!=b1&&c!=b2){
b3 = c;
console.log("made it 1");
a1 = false;
}
}
};
bnc2();
console.log("new2");
console.log(b1,b2,b3,b4,b5);
once it actually hits a number that's the same
It never should. Such algorithms take longer the longer they run. You should take a different approach:
Put all possible numbers into a pool. Once you draw a number, remove it from the pool. Just like it's done in real life.
var pool = [1, 2, 3, 4, 5];
var getNumber = function () {
if (pool.length == 0) {
throw "No numbers left";
}
var index = Math.floor(pool.length * Math.random());
var drawn = pool.splice(index, 1);
return drawn[0];
};
I would rather do it with something like this:
http://jsfiddle.net/YC58s/
generate = function(length)
{
var arr = [];
var n;
for(var i=0; i<length; i++)
{
do
n = Math.floor(Math.random()*20+1);
while(arr.indexOf(n) !== -1)
arr[i] = n;
}
return arr;
}
This can handle generating upto 20 digit UNIQUE random number
JS
var generatedNumbers = [];
function generateRandomNumber(precision) { // precision --> number precision in integer
if (precision <= 20) {
var randomNum = Math.round(Math.random().toFixed(precision) * Math.pow(10, precision));
if (generatedNumbers.indexOf(randomNum) > -1) {
if (generatedNumbers.length == Math.pow(10, precision))
return "Generated all values with this precision";
return generateRandomNumber(precision);
} else {
generatedNumbers.push(randomNum);
return randomNum;
}
} else
return "Number Precision shoould not exceed 20";
}
generateRandomNumber(1);
JsFiddle
window.onload = unRanNumGen(20, 1, 12);
//above, we need 12 random numbers between 20 (included) and 1(included)
function unRanNumGen(max, min, limit){
//max = maximum number [inclued] (range of numbers)
//min = minimum number [included] (range of numbers)
//limit = number of random numbers (how many numbers do you want?)
var pool = [genRan(max, min)];
for(i=0; i<limit; i++){
for(n = 0; n <i; n++){
if(pool[n] !== genRan(max, min)){
pool.push(genRan(max, min));
break;
}
}
}
function genRan(max, min){
var genRan = Math.floor(Math.random() * (max - min) + min);
return genRan;
}
alert(pool.join('\n')); //to display the array of random numbers
}