Главная » Просмотр файлов » Arndt - Algorithms for Programmers

Arndt - Algorithms for Programmers (523138), страница 30

Файл №523138 Arndt - Algorithms for Programmers (Arndt - Algorithms for Programmers) 30 страницаArndt - Algorithms for Programmers (523138) страница 302013-09-15СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 30)

SOME BIT WIZARDRY8.12174The Gray code of a wordCan easily be computed bystatic inline ulong gray_code(ulong x)// Return the Gray code of x// (’bitwise derivative modulo 2’){return x ^ (x>>1);}The inverse is slightly more expensive. The straight forward idea is to usestatic inline ulong inverse_gray_code(ulong x)// inverse of gray_code(){// VERSION 1 (integration modulo 2):ulong h=1, r=0;do{if ( x & 1 ) r^=h;x >>= 1;h = (h<<1)+1;}while ( x!=0 );return r;}which can be improved to// VERSION 2 (apply graycode BITS_PER_LONG-1 times):ulong r = BITS_PER_LONG;while ( --r ) x ^= x>>1;return x;while the best way to do it is// VERSION 3 (use: gray ** BITSPERLONG == id):x ^= x>>1; // gray ** 1x ^= x>>2; // gray ** 2x ^= x>>4; // gray ** 4x ^= x>>8; // gray ** 8x ^= x>>16; // gray ** 16// here: x = gray**31(input)// note: the statements can be reordered at will#if BITS_PER_LONG >= 64x ^= x>>32; // for 64bit words#endifreturn x;Related to the inverse Gray code is the parity of a word (that is: bit-count modulo two).

The inverseGray code of a word contains at each bit position the parity of all bits of the input left from it (includingitself).static inline ulong parity(ulong x)// return 1 if the number of set bits is even, else 0{return inverse_gray_code(x) & 1;}Be warned that the parity bit of many CPUs is the complement of the above. With the x86-architecturethe parity bit also takes in account only the lowest byte, therefore:static inline ulong asm_parity(ulong x){x ^= (x>>16);x ^= (x>>8);asm ("addl $0, %0 \n""setnp %%al\n"CHAPTER 8. SOME BIT WIZARDRY}"movzx %%al, %0": "=r" (x) : "0" (x) : "eax");return x;Cf. [FXT: file auxbit/bitasm.h]The functionstatic inline ulong grs_negative_q(ulong x)// Return whether the Golay-Rudin-Shapiro sequence// (A020985) is negative for index x// returns 1 for x =// 3,6,11,12,13,15,19,22,24,25,26,30,35,38,43,44,45,47,48,49,// 50,52,53,55,59,60,61,63,67,70,75,76,77,79,83,86,88,89,90,94,// 96,97,98,100,101,103,104,105,106,110,115,118,120,121,122,// 126,131,134,139,140, ...//// algorithm: count bit pairs modulo 2//{return parity( x & (x>>1) );}proves to be useful in specialized versions of the fast Fourier- and Walsh transform.A byte-wise Gray code can be computed usingstatic inline ulong byte_gray_code(ulong x)// Return the Gray code of bytes in parallel{return x ^ ((x & 0xfefefefe)>>1);}Its inverse isstatic inline ulong byte_inverse_gray_code(ulong x)// Return the inverse Gray code of bytes in parallel{x ^= ((x & 0xfefefefe)>>1);x ^= ((x & 0xfcfcfcfc)>>2);x ^= ((x & 0xf0f0f0f0)>>4);return x;}Therebystatic inline ulong byte_parity(ulong x)// Return the parities of bytes in parallel{return byte_inverse_gray_code(x) & 0x01010101;}The Gray code related functions can be found in [FXT: file auxbit/graycode.h].Similar to the Gray code and its inverse is thestatic inline ulong green_code(ulong x)// Return the green code of x// (’bitwise derivative modulo 2 towards high bits’)//// green_code(x) == revbin(gray_code(revbin(x))){return x ^ (x<<1);}andstatic inline ulong inverse_green_code(ulong x)// inverse of green_code()175CHAPTER 8.

