代码如下:,

<?php
// sort array in a fixed order with given seed
function do_shuffle( $array, $seed ) {
    mt_srand( $seed );
    usort( $array, fn() => mt_rand( - 9, 9 ) );
    return $array;
}

// the reverse operation of do_shuffle
function undo_shuffle( $array, $seed ) {
    return $array; // to implement
}

$origin_array = str_split( 'olive tree' );

$seed = 20220502;

$shuffled_array = do_shuffle( $origin_array, $seed );
var_dump( $shuffled_array );

// undo shuffle
$origin_array = undo_shuffle( $shuffled_array, $seed );
var_dump( $origin_array );

如何实现数组洗牌及其反向操作?

如何将$shuffled_数组返回到$origin_数组?

推荐答案

关键思想是重新创建一个进程,但不是洗牌数组值,而是洗牌数组索引.这为我们提供了无序索引和原始索引之间的映射:

// the reverse operation of do_shuffle
function undo_shuffle( $array, $seed ) {
    mt_srand( $seed );

    $indices_map = range(0, count($array) - 1);

    // We do just the same shuffle operation but
    // shuffling array indices instead of values
    usort( $indices_map, function(){ 
      return mt_rand( - 9, 9 );
    } );

    // Restore original array using the map we've created
    $out = [];
    foreach( $indices_map as $shuffled_index => $original_index )
      $out[ $original_index ] = $array[ $shuffled_index ];

    // Sort our output by integer key
    ksort($out);

    return $out;
}

Php相关问答推荐

将一个数字分配到一系列因素中(就像贪婪算法)

输入手写CSV时在PHP中进行日期判断

make dd()如何正确工作?¨

未收到Strava WebHook事件数据

使用DOMPDF获取PDF格式的本 map 像

如果WooCommerce购物车在 checkout 时被清空,请重定向至store 页面

为什么WooCommerce的动作钩子';woocommerce_checkout_update_order_review';包含旧信息?

为WooCommerce中存储一些数据的购物车项目添加复选框

随机显示WordPress快捷代码功能时出现问题

API 平台 - UI 服务器端点定义

使用自定义插件中的 WooCommerce 模板发送自定义邮箱

添加产品标签以通过 WooCommerce 邮箱通知订购商品

安装 Herd 并返回 Valet 后为 502

在 WooCommerce 我的帐户自定义部分显示未购买的产品

根据WooCommerce中选定的变体重量更改输入数量步值

Laravel使用另一张表进行关联查询

ACF 更新字段功能不更新 WordPress 中的任何数据

使用 Eloquent 更新现有的外键值

在 DomPDF 和 Laravel 中使用内联 css

PHP 中的 curl 验证失败(openssh 连接正常)