mardi 1 décembre 2015

Need 3 outcomes from IF statment

I have a list of names in excel which have a random number next to them in brackets, the numbers are 1 to 3 digits long. I was using the formula

=IF(LEFT(RIGHT(B8,4),1)=("("),RIGHT(B8,3),RIGHT(B8,4)) to get rid of the first bracket and then 
=IF(RIGHT(LEFT(AX8,3),1)=")",LEFT(AX8,2),LEFT(AX8,3)) to remove the last bracket. 

This was working until I found a name with a 4 digit number in the brackets. Is there a way to add another outcome to the if statement?

comparing strings with isEqual isn't running the full function iOS

I have an annoying issue I'm trying to get around but its just not happening so either I'm missing something stupid or I'm doing it wrong.

basically id like to check a string and if its a no, then load blank strings, if its anything else then load the real strings.

here is my code.

 NSString* q1ynu = [defaults objectForKey:@"1aq1ynu"];
if ([q1ynu isEqualToString:@"No"]){
    NSString *q1text = @" ";
    NSString *q1lmh = @" ";
}else{
    NSString* q1lmh = [defaults objectForKey:@"1aq1lmh"];
    NSString* q1text = [defaults objectForKey:@"1aq1"];
}

I'm putting NSString *q1text = @" "; after implementation and before viewDidLoad but it does complain about the unused variable.

It was loading all 3 answers before regardless of the No check but now after playing its loading the first answer of No, or yes and nothing else?

Am i missing something or is this just not supposed to work? if not then what will work because I am at a loss?

Thanks all

Check raw_input for dictionary

I looked on stackoverflow to solve my problem but from all explanations about loops and checks I don't understand why my code isn't working. So I want to build a dictionary (totally new to Python btw) and I read that I can also check if the input is in the dicitonary module but that is actually not what I want to do here. I just want to see if the raw_input contains at least one number in the string (not if the string only contains numbers) and if the length of the input string is at least 2. If the input passes those checks it should move on (the rest of this dictionary will come later. For now I only want to understand what I did wrong with my check) Here's my code, help would be very much appreciated!

def check():
    if any(char.isdigit() for char in original):
        print ("Please avoid entering numbers. Try a word!")
        enter_word()
    elif len(original)<1:
        print ("Oops, you didn't enter anything. Try again!")
        enter_word()

    else:
        print ("Alright, trying to translate:")
        print ("%s") %(original)

def enter_word():
    original = raw_input("Enter a word:").lower()
    check()

enter_word()

How to make a 0 stay as a 0 in a matrix

I use the following code to generate a matrix

randomdiv <- function(nchrom, ndivs, size) {sz <- matrix(nrow = nchrom, ncol = ndivs) 

for (j in 1:nchrom) {
     n <- size
for (i in 1:ndivs)
    {
     old_subs <- rbinom (1, n, 0.5)  
     num_chrom <- rep(1/nchrom, nchrom)    
     new_subs <- rmultinom(1, size*nchrom/2, prob = c(num_chrom))
     m <- old_subs + new_subs        
     sz[j,i] <- m[1,1]
     n <- m
    }
   }
  return (sz)
 }

>randomdiv(3, 3, 10)
      [,1] [,2] [,3]
  [1,]   11   13   12
  [2,]    6    8    5
  [3,]   12   11    9

The only adjustment I need to make is that when a 0 is generated in the column by the rbinom function, I need that occurence to stay as a 0 for the remainder of the matrix, but anything >0 needs to go through the rest of the loop and have new_subs added to it.

I have tried;

randomdiv <- function(nchrom, ndivs, size, ncell) {sz <- matrix(nrow = nchrom, ncol = ndivs) 

for (j in 1:nchrom) {
     n <- size
for (i in 1:ndivs)
     {
      old_subs <- rbinom (1, n, 0.5)  
      num_chrom <- rep(1/nchrom, nchrom)    
      new_subs <- rmultinom(1, size*nchrom/2, prob = c(num_chrom))
      m <- ifelse(old_subs>0, old_subs + new_subs, old_subs+0)         
      sz[j,i] <- m[1,1]
      n <- m
     }
    }
   return (replicate(ncell, sz, simplify = FALSE))
  }
> randomdiv(3, 3, 10, 5)
#Error in m[1, 1] : incorrect number of dimensions

I've tried a few different tactics with the ifelse function, but I think it only treats the columns as a whole, so if there is a 0 at all, nothing happens for the whole column, whereas I need each value in the columns to be treated individually.

syntax error using if in a bash script

I want to modify an existing bash script to avoid asking input data from the usedr if any parameter is passed. now the part if the existing script is as follow and works fine :

options=("a" "b" "c"  "d"  "e")
select opt in "${options[@]}"

I'm changing with this:

options=("a" "b"  "c"  "d")
if [ $# = 0 ] ; then
        select opt in "${options[@]}"
else
        opt=$1
fi

When i run it (with or without parameter) i get the following error

/usr/local/sbin/script.sh: line 486: syntax error near unexpected token `else'
/usr/local/sbin/script.sh: line 486: `else'

Line 486 is the line with my else statement Any idea of what I'm doing wrong?

Dafny - Call methods inside if statemnts?

Like the title says I would like to call on a method that modifies some variables inside an if statement of another method, such as:

method A
...
{
    ... // Modifies some variables
}

method B
...
{
    ...
    if(statement){
        A();
    }
    ...
}

This doesn't work since Dafny won't allow non ghost methods to be called in such a manner. What would a workaround to this issue be?

lundi 30 novembre 2015

IF Statement Checking (Not Working Properly)

randomEmpty() returns a random coordinate on the n x n grid that is empty (Method works). randomAdjacent() uses randomEmpty() to select an EMPTY coordinate on the map. Comparisons are then made to see if this coordinate has an VALID adjacent coordinate that is NON-EMPTY. The PROBLEM is that randomAdjacent does not always return the coordinates of space with an adjacent NON-EMPTY space. It will always return valid coordinates but not the latter. I can't spot the problem. Can someone help me identify the problem?

public int[] randomEmpty()
{
    Random r = new Random();
    int[] random = new int[2];
    int row = r.nextInt(array.length);
    int column = r.nextInt(array.length);
    while(!(isEmpty(row,column)))
    {
        row = r.nextInt(array.length);
        column = r.nextInt(array.length);
    }
    random[0] = row+1;
    random[1] = column+1;
    return random;        
}

public int[] randomAdjacent()
{
    int[] adjacentToX = new int[8];
    int[] adjacentToY = new int[8];
    int[] adjacentFrom = randomEmpty();
    int count;
    boolean isTrue = false;
    boolean oneAdjacentNotEmpty = false;

    while(!(oneAdjacentNotEmpty))
    {
        count = 0;

        if(validIndex(adjacentFrom,1,-1))
        {
            adjacentToX[count] = adjacentFrom[0]+1;
            adjacentToY[count] = adjacentFrom[1]-1;
            count++;
        }
        if(validIndex(adjacentFrom,0,-1))
        {               
            adjacentToX[count] = adjacentFrom[0];
            adjacentToY[count] = adjacentFrom[1]-1;
            count++;
        }
        if(validIndex(adjacentFrom,-1,-1))
        {          
            adjacentToX[count] = adjacentFrom[0]-1;
            adjacentToY[count] = adjacentFrom[1]-1;
            count++;
        }
        if(validIndex(adjacentFrom,-1,0))
        {        
            adjacentToX[count] = adjacentFrom[0]-1;
            adjacentToY[count] = adjacentFrom[1];
            count++;
        }
        if(validIndex(adjacentFrom,-1,1))
        {       
            adjacentToX[count] = adjacentFrom[0]-1;
            adjacentToY[count] = adjacentFrom[1]+1;
            count++;
        }
        if(validIndex(adjacentFrom,0,1))
        {         
            adjacentToX[count] = adjacentFrom[0];
            adjacentToY[count] = adjacentFrom[1]+1;
            count++;
        }
        if(validIndex(adjacentFrom,1,1))
        {         
            adjacentToX[count] = adjacentFrom[0]+1;
            adjacentToY[count] = adjacentFrom[1]+1;
            count++;
        }
        if(validIndex(adjacentFrom,1,0))
        {        
            adjacentToX[count] = adjacentFrom[0]+1;
            adjacentToY[count] = adjacentFrom[1];
            count++;
        }
        for(int i = 0; i < count; i++)
        {
            if(!(isEmpty(adjacentToX[i],adjacentToY[i])))  
            {
                oneAdjacentNotEmpty = true;
                isTrue = true;
            }
        }
        if(isTrue)
            break;
        else
            adjacentFrom = randomEmpty();           
    }
    return adjacentFrom;
}

public boolean validIndex(int[] a,int i, int j)
{
    try
    {
        Pebble aPebble = array[a[0]+i][a[1]+j];
        return true;
    }
    catch(ArrayIndexOutOfBoundsException e)
    {
        return false;
    }
}
public void setCell(int xPos, int yPos, Pebble aPebble)
{
    array[xPos-1][yPos-1] = aPebble;
}

public Pebble getCell(int xPos, int yPos)
{
    return array[xPos-1][yPos-1];
}

JUNIT Test Performed:

@Test
public void testRandomAdjacent() {
    final int size = 5;
    final Board board2 = new Board(size);
    board2.setCell(1, 1, Pebble.O);
    board2.setCell(5, 5, Pebble.O);
    int[] idx = board2.randomAdjacent();
    int x = idx[0];
    int y = idx[1];
    boolean empty = true;
    for (int i = x - 1; i <= x + 1; i++) {
        for (int j = y - 1; j <= y + 1; j++) {
            if ((i == x && j == y) || i < 1 || j < 1 || i > size || j > size) {
                continue;
            }
            if (board2.getCell(i, j) != Pebble.EMPTY)
                empty = false;
        }

    }
    assertFalse(empty);// NEVER gets SET TO FALSE
    assertEquals(Pebble.EMPTY, board2.getCell(x, y));
}