SOME BIT WIZARDRY176// note: the returned value contains at each bit position// the parity of all bits of the input right from it (incl. itself){// use: green ** BITSPERLONG == id:x ^= x<<1; // green ** 1x ^= x<<2; // green ** 2x ^= x<<4; // green ** 4x ^= x<<8; // green ** 8x ^= x<<16; // green ** 16// here: x = green**31(input)// note: the statements can be reordered at will#if BITS_PER_LONG >= 64x ^= x<<32; // for 64bit words#endifreturn x;}Both can be found in [FXT: file auxbit/greencode.h] The green code preserves the lowest set bit whilethe Gray code preserves the highest.Demonstration of Gray/green code and their inverses with different input words:---------------------------------------------------------111.1111....1111................

= 0xef0f0000 == word1..11...1...1...1............... = gray_code..11...1...1...1................ = green_code1.11.1.11111.1.11111111111111111 = inverse_gray_code1.1..1.1.....1.1................ = inverse_green_code---------------------------------------------------------...1....1111....1111111111111111 = 0x10f0ffff == word...11...1...1...1............... = gray_code..11...1...1...1...............1 = green_code...11111.1.11111.1.1.1.1.1.1.1.1 = inverse_gray_code1111.....1.1.....1.1.1.1.1.1.1.1 = inverse_green_code---------------------------------------------------------......1......................... = 0x2000000 == word......11........................

= gray_code.....11......................... = green_code......11111111111111111111111111 = inverse_gray_code1111111......................... = inverse_green_code---------------------------------------------------------111111.1111111111111111111111111 = 0xfdffffff == word1.....11........................ = gray_code.....11........................1 = green_code1.1.1..1.1.1.1.1.1.1.1.1.1.1.1.1 = inverse_gray_code1.1.1.11.1.1.1.1.1.1.1.1.1.1.1.1 = inverse_green_code----------------------------------------------------------The Gray codes of consecutive values change in one bit.

The Gray codes of the Gray codes of consecutivevalues change in one or two bits. The Gray codes of values that have a difference of two changes in two bit.Gray codes of even/odd values have an even/odd number of bits set, respectively. This is demonstratedin [FXT: file demo/gray2-demo.cc]:k:0:1:2:3:4:5:6:7:8:9:10:11:12:13:14:15:16:17:18:19:20:21:22:23:24:25:26:27:g(k).............1.....11.....1.....11.....111....1.1....1.....11.....11.1...1111...111....1.1....1.11...1..1...1.....11.....11..1..11.11..11.1...1111...11111..111.1..111....1.1....1.1.1..1.111..1.11.g(g(k)).............1.....1......11....1.1....1......111....11....1.1....1.11...1......1..1...1111...111....11.1...11....1.1....1.1.1..1.11...1.111..1...1..1......1..11..1..1...1111...11111..111....111.1g(2*k)............11....11.....1.1...11.....1111...1.1....1..1..11.....11.11..1111...111.1..1.1....1.111..1..1...1...1.11.....11..11.11.11..11.1.1.1111...111111.111.1..111..1.1.1....1.1.11.1.111..1.11.1g(2*k+1)......1.....1.....111....1.....11.1...111....1.11...1.....11..1..11.1...11111..111....1.1.1..1.11...1..11..1.....11...1.11..1..11.111.11.1...1111.1.11111..111.11.111....1.1..1.1.1.1..1.1111.1.11..CHAPTER 8.

SOME BIT WIZARDRY28:29:30:31:..1..1...1..11..1...1..1......11.11..11.1...11..1..11....1..1...1..111.1...1..1....1177.1..1.1.1..11..1...11.1.....In order two produce a random value with with even/odd many bits set, set the lowest bit of a randomnumber to zero/one and take the Gray code.8.13Generating minimal-change bit combinationsThe wonderfulstatic inline ulong igc_next_minchange_comb(ulong x)// Returns the inverse graycode of the next// combination in minchange order.// Input must be the inverse graycode of the// current combination.{ulong g = green_code(x);ulong i = 2;ulong cb; // ==candidateBits;do{ulong y = (x & ~(i-1)) + i;ulong j = lowest_bit(y) << 1;ulong h = !!(y & j);cb = ((j-h) ^ g) & (j-i);i = j;}while ( 0==cb );return x + lowest_bit(cb);}together withstatic inline ulong igc_last_comb(ulong k, ulong n)// return the (inverse graycode of the) last combination// as in igc_next_minchange_comb(){if ( 0==k ) return 0;else return ((1UL<<n) - 1) ^ (((1UL<<k) - 1) / 3);}could be used as demonstrated instatic inline ulong next_minchange_comb(ulong x, ulong last)// not efficient, just to explain the usage// of igc_next_minchange_comb()// Must have: last==igc_last_comb(k, n)//// Example with k==3, n==5://xinverse_gray_code(x)//..111..1.1 == first_sequency(k)//.11.1.1..1//.111..1.11//.1.11.11.1//11..11...1//11.1.1..11//111..1.111//1.1.111..1//1.11.11.11//1..11111.1 == igc_last_comb(k, n){x = inverse_gray_code(x);if ( x==last ) return 0;x = igc_next_minchange_comb(x);return gray_code(x);}CHAPTER 8.

SOME BIT WIZARDRY178Each combination is different from the preceding one in exactly two positions. The same run of bitcombinations could be obtained by going through the Gray codes and omitting all words where thebit-count is 6= k. The algorithm shown here, however, is much more efficient.For reasons of efficiency one may prefer code asulong last = igc_last_comb(k, n);ulong c, nc = first_sequency(k);do{c = nc;nc = igc_next_minchange_comb(c);ulong g = gray_code(c);// Here g contains the bitcombination}while ( c!=last );which avoids the repeated computation of the inverse Gray code.As Doug Moore explains [priv.comm.], the algorithm in igc next minchange comb uses the fact that thedifference of two (inverse gray codes of) successive combinations is always a power of two.

Using thisobservation one can derive a different version that checks the pattern of the change:static inline ulong igc_next_minchange_comb(ulong x)// Alternative version.// Amortized time = O(1).{ulong gx = gray_code( x );ulong y, i = 2;do{y = x + i;ulong gy = gray_code( y );ulong r = gx ^ gy;// Check that change consists of exactly one bit// of the new and one bit of the old pattern:if ( is_pow_of_2( r & gy ) && is_pow_of_2( r & gx ) ) break;// is_pow_of_2(x):=((x & -x) == x) returns 1 also for x==0.// But this cannot happen for both tests at the same timei <<= 1;}while ( 1 );return y;}Still another version which needs k, the number of set bits, as a second parameter:static inline ulong igc_next_minchange_comb(ulong x, ulong k)// Alternative version, uses the fact that the difference// of two successive x is the smallest possible power of 2.// Should be fast if the CPU has a bitcount instruction.// Amortized time = O(1).{ulong y, i = 2;do{y = x + i;i <<= 1;}while ( bit_count( gray_code(y) ) != k );return y;}The necessary modification for the generation of the previous combination is minimal:static inline ulong igc_prev_minchange_comb(ulong x, ulong k)// Returns the inverse graycode of the previous combination in minchange order.// Input must be the inverse graycode of the current combination.// Amortized time = O(1).// With input==first the output is the last for n=BITS_PER_LONG{CHAPTER 8.

Характеристики

Тип файла
PDF-файл
Размер
1,52 Mb
Тип материала
Учебное заведение
Неизвестно

Список файлов книги

Свежие статьи
Популярно сейчас
Как Вы думаете, сколько людей до Вас делали точно такое же задание? 99% студентов выполняют точно такие же задания, как и их предшественники год назад. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6276
Авторов
на СтудИзбе
315
Средний доход
с одного платного файла
Обучение Подробнее