Although I've seen similar question's nothing quite answers why this doesn't work, and I'm unaware of an alternative.
I'm making a very simple calculator and when pulling the expression from the string I need to replace symbols such as '×' and '÷' with operators recognized by the eval.
Currently I'm trying to work through the string one character at a time and copy it into a new string, replacing where necessary. It seems that none of the if statements checking for characters in the string are ever called and I dont know why.
for (var i = 0; i < (expressionPre.length) ; i++) {
alert(expressionPre[i]);
if (expressionPre[i] == "÷") {
expressionPost += "/";
} else if (expressionPre[i] === '×') {
expressionPost += "*";
alert("Finally!");
} else if (expressionPre[i] == "−") {
expressionPost += "-";
} else if (expressionPre[i] % 1 == 0) {
expressionPost += expressionPre[i];
}
alert(expressionPost[i]);
}
as #beaver say, you should use the replace function directly.
this is a function who replace all occurence of text with another one
function tools_replaceAll(str, find, replace) {
return str.replace(new RegExp(find, 'g'), replace);
}
var str = "(1 ÷ 2 ÷ 2) × 3 × 3 − 4− 4 + 5 + 5";
str = tools_replaceAll(str, "÷" , "/" ) ;
str = tools_replaceAll(str, "×" , "*" ) ;
str = tools_replaceAll(str, "-" , "-" ) ;
alert( str ) ;
Related
Hy, I have misunderstanding with this code
By the task I should write a function to find the longest common prefix string amongst an array of strings.
If there is no common prefix, return an empty string "".
So my soluthion :
def longestCommonPrefix(strs: Array[String]): String = {
val size = strs.length
if (size == 0) {
" "
} else {
val j = strs.sortWith(_.length < _.length)
val minStr = Math.min(j(0).length, j(size - 1).length)
var i: Int = 0
while (i < minStr && j(0).take(i) == j(size - 1).take(i))
i=i+1
val pre = j(0).substring(0, i-1)
pre
}
}
Example: val name = Array("flower","flow","flight")
print(longestCommonPrefix(name))
output: fl
And it's correct , but when I put Array("") I have en error
String index out of range: -1
why this condition isn't work ?
if (size == 0) { " "}
I want to make the queue list only show 10 songs at a time, because right now the bot crashes and says that every embed field can only have 1024 characters.
I've put the most important part below, you can find the rest here.
exports.playQueue = (guildId, channel) => {
if (!guilds[guildId] || !guilds[guildId].nowPlaying) {
var embed = new Discord.RichEmbed()
.setColor(9955331)
.setDescription(":mute: Not Playing");
channel.send(embed);
return;
}
var g = guilds[guildId];
var q = "";
var i = 1;
let ytBaseUrl = "https://www.youtube.com/watch?v=";
g.playQueue.forEach((song) => {
let ytLink = ytBaseUrl + song.id;
let title = song.title;
if (title.length > 30) title = title.substring(0, 19) + "... ";
q += "`" + i++ + "`. ";
q += `[${title}](${ytLink}) | `;
q += "`" + song.length + "`\n";
});
let currSong = g.nowPlaying.title;
if (currSong.length > 30) currSong = currSong.substring(0, 19) + "... ";
var cs = `[${currSong}](${ytBaseUrl+g.nowPlaying.id}) | `;
cs += "`" + g.nowPlaying.length + "`";
var embed = new Discord.RichEmbed()
.setColor(9955331)
.addField(":musical_note: Now Playing", cs);
if (g.loop) embed.setFooter("🔁 Looping playlist");
if (q != "") embed.addField(":notes: Play Queue", q);
channel.send(embed);
}
I would solve the problem by building a queue that goes from the first to the tenth song
// I chose a for loop just because I can break out of it
// This goes on until it reaches the end of the queue or the tenth song, whichever comes first
for (let i = 0; i < g.playQueue.length && i < 9; i++) {
let song = g.playQueue[i];
// This is your part
let ytLink = ytBaseUrl + song.id;
let title = song.title;
if (title.length > 30) title = title.substring(0, 19) + "... ";
// Instead of directly adding the next line to q, I store it in another variable
let newline = "";
newline += "`" + (i+1) + "`. ";
newline += `[${title}](${ytLink}) | `;
newline += "`" + song.length + "`\n";
// If the sum of the two lengths doesn't exceed the 1024 chars limit, I add them together
// If it is too long, I don't add it and exit the loop
if (q.length + newline.length > 1024) break;
else q += newline;
}
This should fix it, since q should not exceed 1024 characters. This is a simple but effective solution in my opinion.
Feel free to let me know if something doesn't work properly ;)
Book has page with the ff code to convert Centigrade to Fahrenheit, we've been asked to rewrite/simplify it.
function convertToCentigrade(degFahren)
{
var degCent;
degCent = 5/9 * (degFahren - 32);
return degCent;
}
var degFahren = new Array(212, 32, -459.15);
var degCent = new Array();
var loopCounter;
for (loopCounter = 0; loopCounter <= 2; loopCounter++)
{
degCent[loopCounter] = convertToCentigrade(degFahren[loopCounter]);
}
for (loopCounter = 2; loopCounter >= 0; loopCounter-- )
{
document.write(“Value “ + loopCounter + “ was “ +
degFahren[loopCounter] + “ degrees Fahrenheit”);
document.write(“ which is “ + degCent[loopCounter] +
“ degrees centigrade<br />”);
}
My version:
var degFar = [212, 32, -459.15];
var degCent = [];
function convert(input) {
result = (5/9 * (input - 32));
return result;
}
for (i = 0; j = degFar.length; i <= j; i++) {
degCent.push(convert(degFar[i]));
document.write(degCent[i]);
}
I pulling an error (obviously), but I don't understand what I'm doing wrong.
degFar has 3 elements but its index starts at 0.
Your array is like this:
[0] 212
[1] 32
[2] -459.15
You're trying to push an index [3] that doesn't exists. So modify your loop with this, notice I replaced i<=j for i<j:
for (i = 0; j = degFar.length; i < j; i++) {
degCent.push(convert(degFar[i]));
document.write(degCent[i]);
}
Your for loop is causing the error. You try to use two variables, 'j' and 'i'. I'm not sure what you are trying to accomplish by using 'j' (on top of that you never declared 'j' before trying to initialize it to degFar.length).
Keeping with your logic, I would get rid of 'j'-- you don't need it. After removing 'j' and using 'i' it should look something like this:
for (i = 0; i < degFar.length; i++) {
degCent.push(convert(degFar[i]));
document.write(degCent[i] + "<br>");
}
Hope this helps.
I'm using regex in C where I'm checking a word against a list of regex, below is what I have,
I have this string
0118889994444
and I have these regexes
^012[0-9]{10}$ if this one hits then do 1
^0011[0-9]{10}$ if this one hits then do 2
^00[0-9]{10}$ if if this one hits then do 3
^11[0-9]{10}$ if this one hits then do 4
^011[0-9]{10}$ if this one hits then do 5 // this one will match the string
What I'm currently doing is looping through the regex list and see which one will hit and then do whatever is set for that regex, so, the bigger the list the more time it takes to finish the loop, is there a way or a trick to make this faster and more intelligent :) ?
In the case above I would drop regex altogether, and go for a straightforward approach of checking the prefix against a fixed list, followed by the detection that the rest of the string is composed of ten digit. You can do it like this:
struct mathc_def {
const char *prefix;
int offset;
} match_defs[] = {
{.prefix = "012", .offset = 3}
, {.prefix = "0011", .offset = 4}
, {.prefix = "00", .offset = 2}
, {.prefix = "11", .offset = 2}
, {.prefix = "011", .offset = 3}
};
bool ten_digits(const char* str) {
int i = 0;
while (isdigit(str[i])) {
i++;
}
return i == 10;
}
char *str = "0118889994444";
for (int i = 0 ; i != 5 ; i++) {
if (strstr(str, match_defs[i].prefix) == str && ten_digits(&str[match_defs[i].offset])) {
printf("Item %d matched.\n", i);
}
}
Not sure if it will be the fastest approach, but you could convert the (decimal) string into a 64 bit long and check the value divided by 1e10. Apart from that, check the length of the string to verify the leading zeroes.
This will of course only work as long as the characters are in the [0-9] range.
Example, using uintmax_t as integer type:
uintmax_t val,prefix;
char *endp=NULL;
int len, prefixlen;
printf("sizeof val: %lu\n",sizeof(val));
val = strtoumax(argv[1],&endp,10);
prefix = val / 1e10;
len = endp - argv[1];
prefixlen = len - 10;
printf("val=%ju, len=%u\n",val,len);
printf("prefix=%ju, len=%u\n",prefix,prefixlen);
switch ( prefixlen )
{
case 2:
if ( prefix == 0 ) ; // do 3
if ( prefix == 11 ) ; // do 4
break;
case 3:
if ( prefix == 12 ) ; // do 1
if ( prefix == 11 ) ; // do 5
break;
case 4:
if ( prefix == 11 ) ; // do 2
break;
}
This is probably fast compared to any solution comparing actual strings (just one loop to parse the number), but hard to maintain or expand to non-decimal strings or values exceeding 2^64.
I am writing a program that is due tonight at midnight, and I am utterly stuck. The program is written in C, and takes input from the user in the form SOS where S = a string of characters, O = an operator (I.E. '+', '-', '*', '/'). The example input and output in the book is the following:
Input> abc+aab
Output: abc + aab => bce
And that's literally, not variable. Like, a + a must = b.
What is the code to do this operation? I will post the code I have so far, however all it does is take the input and divide it between each part.
#include <stdio.h>
#include <string.h>
int main() {
system("clear");
char in[20], s1[10], s2[10], o[2], ans[15];
while(1) {
printf("\nInput> ");
scanf("%s", in);
if (in[0] == 'q' && in[1] == 'u' && in[2] == 'i' && in[3] == 't') {
system("clear");
return 0;
}
int i, hold, breakNum;
for (i = 0; i < 20; i++) {
if (in[i] == '+' || in[i] == '-' || in[i] == '/' || in[i] == '*') {
hold = i;
}
if (in[i] == '\0') {
breakNum = i;
}
}
int j;
for (j = 0; j < hold; j++) {
s1[j] = in[j];
}
s1[hold] = '\0';
o[0] = in[hold];
o[1] = '\0';
int k;
int l = 0;
for (k = (hold + 1); k < breakNum; k++) {
s2[l] = in[k];
l++;
}
s2[breakNum] = '\0';
printf("%s %s %s =>\n", s1, o, s2);
}
}
Since this is homework, let's focus on how to solve this, rather than providing a bunch of code which I suspect your instructor would frown upon.
First, don't do everything from within the main() function. Break it up into smaller functions each of which do part of the task.
Second, break the task into its component pieces and write out the pseudocode:
while ( 1 )
{
// read input "abc + def"
// convert input into tokens "abc", "+", "def"
// evaluate tokens 1 and 3 as operands ("abc" -> 123, "def" -> 456)
// perform the operation indicated by token 2
// format the result as a series of characters (579 -> "egi")
}
Finally, write each of the functions. Of course, if you stumble upon roadblocks along the way, be sure to come back to ask your specific questions.
Based on your examples, it appears “a” acts like 1, “b” acts like 2, and so on. Given this, you can perform the arithmetic on individual characters like this:
// Map character from first string to an integer.
int c1 = s1[j] - 'a' + 1;
// Map character from second string to an integer.
int c2 = s2[j] - 'a' + 1;
// Perform operation.
int result = c1 + c2;
// Map result to a character.
char c = result - 1 + 'a';
There are some things you have to add to this:
You have to put this in a loop, to do it for each character in the strings.
You have to vary the operation according to the operator specified in the input.
You have to do something with each result, likely printing it.
You have to do something about results that extended beyond the alphabet, like “y+y”, “a-b”, or “a/b”.
If we assume, from your example answer, that a is going to be the representation of 1, then you can find the representation values of all the other values and subtract the value representation of a from it.
for (i = 0; i < str_len; i++) {
int s1Int = (int)s1[i];
int s2Int = (int)s1[i];
int addAmount = 1 + abs((int)'a' - s2Int);
output[i] = (char)(s1Int + addAmount)
}
Steps
1) For the length of the s1 or s2
2) Retrieve the decimal value of the first char
3) Retrieve the decimal value of the second char
4) Find the difference between the letter a (97) and the second char + 1 <-- assuming a is the representation of 1
5) Add the difference to the s1 char and convert the decimal representation back to a character.
Example 1:
if S1 char is a, S2 char is b:
s1Int = 97
s2Int = 98
addAmount = abs((int)'a' - s2Int)) = 1 + abs(97 - 98) = 2
output = s1Int + addAmount = 97 + 2 = 99 = c
Example 2:
if S1 char is c, S2 char is a:
s1Int = 99
s2Int = 97
addAmount = abs((int)'a' - s2Int)) = 1 + abs(97 - 97) = 1
output = s1Int + addAmount = 99 + 1 = 100 = d