In p5.js, I could define a variable as:
var a = round(random(-1, 1))
And this will randomly output -1, 0, 1. Making it very likely to get 0.
What would be a better way to define a variable that only output values -1 or 1?
You could just use an if statement. Something like this:
var a;
if(random() < .5){
a = -1;
}
else{
a = 1;
}
Here's your answer in one line. I disagree with the accepted answer, you shouldn't define your own functions for something so simple.
var a = (random() < .5)?-1:1;
Define your own random function
function getRandomNumber(){
var a=random(-1,1);
if(a>0)return 1;
else return -1;
}
Related
Is there a way that a function has 2 options of return and the option of return is chosen after a certain interval of iterations?
example:
a function that swaps from "a" to "b" and "b" to "a" after 4 iterations returns:
a
a
a
a
b
b
b
b
a
a
a
a
b
b
b
b
.
.
.
Edit I did something like this to solve the problem:
var counter = 0;
var state = true;
var changeState = function(){
var x = 0
while(x != 12){
if(counter == 4){
counter = 0;
state = !state;
}
if (state){
console.log("a");
} else {
console.log("b")
}
counter += 1;
x += 1
}
}
changeState();
You will need to have a stateful function, as it needs to somehow remember something from previous call(s) that were made to it. This is a so-called side effect, and means that the function is not pure.
For the example you have given, the function would need to know (i.e. have a state with) the number of previous calls (modulo 8), or the previous four returned values, or some mix of this information.
How such a function is implemented, depends on the programming language.
In object oriented programming languages you would create a class with the function as method, and a property reflecting that state. When the function is called, it also updates the state. For instance, in Java:
class MyClass {
int callCount = 0;
char myFunction() {
return "aaaabbbb".charAt(this.callCount++ % 8);
}
}
You would call the function repeatedly like so:
MyClass obj = new MyClass();
for (int i = 0; i < 10; i++) {
System.out.println(obj.myFunction());
}
In JavaScript you could do the same, or you could create a closure:
function createFunction() {
let callCount = 0;
return function myFunction() {
return "aaaabbbb"[callCount++ % 8];
}
}
let myFunction = createFunction();
for (let i = 0; i < 10; i++) {
console.log(myFunction());
}
In Python you can do the same, but it allows also to use default arguments (which are only initialised at function definition time), and so you could define an argument that is an object holding a counter:
def myFunction(counter=[0]):
counter[0] += 1
return "aaaabbbb"[counter[0] % 8]
for _ in range(10):
print(myFunction())
This is of course not an exhaustive list of possibilities, but the essence is that programming languages offer their own ways to construct such stateful functions.
Iterators
Some languages offer a different approach: iterators. This means the function produces a stream of return values. The function can run to produce the first value after which the running state is saved until a new value is requested from it. The function's execution context is then restored to run until it can produce the next value, ...etc.
Here is how that design would look in JavaScript:
function * myIterator() {
let callCount = 0;
while (true) {
yield "aaaabbbb"[callCount++ % 8];
// ^^^^^ a language construct for yielding back to the caller
}
}
let iter = myIterator();
for (let i = 0; i < 10; i++) {
console.log(iter.next().value);
}
When a programming language offers this possibility, it is often preferred over the other alternatives listed earlier.
I have some problems with recursion and to understand it I'm trying to make up questions for myself and solve them. This particular question has gotten me confused:
consider this as an input in the form of a string:
[[a,b,c],[[d]],[[e,f]],[g],h,i,[[j,[k,l]]]]
the goal is to find the total number of things in the lists and the lists them self.for this example the result would be:12+10 = 22
note that the input is not an array,it is a string.Also instead of a,b,...
anything can be used,like numbers,strings etc.
[12345,0.34,["afv",24]]
This is my idea but I will mention why I cant implement it:
We write a function that starts iterating the string.It should count the total thing between [ and ].whenever the function reaches a [ it will recall itself to iterate through the remaining string.This way it can go deeper into the arrays.
These are my problems:
I don't know whether my idea is correct or not.
If my idea is correct,what is the base case.
How can I make sure that it counts all the things inside regardless of in what are they?(I mean how can I make sure it treats numbers,strings etc the same)
I think the body of the function should look like this(I'm using java here but I don't think the language is very important here):
public static int counter(String a){
int sum = 0;
//some code to iterate the string
//some code to check the conditions and if needed call the method
//some code to add the number of objects and arrays to sum
return sum;
}
If the code should like what I said then how can I fill the body?
Thank you for your time.
Depending how you design your recursive algorithm and size of input, you may run into the common problem of recursive stack overflow, where you have very deep recursion and run out of memory space
This is a different iterative pythonic solution if you do not have to use recursion but you should be able to transpose this to Java.
You want to increment you count for every item that is separated by commas. However, if that element has ']' characters, you know that it is a part of a embedded list. By counting the closing braces and the element, you can get the total.
Updated to handle strings with embedded commas
# Function for removing the chars between apostrophes
def remove(s,c):
while(s.find(c) != -1):
i = s.find(c) # find the first instance of c but ' or " in our case
i2 = s.find(c,i+1) # find the second instance
s = s[0:i]+s[i2+1:] # Remove the string
return s
return s
s = "[['a,b,c'],[1,2,3]]"
s = s[:-1] # remove the last list char
total = 0
s = remove(s,'\'')
s = remove(s,'"')
l = s.split(',')
for el in l:
total+=1
total+= el.count(']')
print(total)
Since you don't care about parsing the actual contents of the lists (for that you would implement a recursive descent parser), you can instead implement a simple state machine.
Here's a very rough, partial implementation in pseudo code just to give you some idea about how you might implement this. Ideally you would have more states to detect syntax errors:
int lists, elements = 0;
state = normal;
foreach (char c in input)
{
switch state
case normal:
if (c == '[')
lists++;
else if (c == ']')
// do nothing
else if (c == ',')
// do nothing (will only count [ and , on elements)
else if (c == '"')
elements++;
state = quoted_element
else
elements++;
state = element;
break;
case quoted_element:
if (c == '"')
state = element;
break;
case element:
if (c == '"' || c == '[')
exception("Syntax error");
else if (c == ",")
elements++;
else if (c == "]")
state = normal;
break;
}
Here's a recursion in JavaScript that might give you some ideas.
function f(s){
function nextIndexafterStr(i){
while (!(s[i] == "\"" && s[i-1] != "\\"))
i++;
return i + 1;
}
function nextIndexafterNum(i){
while (![",", "]"].includes(s[i]))
i++;
return i;
}
// Returns [numArrays, numElements, endIndex]
// Assumes valid input
function g(i, as, es){
// base case
if (s[i] == "]" || i == s.length)
return [as, es, i];
if (s[i] == ",")
return g(i + 1, as, es);
// a list
if (s[i] == "["){
const [aas, ees, endIndex] = g(i + 1, 0, 0);
return g(endIndex + 1, as + 1 + aas, es + ees);
}
// string element
if (s[i] == "\"")
return g(nextIndexafterStr(i + 1), as, es + 1);
// number or variable-name element
return g(nextIndexafterNum(i), as, es + 1);
}
const [as, es, _] = g(0, 0, 0);
return as + es;
}
var a = [12345,0.34,["af\"v",24]];
var b = "[[a,b,c],[[d]],[[e,f]],[g],h,i,[[j,[k,l]]]]";
a = JSON.stringify(a);
console.log(a);
console.log(f(a));
console.log(b);
console.log(f(b));
My question seams to be quite easy but currently I am not seeing the wood for the trees.
I've written code in swift 2 using a for-loop with two counter like:
for var i = 0, j = 1; i < 5; i++, j++ {
code...
}
but, with swift 3 this become deprecated.
I mean with one variable it's clear:
for i in 0 ..< endcondition {
code...
}
but how would the code with a for-loop looks like in swift 3 with two counter, without interlacing two for-loop?
Thanks in advance
Stefan
In this particular case
for i in 0..<5 {
let j = i + 1
print(i, j)
}
var i:Int = 0
var j:Int = 1
for each in 0...arrayCount -1{
//do stuff
/// place increments in closures as needed
j += 1
i += 1
}
You may want to consider on while loop to allow usage of evaluating multiple values to signal a stop.
while condition {
statements
Change condition
}
how to reverse a number?
Example1: x = 123, return 321
Example2: x = -123, return -321
this is my answer:
public int reverse(int x) {
int result = 0;
while(x != 0){
result = result * 10 + x % 10;
x = x / 10;
}
return result;
}
but when I input 1534236469 , it will output 1056389759 , this is wrong. what do you think about my program? thanks.
One reason your program cannot give the right answer is that you
store result in an int but you expect to be able to
reverse the number 1534236469.
The correct answer would be 9646324351,
but that number is greater than the largest possible value of an int
so you end up with something else.
Try long long or try using input with no more than 9 digits.
Followup:
I suggested long long because that will fairly reliably give you
an 8-byte integer. You may also get 8 bytes in a long, depending on
where you are building your code,
but Visual C++ on 32-bit Windows (for example) will
give you only 4 bytes. Possibly the 4-byte long will go the way of the 2-byte int soon enough, but at this point in time some of us still have to deal with it.
Jason,
You should just change the type from int to long.
public long reverse(long x)
{
long result = 0;
while (x != 0)
{
result = result * 10 + x % 10;
x = x / 10;
}
return result;
}
You can write x >0 (doesn't matter though )also after that you have to consider negative numbers , I made that change to your logic as follows (Also use long long to avoid overflow):
long long reverse(long long x)
{
int sign = 1;
long long ans=0;
if(x < 0)
sign = -1;
x = abs(x);
while(x > 0)
{
ans *= 10;
ans += x%10;
x /=10;
}
return ans*sign;
}
How about convert to string and reverse? Quite simple:
int reverseDigits(int x) {
String s = Integer.toString(x);
for (int i = 0; i < s.length() / 2; i++) {
char t = s[i];
s[i] = s[s.length() - i - 1];
s[s.length() - i - 1] = t;
}
return Integer.parseInteger(s); // subject to overflow
}
can use long type to store the result
public int reverse(int x) {
long result = 0;
while (x != 0) {
result = result * 10 + x % 10;
x /= 10;
}
if (result > Integer.MAX_VALUE || result < Integer.MIN_VALUE)
return 0;
return (int)result;
}
This is a question posted on Leetcode and it gives a wrong answer expecting a 0. The clue is that before returning the reversed integer we have to check if it does not exceed the limit of a 32-bit int ie 2^31-1.
Code in Python 3:
class Solution:
def reverse(self, x: int) -> int:
s=[]
rev=0
neg=False
if x==0:
return 0
if x<0:
x=x* -1
neg=True
while x:
s.append(x%10)
x=int(x/10)
i=len(s)
j=0
while i:
rev=rev+s[j]*10**(i-1)
i=i-1
j=j+1
if(rev>2**31-1):
return 0
return rev * -1 if neg else rev
You are using int for storing the number whereas number is out of range of int. You have tagged algorithm in this question. So, better way would be by using link list. You can google more about it. There are lot of algorithms for reversing a link list.
Why not simply do:
while (x)
print x%10
x /= 10
with a double sign conversion if the value of x is originally negative, to avoid the question of what mod a -ve number is.
A shorter version of Schultz9999's answer:
int reverseDigits(int x) {
String s = Integer.toString(x);
s=new StringBuilder(s).reverse().toString();
return Integer.parseInt(s);
}
Here is the python code of reverse number::
n=int(input('Enter the number:'))
r=0
while (n!=0):
remainder=n%10
r=remainder+(r*10)
n=n//10
print('Reverse order is %d'%r)
A compact Python solution is
reverse = int(str(number)[::-1])
If negative numbers are a possibility, then
num = abs(number) # absolute value of the number
rev = int(str(num)[::-1]) # reverse the number
reverse = -rev # negate the reverse
In JS I wrote it in this way
function reverseNumber(n) {
const reversed = n
.toString()
.split('')
.reverse()
.join('');
return parseInt(reversed) * Math.sign(n);
}
Reverse Integer In JavaScript | Accepted LeetCode solution | Memory efficient
If reversing the number causes the value to go outside the signed 32-bit integer range [-2^31, 2^31 - 1], then returned 0.
Intuition:
First converted the integer to a string which is much easy to reverse and check characters.
Approach:
Converted number to string.
Checked for 1st character negative value.
Spliced (-) and stored if any which is concat in the last.
Then reversed the string without (-).
var reverse = function(x) {
x= x.toString();
let s = Number(x[0]) ? '' : x[0],reverse='';
if(s) { //If x= -123 && here s='-'
x =x.substring(1) // removing '-' from the string
}
for(let i = x.length-1; i>=0; i--) {
if((Number(x[i]) && !reverse) || reverse){
reverse += x[i];
}
}
if(Number(s+reverse) > 2147483648 || (Number(s+reverse) < -2147483648 && Number(s+reverse) < 0)){
return 0
}
return Number(s+reverse); // s='-' or ''
};
I'm a jscript newbie and I've a problem.
I'm writing a script to validate an IBAN bank account number in Belgium. I need to replace some letters by their position in a searchstring and afterwards I convert this string into a number to take the modulo 97 test.
The first part goes well, but afterwards with the conversion from string to number, 10 is added to my number. I don't know what I'm doing wrong.
function checkIBAN()
{
var iban = crmForm.all.fp_iban.DataValue;
if (iban != null)
{
iban = iban.substring(4) + iban.substring(0, 4);
iban = iban.toUpperCase();
var searchString = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var pos;
var tmp = '';
for (x = 0; x < iban.length; x++) {
pos = searchString.search(RegExp(iban.charAt(x),'i'));
if (pos == -1)
return false;
else
tmp += pos.toString();
}
alert(tmp); // Here my value is 735320036532111490
var nr =parseInt(tmp);
alert(nr); // Now my value seems to be 735320036532111500
alert(nr % 97);
if (nr % 97 != 1)
{
alert('IBAN number is not correct !');
}
}
}
Yes, 735320036532111490 is simply too great a value to store in an int. It'll always be rounded:
alert(735320036532111490 / 10);
// alerts 73532003653211150
Here's a solution that might work for you.
Always specify the radix when using parseInt.
var nr =parseInt(tmp, 10);
For reference information: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt