سؤال

I have an array (array1) that is 19 bits long initialized to 0 and another array (clave) that is 64 bits long. I want to iterate over array1 64 times while clave is also been checked. I did this:

def fase2
    j=0
    for i in 0..63
        @array1[j]=@array1[18].to_i^@array1[17].to_i^@array1[16].to_i^@array1[13].to_i^@clave[i].to_i
    j=j+1
    if j>19  
        j=0  
    end  
    end
    print @array1
    gets
end

is there a cleaner way to do this...?

هل كانت مفيدة؟

المحلول

I can think of a few improvements.

  1. Call all of your variable names something more meaningful. What is in @array1? Integers? consider calling it @ints. Its good to call arrays a plural name. Same goes for j and i if possible.

  2. Use (0..63).each do |i| instead of for i in 0..63. More ruby-like

  3. Use spacing between operators, especially equals. j = 0 not j=0

  4. Small conditionals can go on one line: j = 0 if j > 19

  5. Why the magic numbers? Why are 18, 17, 16, and 13 special? Put them in an appropriately named array to start, and then use Array#reduce like so

    special_indeces = [18, 17, 16, 13]
    
    ... and then in loop ...
    
    xor = special_indeces.reduce do |val, index|
      val ^ @array1[index].to_i
    end
    
  6. What is with gets at the end? What is the point of that?

Good luck, that code needs serious work.

نصائح أخرى

This is untested, but it's more how I'd write the inner loops:

def fase2
  @clave.each do |clave|
    (0..19).each do |j|
      @array1[j] = @array1[18].to_i ^ @array1[17].to_i ^ @array1[16].to_i ^ @array1[13].to_i ^ clave.to_i
    end
  end
  print @array1
  gets
end
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top